@pkmn/engine 0.1.0-dev.84cc1a02 → 0.1.0-dev.942dbfa4

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 (45) hide show
  1. package/README.md +52 -24
  2. package/build/pkg/addon.d.ts +7 -0
  3. package/build/pkg/addon.js +111 -0
  4. package/build/pkg/addon.js.map +1 -0
  5. package/build/pkg/data/layout.json +1 -1
  6. package/build/pkg/data.d.ts +1 -2
  7. package/build/pkg/data.js +3 -5
  8. package/build/pkg/data.js.map +1 -1
  9. package/build/pkg/gen1.d.ts +5 -4
  10. package/build/pkg/gen1.js +43 -24
  11. package/build/pkg/gen1.js.map +1 -1
  12. package/build/pkg/index.d.ts +15 -12
  13. package/build/pkg/index.js.map +1 -1
  14. package/build/pkg/protocol.d.ts +4 -2
  15. package/build/pkg/protocol.js +4 -2
  16. package/build/pkg/protocol.js.map +1 -1
  17. package/build/test/display.js +400 -0
  18. package/build/test/display.js.map +1 -0
  19. package/build/tools/debug.js +133 -0
  20. package/build/tools/debug.js.map +1 -0
  21. package/build.zig +30 -39
  22. package/package.json +45 -34
  23. package/src/bin/install-pkmn-engine +47 -28
  24. package/src/bin/pkmn-debug +62 -0
  25. package/src/lib/binding/node.zig +7 -7
  26. package/src/lib/binding/wasm.zig +3 -3
  27. package/src/lib/common/data.zig +1 -1
  28. package/src/lib/common/debug.zig +1 -0
  29. package/src/lib/common/options.zig +3 -3
  30. package/src/lib/common/protocol.zig +140 -133
  31. package/src/lib/gen1/README.md +106 -70
  32. package/src/lib/gen1/data/moves.zig +10 -10
  33. package/src/lib/gen1/data/species.zig +2 -2
  34. package/src/lib/gen1/data/types.zig +2 -2
  35. package/src/lib/gen1/data.zig +32 -28
  36. package/src/lib/gen1/helpers.zig +6 -17
  37. package/src/lib/gen1/mechanics.zig +418 -325
  38. package/src/lib/gen2/data/items.zig +3 -3
  39. package/src/lib/gen2/data/moves.zig +1 -1
  40. package/src/lib/gen2/data/species.zig +1 -1
  41. package/src/lib/gen2/data/types.zig +3 -3
  42. package/src/lib/gen2/data.zig +12 -12
  43. package/src/lib/gen2/helpers.zig +3 -3
  44. package/src/lib/pkmn.zig +7 -7
  45. package/src/test/display/pkmn.html.tmpl +368 -0
package/build.zig CHANGED
@@ -1,13 +1,13 @@
1
1
  const std = @import("std");
2
2
  const builtin = @import("builtin");
3
3
 
4
- pub const Options = struct { showdown: ?bool = null, trace: ?bool = null };
4
+ pub const Options = struct { showdown: ?bool = null, log: ?bool = null };
5
5
 
6
6
  pub fn module(b: *std.Build, options: Options) *std.Build.Module {
7
7
  const dirname = comptime std.fs.path.dirname(@src().file) orelse ".";
8
8
  const build_options = b.addOptions();
9
9
  build_options.addOption(?bool, "showdown", options.showdown);
10
- build_options.addOption(?bool, "trace", options.trace);
10
+ build_options.addOption(?bool, "log", options.log);
11
11
  return b.createModule(.{
12
12
  .source_file = .{ .path = dirname ++ "/src/lib/pkmn.zig" },
13
13
  .dependencies = &.{.{ .name = "build_options", .module = build_options.createModule() }},
@@ -27,25 +27,25 @@ pub fn build(b: *std.Build) !void {
27
27
  const dynamic = b.option(bool, "dynamic", "Build a dynamic library") orelse false;
28
28
  const strip = b.option(bool, "strip", "Strip debugging symbols from binary") orelse false;
29
29
  const pic = b.option(bool, "pic", "Force position independent code") orelse false;
30
+ const emit_asm = b.option(bool, "emit-asm", "Output .s (assembly code)") orelse false;
30
31
 
31
- const cmd = b.findProgram(&[_][]const u8{"strip"}, &[_][]const u8{}) catch null;
32
+ const cmd = b.findProgram(&.{"strip"}, &.{}) catch null;
32
33
 
33
- var parser = std.json.Parser.init(b.allocator, false);
34
- defer parser.deinit();
35
- var tree = try parser.parse(@embedFile("package.json"));
36
- defer tree.deinit();
37
- const version = tree.root.Object.get("version").?.String;
38
- const description = tree.root.Object.get("description").?.String;
39
- var repository = std.mem.split(u8, tree.root.Object.get("repository").?.String, ":");
34
+ const json = @embedFile("package.json");
35
+ var parsed = try std.json.parseFromSlice(std.json.Value, b.allocator, json, .{});
36
+ defer parsed.deinit();
37
+ const version = parsed.value.object.get("version").?.string;
38
+ const description = parsed.value.object.get("description").?.string;
39
+ var repository = std.mem.split(u8, parsed.value.object.get("repository").?.string, ":");
40
40
  std.debug.assert(std.mem.eql(u8, repository.first(), "github"));
41
41
 
42
42
  const showdown =
43
43
  b.option(bool, "showdown", "Enable Pokémon Showdown compatibility mode") orelse false;
44
- const trace = b.option(bool, "trace", "Enable trace logs") orelse false;
44
+ const log = b.option(bool, "log", "Enable protocol message logging") orelse false;
45
45
 
46
46
  const options = b.addOptions();
47
47
  options.addOption(?bool, "showdown", showdown);
48
- options.addOption(?bool, "trace", trace);
48
+ options.addOption(?bool, "log", log);
49
49
 
50
50
  const name = if (showdown) "pkmn-showdown" else "pkmn";
51
51
 
@@ -72,14 +72,14 @@ pub fn build(b: *std.Build) !void {
72
72
  maybeStrip(b, lib, b.getInstallStep(), strip, cmd);
73
73
  if (pic) lib.force_pic = pic;
74
74
  // Always emit to build/lib because this is where the driver code expects to find it
75
- // TODO(ziglang/zig#2231): using the following used to work (though be hacky):
75
+ // TODO(ziglang/zig#2231): using the following used to work (though was hacky):
76
76
  //
77
77
  // lib.emit_bin = .{ .emit_to = b.fmt("build/lib/{s}", .{addon}) };
78
78
  // b.getInstallStep().dependOn(&lib.step);
79
79
  //
80
80
  // But ziglang/zig#14647 broke this so we now need to do an install() and then manually
81
81
  // rename the file ourself in install-pkmn-engine
82
- lib.install();
82
+ b.installArtifact(lib);
83
83
  } else if (wasm) {
84
84
  const lib = b.addSharedLibrary(.{
85
85
  .name = name,
@@ -96,24 +96,21 @@ pub fn build(b: *std.Build) !void {
96
96
  lib.rdynamic = true;
97
97
  lib.strip = strip;
98
98
  if (pic) lib.force_pic = pic;
99
- const opt = b.findProgram(
100
- &[_][]const u8{"wasm-opt"},
101
- &[_][]const u8{"./node_modules/.bin"},
102
- ) catch null;
99
+ const opt = b.findProgram(&.{"wasm-opt"}, &.{"./node_modules/.bin"}) catch null;
103
100
  if (optimize != .Debug and opt != null) {
104
101
  const out = b.fmt("build/lib/{s}.wasm", .{name});
105
- const sh = b.addSystemCommand(&[_][]const u8{ opt.?, "-O4" });
102
+ const sh = b.addSystemCommand(&.{ opt.?, "-O4" });
106
103
  sh.addArtifactArg(lib);
107
104
  sh.addArg("-o");
108
105
  sh.addFileSourceArg(.{ .path = out });
109
106
  b.getInstallStep().dependOn(&sh.step);
110
107
  }
111
- lib.install();
108
+ b.installArtifact(lib);
112
109
  } else if (dynamic) {
113
110
  const lib = b.addSharedLibrary(.{
114
111
  .name = name,
115
112
  .root_source_file = .{ .path = "src/lib/binding/c.zig" },
116
- .version = try std.builtin.Version.parse(version),
113
+ .version = try std.SemanticVersion.parse(version),
117
114
  .optimize = optimize,
118
115
  .target = target,
119
116
  });
@@ -122,7 +119,7 @@ pub fn build(b: *std.Build) !void {
122
119
  lib.addIncludePath("src/include");
123
120
  maybeStrip(b, lib, b.getInstallStep(), strip, cmd);
124
121
  if (pic) lib.force_pic = pic;
125
- lib.install();
122
+ b.installArtifact(lib);
126
123
  c = true;
127
124
  } else {
128
125
  const lib = b.addStaticLibrary(.{
@@ -137,7 +134,8 @@ pub fn build(b: *std.Build) !void {
137
134
  lib.bundle_compiler_rt = true;
138
135
  maybeStrip(b, lib, b.getInstallStep(), strip, cmd);
139
136
  if (pic) lib.force_pic = pic;
140
- lib.install();
137
+ if (emit_asm) lib.emit_asm = .emit;
138
+ b.installArtifact(lib);
141
139
  c = true;
142
140
  }
143
141
 
@@ -186,7 +184,7 @@ pub fn build(b: *std.Build) !void {
186
184
  .general = config,
187
185
  .tool = .{
188
186
  .showdown = showdown,
189
- .trace = trace,
187
+ .log = log,
190
188
  .tests = if (tests.build) tests else null,
191
189
  .exes = &exes,
192
190
  },
@@ -208,7 +206,7 @@ pub fn build(b: *std.Build) !void {
208
206
  const lint_exe =
209
207
  b.addExecutable(.{ .name = "lint", .root_source_file = .{ .path = "src/tools/lint.zig" } });
210
208
  if (tests.build) tests.step.dependOn(&lint_exe.step);
211
- const lint = lint_exe.run();
209
+ const lint = b.addRunArtifact(lint_exe);
212
210
 
213
211
  b.step("benchmark", "Run benchmark code").dependOn(&benchmark.step);
214
212
  b.step("fuzz", "Run fuzz tester").dependOn(&fuzz.step);
@@ -233,7 +231,7 @@ fn maybeStrip(
233
231
  if (mac and artifact.isDynamicLibrary()) return;
234
232
  // Assuming GNU strip, which complains "illegal pathname found in archive member"...
235
233
  if (!mac and artifact.isStaticLibrary()) return;
236
- const sh = b.addSystemCommand(&[_][]const u8{ cmd.?, if (mac) "-x" else "-s" });
234
+ const sh = b.addSystemCommand(&.{ cmd.?, if (mac) "-x" else "-s" });
237
235
  sh.addArtifactArg(artifact);
238
236
  step.dependOn(&sh.step);
239
237
  }
@@ -246,7 +244,7 @@ const Config = struct {
246
244
  cmd: ?[]const u8,
247
245
  };
248
246
 
249
- const TESTS = [_][]const u8{
247
+ const TESTS = .{
250
248
  "src/lib/common/test.zig",
251
249
  "src/lib/gen1/test.zig",
252
250
  "src/lib/gen2/test.zig",
@@ -259,11 +257,8 @@ const TestStep = struct {
259
257
  pub fn create(b: *std.Build, options: *std.Build.OptionsStep, config: Config) *TestStep {
260
258
  const coverage = b.option([]const u8, "test-coverage", "Generate test coverage");
261
259
  const test_file = b.option([]const u8, "test-file", "Input file for test");
262
- const test_bin = b.option([]const u8, "test-bin", "Emit test binary to");
263
260
  const test_filter =
264
261
  b.option([]const u8, "test-filter", "Skip tests that do not match filter");
265
- const test_no_exec =
266
- b.option(bool, "test-no-exec", "Compiles test binary without running it") orelse false;
267
262
 
268
263
  const self = b.allocator.create(TestStep) catch @panic("OOM");
269
264
  const step = std.Build.Step.init(.{ .id = .custom, .name = "Run all tests", .owner = b });
@@ -277,21 +272,17 @@ const TestStep = struct {
277
272
  .root_source_file = .{ .path = path },
278
273
  .optimize = config.optimize,
279
274
  .target = config.target,
275
+ .filter = test_filter,
280
276
  });
281
277
  tests.setMainPkgPath("./");
282
- tests.setFilter(test_filter);
283
278
  tests.addOptions("build_options", options);
284
279
  tests.single_threaded = true;
285
280
  maybeStrip(b, tests, &tests.step, config.strip, config.cmd);
286
281
  if (config.pic) tests.force_pic = config.pic;
287
- if (test_bin) |bin| {
288
- tests.name = std.fs.path.basename(bin);
289
- if (std.fs.path.dirname(bin)) |dir| tests.setOutputDir(dir);
290
- }
291
282
  if (coverage) |c| {
292
283
  tests.setExecCmd(&.{ "kcov", "--include-pattern=src/lib", c, null });
293
284
  }
294
- self.step.dependOn(if (test_no_exec) &tests.step else &tests.run().step);
285
+ self.step.dependOn(&b.addRunArtifact(tests).step);
295
286
  }
296
287
  return self;
297
288
  }
@@ -301,7 +292,7 @@ const ToolConfig = struct {
301
292
  general: Config,
302
293
  tool: struct {
303
294
  showdown: bool,
304
- trace: bool,
295
+ log: bool,
305
296
  tests: ?*TestStep,
306
297
  name: ?[]const u8 = null,
307
298
  exes: *std.ArrayList(*std.Build.CompileStep),
@@ -322,14 +313,14 @@ fn tool(b: *std.Build, path: []const u8, config: ToolConfig) *std.Build.RunStep
322
313
  });
323
314
  exe.addModule("pkmn", module(b, .{
324
315
  .showdown = config.tool.showdown,
325
- .trace = config.tool.trace,
316
+ .log = config.tool.log,
326
317
  }));
327
318
  exe.single_threaded = true;
328
319
  if (config.general.pic) exe.force_pic = config.general.pic;
329
320
  if (config.tool.tests) |ts| ts.step.dependOn(&exe.step);
330
321
  config.tool.exes.append(exe) catch @panic("OOM");
331
322
 
332
- const run = exe.run();
323
+ const run = b.addRunArtifact(exe);
333
324
  maybeStrip(b, exe, &run.step, config.general.strip, config.general.cmd);
334
325
  if (b.args) |args| run.addArgs(args);
335
326
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pkmn/engine",
3
- "version": "0.1.0-dev.84cc1a02",
3
+ "version": "0.1.0-dev.942dbfa4",
4
4
  "description": "A minimal, complete, Pokémon battle simulation engine optimized for performance",
5
5
  "repository": "github:pkmn/engine",
6
6
  "license": "MIT",
@@ -9,6 +9,28 @@
9
9
  "types": "build/pkg/index.d.ts",
10
10
  "files": [
11
11
  "build.zig",
12
+ "build/pkg/data.d.ts",
13
+ "build/pkg/data.js.map",
14
+ "build/pkg/addon.d.ts",
15
+ "build/pkg/addon.js.map",
16
+ "build/pkg/addon.js",
17
+ "build/pkg/data.js",
18
+ "build/pkg/data/ids.json",
19
+ "build/pkg/data/layout.json",
20
+ "build/pkg/data/protocol.json",
21
+ "build/pkg/gen1.d.ts",
22
+ "build/pkg/gen1.js.map",
23
+ "build/pkg/gen1.js",
24
+ "build/pkg/index.d.ts",
25
+ "build/pkg/index.js.map",
26
+ "build/pkg/index.js",
27
+ "build/pkg/protocol.d.ts",
28
+ "build/pkg/protocol.js.map",
29
+ "build/pkg/protocol.js",
30
+ "build/test/display.js.map",
31
+ "build/test/display.js",
32
+ "build/tools/debug.js.map",
33
+ "build/tools/debug.js",
12
34
  "src/bin/install-pkmn-engine",
13
35
  "src/lib/binding/node.zig",
14
36
  "src/lib/binding/wasm.zig",
@@ -17,78 +39,66 @@
17
39
  "src/lib/common/options.zig",
18
40
  "src/lib/common/protocol.zig",
19
41
  "src/lib/common/rng.zig",
42
+ "src/lib/gen1/data.zig",
20
43
  "src/lib/gen1/data/moves.zig",
21
44
  "src/lib/gen1/data/species.zig",
22
45
  "src/lib/gen1/data/types.zig",
23
- "src/lib/gen1/data.zig",
24
46
  "src/lib/gen1/helpers.zig",
25
47
  "src/lib/gen1/mechanics.zig",
48
+ "src/lib/gen2/data.zig",
26
49
  "src/lib/gen2/data/items.zig",
27
50
  "src/lib/gen2/data/moves.zig",
28
51
  "src/lib/gen2/data/species.zig",
29
52
  "src/lib/gen2/data/types.zig",
30
- "src/lib/gen2/data.zig",
31
53
  "src/lib/gen2/helpers.zig",
32
54
  "src/lib/gen2/mechanics.zig",
33
55
  "src/lib/pkmn.zig",
34
- "build/pkg/data/ids.json",
35
- "build/pkg/data/layout.json",
36
- "build/pkg/data/protocol.json",
37
- "build/pkg/data.d.ts",
38
- "build/pkg/data.js",
39
- "build/pkg/data.js.map",
40
- "build/pkg/gen1.d.ts",
41
- "build/pkg/gen1.js",
42
- "build/pkg/gen1.js.map",
43
- "build/pkg/index.d.ts",
44
- "build/pkg/index.js",
45
- "build/pkg/index.js.map",
46
- "build/pkg/protocol.d.ts",
47
- "build/pkg/protocol.js",
48
- "build/pkg/protocol.js.map"
56
+ "src/test/display/pkmn.html.tmpl"
49
57
  ],
50
58
  "engines": {
51
59
  "node": ">=16.0.0"
52
60
  },
53
61
  "bin": {
54
- "install-pkmn-engine": "src/bin/install-pkmn-engine"
62
+ "install-pkmn-engine": "src/bin/install-pkmn-engine",
63
+ "pkmn-debug": "src/bin/pkmn-debug"
55
64
  },
56
65
  "publishConfig": {
57
66
  "access": "public"
58
67
  },
59
68
  "dependencies": {
60
- "@pkmn/data": "^0.7.35",
61
- "@pkmn/protocol": "^0.6.11"
69
+ "@pkmn/data": "^0.7.43",
70
+ "@pkmn/protocol": "^0.6.12"
62
71
  },
63
72
  "devDependencies": {
64
- "@pkmn/eslint-config": "^3.0.0",
65
- "@pkmn/img": "^0.2.8",
73
+ "@pkmn/eslint-config": "^3.2.0",
74
+ "@pkmn/img": "^0.2.11",
66
75
  "@pkmn/sets": "^5.0.4",
67
- "@pkmn/sim": "0.7.35",
76
+ "@pkmn/sim": "0.7.43",
68
77
  "@types/html-minifier": "^4.0.2",
69
- "@types/jest": "^29.5.0",
78
+ "@types/jest": "^29.5.2",
70
79
  "@types/minimist": "^1.2.2",
71
80
  "@types/mustache": "^4.2.2",
72
- "@types/node": "^18.15.11",
73
- "@vitest/coverage-c8": "^0.29.8",
74
- "binaryen": "^112.0.0",
75
- "eslint": "^8.37.0",
81
+ "@types/node": "^20.3.1",
82
+ "@vitest/coverage-c8": "^0.32.2",
83
+ "binaryen": "^113.0.0",
84
+ "eslint": "^8.43.0",
76
85
  "html-minifier": "^4.0.0",
77
86
  "json-stringify-pretty-compact": "3.0.0",
78
87
  "minimist": "^1.2.8",
79
88
  "mustache": "^4.2.0",
80
89
  "source-map-support": "^0.5.21",
81
90
  "trakr": "^0.2.0",
82
- "typescript": "^5.0.3",
83
- "vitest": "^0.29.8"
91
+ "typescript": "^5.1.3",
92
+ "vitest": "^0.32.2"
84
93
  },
85
94
  "scripts": {
86
- "lint": "eslint --cache src --ext ts,js && eslint src/bin/install-pkmn-engine",
87
- "fix": "eslint --fix src --ext ts,js && eslint --fix src/bin/install-pkmn-engine",
95
+ "lint": "eslint --cache src --ext ts,js && eslint src/bin/*",
96
+ "fix": "eslint --fix src --ext ts,js && eslint --fix src/bin/*",
88
97
  "compile": "tsc -p .",
89
98
  "build": "npm run compile",
90
99
  "test": "vitest src/pkg",
91
100
  "test:integration": "vitest src/test",
101
+ "debug": "npm run compile && node build/tools/debug",
92
102
  "fuzz": "npm run compile && node build/test/fuzz",
93
103
  "generate": "npm run compile && node build/tools/generate",
94
104
  "release": "npm run compile && node build/tools/release",
@@ -151,7 +161,8 @@
151
161
  },
152
162
  {
153
163
  "files": [
154
- "src/test/*.test.ts"
164
+ "src/test/*.test.ts",
165
+ "src/test/regression/*.test.ts"
155
166
  ],
156
167
  "rules": {
157
168
  "jest/no-standalone-expect": "off"
@@ -10,13 +10,15 @@ const path = require('path');
10
10
  const {pipeline} = require('stream/promises');
11
11
  const tty = require('tty');
12
12
 
13
- const ZIG_VERSION = {major: 0, minor: 11, patch: 0, dev: 2168};
13
+ const ZIG_VERSION = {major: 0, minor: 11, patch: 0, dev: 3737};
14
14
  const DEV = ZIG_VERSION.dev ? `-dev.${ZIG_VERSION.dev}` : '';
15
15
  const VERSION = `${ZIG_VERSION.major}.${ZIG_VERSION.minor}.${ZIG_VERSION.patch}${DEV}`;
16
16
  const INDEX = 'https://ziglang.org/download/index.json';
17
17
  const ROOT = path.resolve(__dirname, '..', '..');
18
+ let SILENT = false;
18
19
 
19
20
  const sh = (cmd, args) => execFileSync(cmd, args, {encoding: 'utf8', cwd: ROOT});
21
+ const log = (...args) => { if (!SILENT) console.log(...args); };
20
22
 
21
23
  // This is hardly the browser fetch API, but it works for our primitive needs
22
24
  const fetch = url => new Promise((resolve, reject) => {
@@ -61,7 +63,7 @@ const unpack7 = (input, output) => new Promise((resolve, reject) => {
61
63
  require.resolve('7zip-min');
62
64
  } catch (err) {
63
65
  if (err.code !== 'MODULE_NOT_FOUND') throw err;
64
- console.log('Installing 7zip-min package locally to unpack the archive...');
66
+ log('Installing 7zip-min package locally to unpack the archive...');
65
67
  sh('npm', ['install', '7zip-min', '--no-audit', '--no-save']);
66
68
  }
67
69
 
@@ -83,7 +85,7 @@ const unpack = async (input, output) => {
83
85
  sh('tar', ['xf', input, '-C', output]);
84
86
  return;
85
87
  } catch {
86
- console.log('tar command not found, falling back to 7z');
88
+ log('tar command not found, falling back to 7z');
87
89
  }
88
90
  }
89
91
  // Try to use a 7z binary if we can, and only install 7zip-min as a last resort
@@ -120,10 +122,10 @@ const find = zig => {
120
122
  (!ZIG_VERSION.dev || (dev && dev >= ZIG_VERSION.dev)));
121
123
 
122
124
  if (compatible) {
123
- console.log('Found existing compatible Zig executable:', zig_exe);
125
+ log('Found existing compatible Zig executable:', zig_exe);
124
126
  return zig_exe;
125
127
  } else {
126
- console.log(`Existing Zig executable is not compatible (${version} < ${VERSION}):`, zig_exe);
128
+ log(`Existing Zig executable is not compatible (${version} < ${VERSION}):`, zig_exe);
127
129
  }
128
130
  } catch (err) {
129
131
  if (err.code !== 'ENOENT') throw err;
@@ -168,11 +170,11 @@ const install = async () => {
168
170
  let base = path.basename(url);
169
171
  const archive = path.join(dir, path.basename(url));
170
172
 
171
- console.log(`Downloading Zig tarball from ${url} to ${archive}`);
173
+ log(`Downloading Zig tarball from ${url} to ${archive}`);
172
174
  try {
173
175
  await download(url, archive, release.shasum);
174
176
 
175
- console.log(`Extracting tarball and installing to ${dir}`);
177
+ log(`Extracting tarball and installing to ${dir}`);
176
178
  await unpack(archive, dir);
177
179
  if (archive.endsWith('.zip')) {
178
180
  base = base.slice(0, -4);
@@ -187,17 +189,17 @@ const install = async () => {
187
189
  } catch (err) {
188
190
  if (err.code !== 'ENOENT') throw err;
189
191
  }
190
- console.log(`Zig${version === 'master' ? '' : ` v${version}`} executable:`, zig,
192
+ log(`Zig${version === 'master' ? '' : ` v${version}`} executable:`, zig,
191
193
  '(this version of Zig will be retained to speed up future updates)');
192
194
  const [pre, post] = tty.isatty(1) ? ['\x1b[1m\x1b[35m', '\x1b[0m'] : ['', ''];
193
- console.log(
195
+ log(
194
196
  `${pre}Consider moving the ${path.dirname(zig)} directory and adding it to your PATH`,
195
197
  `to use Zig on other projects, or delete this if you wish to save space.${post}`
196
198
  );
197
199
 
198
200
  return zig;
199
201
  } finally {
200
- console.log(`Cleaning up ${archive}`);
202
+ log(`Cleaning up ${archive}`);
201
203
  try { fs.rmSync(archive); } catch {}
202
204
  }
203
205
  };
@@ -206,17 +208,17 @@ const install = async () => {
206
208
  const downloadHeaders = async () => {
207
209
  const include = path.resolve(process.execPath, '..', '..', 'include', 'node');
208
210
  if (fs.existsSync(path.join(include, 'node.h'))) {
209
- console.log('Node headers:', include);
211
+ log('Node headers:', include);
210
212
  return include;
211
213
  }
212
214
 
213
215
  const dir = path.join(ROOT, 'build', 'include');
214
216
  const dest = path.join(dir, 'node');
215
217
  if (fs.existsSync(path.join(dest, 'node.h'))) {
216
- console.log('Node headers:', dest);
218
+ log('Node headers:', dest);
217
219
  return dest;
218
220
  } else {
219
- console.log(`Could not find Node headers at ${include}, downloading...`);
221
+ log(`Could not find Node headers at ${include}, downloading...`);
220
222
  }
221
223
 
222
224
  try {
@@ -229,14 +231,14 @@ const downloadHeaders = async () => {
229
231
  const targz = path.join(dir, path.basename(url));
230
232
  const unpacked = path.join(dir, `node-${process.version}`, 'include');
231
233
 
232
- console.log(`Downloading Node headers from ${url} to ${targz}`);
234
+ log(`Downloading Node headers from ${url} to ${targz}`);
233
235
 
234
236
  try {
235
237
  await download(url, targz);
236
238
  await unpack(targz, dir);
237
239
  fs.renameSync(path.join(unpacked, 'node'), dest);
238
240
 
239
- console.log('Node headers:', dest);
241
+ log('Node headers:', dest);
240
242
 
241
243
  return dest;
242
244
  } finally {
@@ -248,7 +250,7 @@ const downloadHeaders = async () => {
248
250
  const downloadImportLib = async () => {
249
251
  const library = path.resolve(process.execPath, '..', 'node.lib');
250
252
  if (fs.existsSync(path.join(library, 'node.h'))) {
251
- console.log('Node import library:', library);
253
+ log('Node import library:', library);
252
254
  return library;
253
255
  }
254
256
 
@@ -256,10 +258,10 @@ const downloadImportLib = async () => {
256
258
  const url = new URL('./win-x64/node.lib', process.release.headersUrl).href;
257
259
  const dest = path.join(dir, path.basename(url));
258
260
  if (fs.existsSync(path.join(dest))) {
259
- console.log('Node import library:', dest);
261
+ log('Node import library:', dest);
260
262
  return dest;
261
263
  } else {
262
- console.log(`Could not find Node import library at ${library}, downloading...`);
264
+ log(`Could not find Node import library at ${library}, downloading...`);
263
265
  }
264
266
 
265
267
  try {
@@ -268,24 +270,41 @@ const downloadImportLib = async () => {
268
270
  if (err.code !== 'EEXIST') throw err;
269
271
  }
270
272
 
271
- console.log(`Downloading Node import library from ${url} to ${dest}`);
273
+ log(`Downloading Node import library from ${url} to ${dest}`);
272
274
  await download(url, dest);
273
- console.log('Node import library:', dest);
275
+ log('Node import library:', dest);
274
276
 
275
277
  return dest;
276
278
  };
277
279
 
278
280
  (async () => {
279
- const options = (process.argv[2] || '').startsWith('--options=')
280
- ? process.argv[2].slice(10).split(' ') : undefined;
281
- if (process.argv.length > 3 ||
282
- process.argv.length === 3 && !(process.argv[2] === '--zig' || options)) {
281
+ let only = false;
282
+ let options = undefined;
283
+ let error = false;
284
+ for (let i = 2; i < process.argv.length; i++) {
285
+ switch (process.argv[i]) {
286
+ case "--silent": {
287
+ SILENT = true;
288
+ break;
289
+ }
290
+ case "--zig": {
291
+ if (options || only) error = true;
292
+ only = true;
293
+ break;
294
+ }
295
+ default: {
296
+ if (options || only || !process.argv[i].startsWith('--options=')) error = true;
297
+ options = process.argv[i].slice(10).split(' ');
298
+ }
299
+ }
300
+ }
301
+ if (error) {
283
302
  console.error('Invalid arguments');
284
303
  process.exit(1);
285
304
  }
286
305
 
287
306
  const zig = await install();
288
- if (process.argv[2] === '--zig') process.exit(0);
307
+ if (only) process.exit(0);
289
308
 
290
309
  let tmp;
291
310
  try {
@@ -318,13 +337,13 @@ const downloadImportLib = async () => {
318
337
  if (!options) {
319
338
  const addon = require(copy);
320
339
  if (addon.options.showdown) opts.push('-Dshowdown');
321
- if (addon.options.trace) opts.push('-Dtrace');
340
+ if (addon.options.log) opts.push('-Dlog');
322
341
  }
323
342
  } else if (!options) {
324
343
  const addon = await WebAssembly.instantiate(fs.readFileSync(copy));
325
344
  const values = new Uint8Array(addon.instance.exports.memory.buffer);
326
345
  if (values[addon.instance.exports.SHOWDOWN.value]) opts.push('-Dshowdown');
327
- if (values[addon.instance.exports.TRACE.value]) opts.push('-Dtrace');
346
+ if (values[addon.instance.exports.LOG.value]) opts.push('-Dlog');
328
347
  }
329
348
  const key = `${type} ${opts.sort().join(' ')}`;
330
349
  if (!configs.has(key)) configs.set(key, {type, options: opts});
@@ -355,7 +374,7 @@ const downloadImportLib = async () => {
355
374
  opts.includes('-Dshowdown') || opts.includes('-Dshowdown=true') ? '-showdown' : '';
356
375
  const flags = opts.length ? ` (${opts.join(' ')})` : '';
357
376
  const artifact = path.join('build', 'lib', `pkmn${suffix}.${config.type}`);
358
- console.log(`Building ${artifact}${flags}`);
377
+ log(`Building ${artifact}${flags}`);
359
378
  sh(zig, args);
360
379
  // TODO: ziglang/zig#14647 broke emit_to so we get to rename the file ourselves...
361
380
  if (config.type === 'node') {
@@ -0,0 +1,62 @@
1
+ #!/usr/bin/env node
2
+ 'use strict';
3
+
4
+ try {
5
+ require('source-map-support').install();
6
+ } catch (err) {
7
+ if (err.code !== 'MODULE_NOT_FOUND') throw err;
8
+ }
9
+
10
+ const {execFileSync} = require('child_process');
11
+ const {readFileSync} = require('fs');
12
+ const {join, resolve} = require('path');
13
+
14
+ const ROOT = resolve(__dirname, '..', '..');
15
+ const packageJSON = JSON.parse(readFileSync(join(ROOT, 'package.json'), 'utf8'));
16
+
17
+ const missing = [];
18
+ for (const dep of ['@pkmn/img', 'html-minifier', 'mustache']) {
19
+ try {
20
+ require.resolve(dep);
21
+ } catch (e) {
22
+ if (e.code !== 'MODULE_NOT_FOUND') throw e;
23
+ missing.push(`${dep}@${packageJSON.devDependencies[dep]}`);
24
+ }
25
+ }
26
+
27
+ let Dex = undefined;
28
+ try {
29
+ Dex = require('@pkmn/sim').Dex;
30
+ } catch (err) {
31
+ if (err.code !== 'MODULE_NOT_FOUND') throw err;
32
+ try {
33
+ Dex = require('@pkmn/dex').Dex;
34
+ } catch (e) {
35
+ if (e.code !== 'MODULE_NOT_FOUND') throw e;
36
+ missing.push(`@pkmn/dex@${packageJSON.dependencies['@pkmn/data']}`);
37
+ }
38
+ }
39
+
40
+ if (missing.length) {
41
+ if (+/^v(\d+)/.exec(process.version)[1] < 16) {
42
+ console.error('pkmn-debug requires Node v16+');
43
+ process.exit(1);
44
+ }
45
+
46
+ execFileSync('npm', ['install', ...missing, '--global'], {encoding: 'utf8'});
47
+
48
+ const node_modules = execFileSync('npm', ['root', '--global'], {encoding: 'utf8'}).trim();
49
+ if (!process.env.NODE_PATH || !process.env.NODE_PATH.includes(node_modules)) {
50
+ console.error(`NODE_PATH must include npm's global node_modules directory: '${node_modules}'`);
51
+ process.exit(1);
52
+ }
53
+ }
54
+
55
+ const {Generations} = require('@pkmn/data');
56
+
57
+ const {run} = require('../../build/tools/debug');
58
+
59
+ run(new Generations(Dex)).catch(err => {
60
+ console.error(err.message);
61
+ process.exit(1);
62
+ });