@pkmn/engine 0.1.0-dev.84cc1a02 → 0.1.0-dev.93b7cb0d

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.
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,26 @@ 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
+ var parser = std.json.Parser.init(b.allocator, .alloc_if_needed);
34
35
  defer parser.deinit();
35
36
  var tree = try parser.parse(@embedFile("package.json"));
36
37
  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, ":");
38
+ const version = tree.root.object.get("version").?.string;
39
+ const description = tree.root.object.get("description").?.string;
40
+ var repository = std.mem.split(u8, tree.root.object.get("repository").?.string, ":");
40
41
  std.debug.assert(std.mem.eql(u8, repository.first(), "github"));
41
42
 
42
43
  const showdown =
43
44
  b.option(bool, "showdown", "Enable Pokémon Showdown compatibility mode") orelse false;
44
- const trace = b.option(bool, "trace", "Enable trace logs") orelse false;
45
+ const log = b.option(bool, "log", "Enable protocol message logging") orelse false;
45
46
 
46
47
  const options = b.addOptions();
47
48
  options.addOption(?bool, "showdown", showdown);
48
- options.addOption(?bool, "trace", trace);
49
+ options.addOption(?bool, "log", log);
49
50
 
50
51
  const name = if (showdown) "pkmn-showdown" else "pkmn";
51
52
 
@@ -72,14 +73,14 @@ pub fn build(b: *std.Build) !void {
72
73
  maybeStrip(b, lib, b.getInstallStep(), strip, cmd);
73
74
  if (pic) lib.force_pic = pic;
74
75
  // 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):
76
+ // TODO(ziglang/zig#2231): using the following used to work (though was hacky):
76
77
  //
77
78
  // lib.emit_bin = .{ .emit_to = b.fmt("build/lib/{s}", .{addon}) };
78
79
  // b.getInstallStep().dependOn(&lib.step);
79
80
  //
80
81
  // But ziglang/zig#14647 broke this so we now need to do an install() and then manually
81
82
  // rename the file ourself in install-pkmn-engine
82
- lib.install();
83
+ b.installArtifact(lib);
83
84
  } else if (wasm) {
84
85
  const lib = b.addSharedLibrary(.{
85
86
  .name = name,
@@ -96,19 +97,16 @@ pub fn build(b: *std.Build) !void {
96
97
  lib.rdynamic = true;
97
98
  lib.strip = strip;
98
99
  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;
100
+ const opt = b.findProgram(&.{"wasm-opt"}, &.{"./node_modules/.bin"}) catch null;
103
101
  if (optimize != .Debug and opt != null) {
104
102
  const out = b.fmt("build/lib/{s}.wasm", .{name});
105
- const sh = b.addSystemCommand(&[_][]const u8{ opt.?, "-O4" });
103
+ const sh = b.addSystemCommand(&.{ opt.?, "-O4" });
106
104
  sh.addArtifactArg(lib);
107
105
  sh.addArg("-o");
108
106
  sh.addFileSourceArg(.{ .path = out });
109
107
  b.getInstallStep().dependOn(&sh.step);
110
108
  }
111
- lib.install();
109
+ b.installArtifact(lib);
112
110
  } else if (dynamic) {
113
111
  const lib = b.addSharedLibrary(.{
114
112
  .name = name,
@@ -122,7 +120,7 @@ pub fn build(b: *std.Build) !void {
122
120
  lib.addIncludePath("src/include");
123
121
  maybeStrip(b, lib, b.getInstallStep(), strip, cmd);
124
122
  if (pic) lib.force_pic = pic;
125
- lib.install();
123
+ b.installArtifact(lib);
126
124
  c = true;
127
125
  } else {
128
126
  const lib = b.addStaticLibrary(.{
@@ -137,7 +135,8 @@ pub fn build(b: *std.Build) !void {
137
135
  lib.bundle_compiler_rt = true;
138
136
  maybeStrip(b, lib, b.getInstallStep(), strip, cmd);
139
137
  if (pic) lib.force_pic = pic;
140
- lib.install();
138
+ if (emit_asm) lib.emit_asm = .emit;
139
+ b.installArtifact(lib);
141
140
  c = true;
142
141
  }
143
142
 
@@ -186,7 +185,7 @@ pub fn build(b: *std.Build) !void {
186
185
  .general = config,
187
186
  .tool = .{
188
187
  .showdown = showdown,
189
- .trace = trace,
188
+ .log = log,
190
189
  .tests = if (tests.build) tests else null,
191
190
  .exes = &exes,
192
191
  },
@@ -208,7 +207,7 @@ pub fn build(b: *std.Build) !void {
208
207
  const lint_exe =
209
208
  b.addExecutable(.{ .name = "lint", .root_source_file = .{ .path = "src/tools/lint.zig" } });
210
209
  if (tests.build) tests.step.dependOn(&lint_exe.step);
211
- const lint = lint_exe.run();
210
+ const lint = b.addRunArtifact(lint_exe);
212
211
 
213
212
  b.step("benchmark", "Run benchmark code").dependOn(&benchmark.step);
214
213
  b.step("fuzz", "Run fuzz tester").dependOn(&fuzz.step);
@@ -233,7 +232,7 @@ fn maybeStrip(
233
232
  if (mac and artifact.isDynamicLibrary()) return;
234
233
  // Assuming GNU strip, which complains "illegal pathname found in archive member"...
235
234
  if (!mac and artifact.isStaticLibrary()) return;
236
- const sh = b.addSystemCommand(&[_][]const u8{ cmd.?, if (mac) "-x" else "-s" });
235
+ const sh = b.addSystemCommand(&.{ cmd.?, if (mac) "-x" else "-s" });
237
236
  sh.addArtifactArg(artifact);
238
237
  step.dependOn(&sh.step);
239
238
  }
@@ -246,7 +245,7 @@ const Config = struct {
246
245
  cmd: ?[]const u8,
247
246
  };
248
247
 
249
- const TESTS = [_][]const u8{
248
+ const TESTS = .{
250
249
  "src/lib/common/test.zig",
251
250
  "src/lib/gen1/test.zig",
252
251
  "src/lib/gen2/test.zig",
@@ -259,11 +258,8 @@ const TestStep = struct {
259
258
  pub fn create(b: *std.Build, options: *std.Build.OptionsStep, config: Config) *TestStep {
260
259
  const coverage = b.option([]const u8, "test-coverage", "Generate test coverage");
261
260
  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
261
  const test_filter =
264
262
  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
263
 
268
264
  const self = b.allocator.create(TestStep) catch @panic("OOM");
269
265
  const step = std.Build.Step.init(.{ .id = .custom, .name = "Run all tests", .owner = b });
@@ -277,21 +273,17 @@ const TestStep = struct {
277
273
  .root_source_file = .{ .path = path },
278
274
  .optimize = config.optimize,
279
275
  .target = config.target,
276
+ .filter = test_filter,
280
277
  });
281
278
  tests.setMainPkgPath("./");
282
- tests.setFilter(test_filter);
283
279
  tests.addOptions("build_options", options);
284
280
  tests.single_threaded = true;
285
281
  maybeStrip(b, tests, &tests.step, config.strip, config.cmd);
286
282
  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
283
  if (coverage) |c| {
292
284
  tests.setExecCmd(&.{ "kcov", "--include-pattern=src/lib", c, null });
293
285
  }
294
- self.step.dependOn(if (test_no_exec) &tests.step else &tests.run().step);
286
+ self.step.dependOn(&b.addRunArtifact(tests).step);
295
287
  }
296
288
  return self;
297
289
  }
@@ -301,7 +293,7 @@ const ToolConfig = struct {
301
293
  general: Config,
302
294
  tool: struct {
303
295
  showdown: bool,
304
- trace: bool,
296
+ log: bool,
305
297
  tests: ?*TestStep,
306
298
  name: ?[]const u8 = null,
307
299
  exes: *std.ArrayList(*std.Build.CompileStep),
@@ -322,14 +314,14 @@ fn tool(b: *std.Build, path: []const u8, config: ToolConfig) *std.Build.RunStep
322
314
  });
323
315
  exe.addModule("pkmn", module(b, .{
324
316
  .showdown = config.tool.showdown,
325
- .trace = config.tool.trace,
317
+ .log = config.tool.log,
326
318
  }));
327
319
  exe.single_threaded = true;
328
320
  if (config.general.pic) exe.force_pic = config.general.pic;
329
321
  if (config.tool.tests) |ts| ts.step.dependOn(&exe.step);
330
322
  config.tool.exes.append(exe) catch @panic("OOM");
331
323
 
332
- const run = exe.run();
324
+ const run = b.addRunArtifact(exe);
333
325
  maybeStrip(b, exe, &run.step, config.general.strip, config.general.cmd);
334
326
  if (b.args) |args| run.addArgs(args);
335
327
 
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.93b7cb0d",
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",
69
+ "@pkmn/data": "^0.7.38",
61
70
  "@pkmn/protocol": "^0.6.11"
62
71
  },
63
72
  "devDependencies": {
64
73
  "@pkmn/eslint-config": "^3.0.0",
65
74
  "@pkmn/img": "^0.2.8",
66
75
  "@pkmn/sets": "^5.0.4",
67
- "@pkmn/sim": "0.7.35",
76
+ "@pkmn/sim": "0.7.38",
68
77
  "@types/html-minifier": "^4.0.2",
69
78
  "@types/jest": "^29.5.0",
70
79
  "@types/minimist": "^1.2.2",
71
80
  "@types/mustache": "^4.2.2",
72
81
  "@types/node": "^18.15.11",
73
- "@vitest/coverage-c8": "^0.29.8",
82
+ "@vitest/coverage-c8": "^0.30.1",
74
83
  "binaryen": "^112.0.0",
75
- "eslint": "^8.37.0",
84
+ "eslint": "^8.38.0",
76
85
  "html-minifier": "^4.0.0",
77
- "json-stringify-pretty-compact": "3.0.0",
86
+ "json-stringify-pretty-compact": "4.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.0.4",
92
+ "vitest": "^0.30.1"
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: 3191};
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
+ });
@@ -21,7 +21,7 @@ fn options(env: c.napi_env) c.napi_value {
21
21
  var object = Object.init(env);
22
22
  const properties = [_]c.napi_property_descriptor{
23
23
  Property.init("showdown", .{ .value = Boolean.init(env, pkmn.options.showdown) }),
24
- Property.init("trace", .{ .value = Boolean.init(env, pkmn.options.trace) }),
24
+ Property.init("log", .{ .value = Boolean.init(env, pkmn.options.log) }),
25
25
  };
26
26
  assert(c.napi_define_properties(env, object, properties.len, &properties) == c.napi_ok);
27
27
  return object;
@@ -34,11 +34,11 @@ fn bindings(env: c.napi_env) c.napi_value {
34
34
  }
35
35
 
36
36
  fn bind(env: c.napi_env, gen: anytype) c.napi_value {
37
- const options_size = @intCast(u32, gen.OPTIONS_SIZE);
37
+ const choices_size = @intCast(u32, gen.CHOICES_SIZE);
38
38
  const logs_size = @intCast(u32, gen.LOGS_SIZE);
39
39
  var object = Object.init(env);
40
40
  const properties = [_]c.napi_property_descriptor{
41
- Property.init("OPTIONS_SIZE", .{ .value = Number.init(env, options_size) }),
41
+ Property.init("CHOICES_SIZE", .{ .value = Number.init(env, choices_size) }),
42
42
  Property.init("LOGS_SIZE", .{ .value = Number.init(env, logs_size) }),
43
43
  Property.init("update", .{ .method = update(gen) }),
44
44
  Property.init("choices", .{ .method = choices(gen) }),
@@ -108,10 +108,10 @@ fn choices(gen: anytype) c.napi_callback {
108
108
  const request = @intToEnum(pkmn.Choice.Type, Number.get(env, argv[2], u8));
109
109
 
110
110
  assert(c.napi_get_arraybuffer_info(env, argv[3], &data, &len) == c.napi_ok);
111
- assert(len == gen.OPTIONS_SIZE);
111
+ assert(len == gen.CHOICES_SIZE);
112
112
  assert(data != null);
113
113
 
114
- var out = @ptrCast([*]pkmn.Choice, data.?)[0..gen.OPTIONS_SIZE];
114
+ var out = @ptrCast([*]pkmn.Choice, data.?)[0..gen.CHOICES_SIZE];
115
115
  const n = battle.choices(player, request, out);
116
116
  return Number.init(env, @bitCast(u8, n));
117
117
  }
@@ -2,9 +2,9 @@ const std = @import("std");
2
2
  const pkmn = @import("../pkmn.zig");
3
3
 
4
4
  export const SHOWDOWN = pkmn.options.showdown;
5
- export const TRACE = pkmn.options.trace;
5
+ export const LOG = pkmn.options.log;
6
6
 
7
- export const GEN1_OPTIONS_SIZE =
8
- std.math.ceilPowerOfTwo(u32, @intCast(u32, pkmn.gen1.OPTIONS_SIZE)) catch unreachable;
7
+ export const GEN1_CHOICES_SIZE =
8
+ std.math.ceilPowerOfTwo(u32, @intCast(u32, pkmn.gen1.CHOICES_SIZE)) catch unreachable;
9
9
  export const GEN1_LOGS_SIZE =
10
10
  std.math.ceilPowerOfTwo(u32, @intCast(u32, pkmn.gen1.LOGS_SIZE)) catch unreachable;