@ratatoskr.io/plugin-tools 0.0.0-stage → 0.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Asgard
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,21 @@
1
- # Temporary Holding Version
1
+ # @ratatoskr.io/plugin-tools
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Builds [Wraith](https://wraith.io) plugins written in TypeScript or JavaScript. New plugins made with `npm create @ratatoskr.io/plugin` already use it.
4
+
5
+ ```
6
+ wraith-plugin build typings, type check and bundle, into dist/
7
+ wraith-plugin dev build again on every change. Run `wraith dev add dist` once so Wraith loads it
8
+ wraith-plugin pack build, and zip it for the Wraith Hub
9
+ wraith-plugin types only the typings, in .wraith/types, for your editor
10
+ wraith-plugin wraith which Wraith it builds against
11
+ ```
12
+
13
+ The typings come from the Wraith it finds: `WRAITH` (its `wraith.exe` or folder), the Wraith app's install, or `PATH`. Without one, it downloads the latest release.
14
+
15
+ See [Setting up](https://docs.wraith.io/plugins/js/setup/) and [Sharing](https://docs.wraith.io/plugins/js/sharing/) in the docs.
16
+
17
+ Wraith runs on Windows, so plugins build there.
18
+
19
+ ## License
20
+
21
+ MIT, see [LICENSE](LICENSE).
@@ -0,0 +1,74 @@
1
+ #!/usr/bin/env node
2
+ // `wraith-plugin` builds a JS or TS Wraith plugin.
3
+
4
+ import { findWraith } from "../lib/wraith.js";
5
+ import { loadProject } from "../lib/project.js";
6
+ import { build, dev, pack, types } from "../lib/build.js";
7
+
8
+ const usage = `Usage: wraith-plugin <command>
9
+ Commands:
10
+ build [--no-check] typings, type check and bundle, into dist/
11
+ dev build into dist/, and again on every change. Run
12
+ \`wraith dev add dist\` once so Wraith loads it from there
13
+ pack [--no-check] build, and zip it for the Wraith Hub (<name>-<version>.zip)
14
+ types only the typings (.wraith/types): for the editor
15
+ wraith which Wraith it builds against
16
+
17
+ Wraith is found from WRAITH (its wraith.exe, or folder), the Wraith app's install, or
18
+ PATH, else the latest release is downloaded (WRAITH_DIST_URL).`;
19
+
20
+ const log = (message) => console.error(message);
21
+
22
+ async function main(argv) {
23
+ const [command, ...rest] = argv;
24
+ const flag = (name) => rest.includes(name);
25
+ if (!command || command === "help" || command === "--help") {
26
+ console.log(usage);
27
+ return 0;
28
+ }
29
+ if (!["build", "dev", "pack", "types", "wraith"].includes(command)) {
30
+ console.error(usage);
31
+ return 1;
32
+ }
33
+ const wraith = await findWraith({ log });
34
+ if (command === "wraith") {
35
+ console.log(`Wraith ${wraith.version}: ${wraith.exe} (from ${wraith.source})\nMods folder: ${wraith.modsDir}`);
36
+ return 0;
37
+ }
38
+ const project = loadProject(process.cwd());
39
+ switch (command) {
40
+ case "types":
41
+ types(project, wraith);
42
+ break;
43
+ case "build":
44
+ await build(project, wraith, { check: !flag("--no-check"), log });
45
+ break;
46
+ case "pack": {
47
+ const { file, sha256 } = await pack(project, wraith, { check: !flag("--no-check"), log });
48
+ console.log(`${file}\nsha256: ${sha256}\n\nFor the registry (plugins/${project.name}.json), once it's uploaded:\n` +
49
+ JSON.stringify({ versions: [{ url: "<where it's uploaded>", sha256 }] }, null, 2));
50
+ break;
51
+ }
52
+ case "dev": {
53
+ const session = await dev(project, wraith, { log });
54
+ const stop = async () => {
55
+ await session.stop();
56
+ process.exit(0);
57
+ };
58
+ process.on("SIGINT", stop);
59
+ process.on("SIGTERM", stop);
60
+ return null;
61
+ }
62
+ }
63
+ return 0;
64
+ }
65
+
66
+ main(process.argv.slice(2)).then(
67
+ (code) => {
68
+ if (code !== null) process.exitCode = code;
69
+ },
70
+ (e) => {
71
+ console.error(e.message);
72
+ process.exitCode = 1;
73
+ },
74
+ );
package/lib/build.js ADDED
@@ -0,0 +1,166 @@
1
+ // Builds a plugin project into dist/, the folder Wraith loads.
2
+
3
+ import { execFileSync } from "node:child_process";
4
+ import { createHash } from "node:crypto";
5
+ import { cpSync, existsSync, mkdirSync, readFileSync, readdirSync, rmSync, statSync, watch, writeFileSync } from "node:fs";
6
+ import { createRequire } from "node:module";
7
+ import { join, relative } from "node:path";
8
+ import * as esbuild from "esbuild";
9
+ import { compareVersions, isDevVersion, sdk } from "./wraith.js";
10
+ import { zip } from "./zip.js";
11
+
12
+ export const typesDir = ".wraith/types";
13
+ /** The game's types, which Wraith reads from the plugin's folder as the `schema` module. */
14
+ export const schemasDir = "schemas";
15
+
16
+
17
+ /**
18
+ * @param {import("./project.js").Project} project
19
+ * @param {import("./wraith.js").Wraith} wraith
20
+ */
21
+ export function types(project, wraith) {
22
+ rmSync(join(project.root, typesDir), { recursive: true, force: true });
23
+ // It reads schemas/ itself
24
+ sdk(wraith, ["js", "types", "--out", typesDir, "--pointer-size", String(project.pointerSize)], project.root);
25
+ }
26
+
27
+ /** False if there's no TypeScript. Throws on type errors. */
28
+ export function check(project) {
29
+ let tsc;
30
+ try {
31
+ const require = createRequire(join(project.root, "package.json"));
32
+ const pkgPath = require.resolve("typescript/package.json");
33
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf8"));
34
+ const bin = typeof pkg.bin === "string" ? pkg.bin : pkg.bin?.tsc;
35
+ tsc = join(pkgPath, "..", bin);
36
+ } catch {
37
+ return false;
38
+ }
39
+ try {
40
+ execFileSync(process.execPath, [tsc, "--noEmit", "-p", project.root], { cwd: project.root, stdio: "inherit" });
41
+ } catch {
42
+ throw new Error("Type errors (above)");
43
+ }
44
+ return true;
45
+ }
46
+
47
+ function bundleOptions(project) {
48
+ return {
49
+ absWorkingDir: project.root,
50
+ entryPoints: [project.entry],
51
+ outfile: join(project.outDir, "main.js"),
52
+ bundle: true,
53
+ format: "esm",
54
+ // quickjs-ng runs ES2023. No Node or DOM
55
+ platform: "neutral",
56
+ target: "es2023",
57
+ mainFields: ["module", "main"],
58
+ // Wraith gives these
59
+ external: ["wraith", "schema", "salamander"],
60
+ logLevel: "warning",
61
+ };
62
+ }
63
+
64
+ function copyFiles(project) {
65
+ const out = join(project.root, project.outDir);
66
+ mkdirSync(out, { recursive: true });
67
+ cpSync(join(project.root, project.manifestFile), join(out, project.manifestFile));
68
+ const schemas = join(project.root, schemasDir);
69
+ if (existsSync(schemas)) {
70
+ cpSync(schemas, join(out, schemasDir), { recursive: true, filter: (src) => statSync(src).isDirectory() || src.endsWith(".sal") });
71
+ }
72
+ const pub = join(project.root, project.public);
73
+ if (existsSync(pub)) cpSync(pub, out, { recursive: true });
74
+ }
75
+
76
+ /**
77
+ * @param {import("./project.js").Project} project
78
+ * @param {import("./wraith.js").Wraith} wraith
79
+ * @param {{ check?: boolean, log?: (message: string) => void }} [options]
80
+ */
81
+ export async function build(project, wraith, options = {}) {
82
+ const log = options.log ?? (() => {});
83
+ warnIfTooOld(project, wraith, log);
84
+ types(project, wraith);
85
+ if (options.check !== false && !check(project)) log("No TypeScript in the project: not type-checked");
86
+ rmSync(join(project.root, project.outDir), { recursive: true, force: true });
87
+ await esbuild.build(bundleOptions(project));
88
+ copyFiles(project);
89
+ log(`Built ${project.name} in ${project.outDir}`);
90
+ }
91
+
92
+ function warnIfTooOld(project, wraith, log) {
93
+ const needs = project.manifest.wraith;
94
+ if (needs && !isDevVersion(wraith.version) && compareVersions(wraith.version, needs) < 0) {
95
+ log(`Warning: ${project.manifestFile} says it needs Wraith ${needs}, but this is ${wraith.version} (${wraith.exe}): it won't load it`);
96
+ }
97
+ }
98
+
99
+ /** Skips type checks, the editor and `build` do that. */
100
+ export async function dev(project, wraith, { log = () => {} } = {}) {
101
+ warnIfTooOld(project, wraith, log);
102
+ types(project, wraith);
103
+ const out = join(project.root, project.outDir);
104
+ rmSync(out, { recursive: true, force: true });
105
+ copyFiles(project);
106
+ let first = true;
107
+ const ctx = await esbuild.context({
108
+ ...bundleOptions(project),
109
+ plugins: [{
110
+ name: "wraith-install",
111
+ setup(b) {
112
+ b.onEnd((result) => {
113
+ if (result.errors.length) return;
114
+ log(first ? `Built in ${out}. If Wraith doesn't load it yet: wraith dev add ${out}, then Rescan in the overlay's Plugins window. Reload it there after each change` : `Rebuilt ${new Date().toLocaleTimeString()}`);
115
+ first = false;
116
+ });
117
+ },
118
+ }],
119
+ });
120
+ await ctx.watch();
121
+
122
+ let timer;
123
+ const changed = () => {
124
+ clearTimeout(timer);
125
+ timer = setTimeout(() => {
126
+ try {
127
+ types(project, wraith);
128
+ copyFiles(project);
129
+ log(`Updated ${new Date().toLocaleTimeString()}`);
130
+ } catch (e) {
131
+ log(e.message);
132
+ }
133
+ }, 100);
134
+ };
135
+ const watchers = [watch(join(project.root, project.manifestFile), changed)];
136
+ for (const dir of [schemasDir, project.public]) {
137
+ if (existsSync(join(project.root, dir))) watchers.push(watch(join(project.root, dir), { recursive: true }, changed));
138
+ }
139
+ return {
140
+ async stop() {
141
+ clearTimeout(timer);
142
+ for (const w of watchers) w.close();
143
+ await ctx.dispose();
144
+ },
145
+ };
146
+ }
147
+
148
+ /**
149
+ * Files go in one folder named after the plugin.
150
+ * @returns {{ file: string, sha256: string }}
151
+ */
152
+ export async function pack(project, wraith, options = {}) {
153
+ await build(project, wraith, options);
154
+ const out = join(project.root, project.outDir);
155
+ const entries = files(out).map((path) => ({ name: `${project.name}/${relative(out, path).replaceAll("\\", "/")}`, data: readFileSync(path) }));
156
+ const bytes = zip(entries);
157
+ const file = join(project.root, `${project.name}-${project.manifest.version}.zip`);
158
+ writeFileSync(file, bytes);
159
+ return { file, sha256: createHash("sha256").update(bytes).digest("hex") };
160
+ }
161
+
162
+ function files(dir) {
163
+ return readdirSync(dir, { withFileTypes: true })
164
+ .sort((a, b) => (a.name < b.name ? -1 : 1))
165
+ .flatMap((e) => (e.isDirectory() ? files(join(dir, e.name)) : [join(dir, e.name)]));
166
+ }
package/lib/index.js ADDED
@@ -0,0 +1,4 @@
1
+ export { findWraith, compareVersions, isDevVersion, cacheDir, sdk } from "./wraith.js";
2
+ export { loadProject, readManifest, validateManifest, manifestFile, schemaUrl } from "./project.js";
3
+ export { build, check, dev, pack, types, typesDir } from "./build.js";
4
+ export { zip, unzip, extract } from "./zip.js";
package/lib/project.js ADDED
@@ -0,0 +1,159 @@
1
+ // A plugin project. package.json's `"wraith"` can override its paths.
2
+
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { join } from "node:path";
5
+
6
+ export const manifestFile = "wraith.json";
7
+ export const schemaUrl = "https://hub.wraith.io/schema/v1/wraith.json";
8
+
9
+ /**
10
+ * wraith.json, see schemaUrl.
11
+ * @typedef {object} Manifest
12
+ * @property {string} id
13
+ * @property {"plugin" | "project"} kind
14
+ * @property {string} version
15
+ * @property {string} title
16
+ * @property {string} summary
17
+ * @property {string} [description]
18
+ * @property {string} [license]
19
+ * @property {string} [author]
20
+ * @property {string} [homepage]
21
+ * @property {string} [wraith]
22
+ * @property {{ ids?: string[], exes?: string[], builds?: string[], hashes?: string[] }} [game] left out means any game
23
+ * @property {("x64" | "x86")[]} [arches]
24
+ * @property {string} [provider]
25
+ * @property {boolean} [autoLoad]
26
+ * @property {string[]} [depends]
27
+ */
28
+
29
+ /**
30
+ * @typedef {object} Project
31
+ * @property {string} root
32
+ * @property {string} name its manifest's id
33
+ * @property {string} manifestFile
34
+ * @property {Manifest} manifest
35
+ * @property {string} entry
36
+ * @property {string} public
37
+ * @property {string} outDir
38
+ * @property {4 | 8} pointerSize
39
+ */
40
+
41
+ /** @returns {Project} */
42
+ export function loadProject(root) {
43
+ const path = join(root, manifestFile);
44
+ if (!existsSync(path)) throw new Error(`${root} has no ${manifestFile}`);
45
+ const manifest = readManifest(readFileSync(path, "utf8"));
46
+ if (manifest.kind !== "plugin") throw new Error(`${manifestFile} must say "kind": "plugin"`);
47
+ if (manifest.provider !== "js") throw new Error(`${manifestFile} must say "provider": "js"`);
48
+ const name = manifest.id;
49
+
50
+ let options = {};
51
+ try {
52
+ options = JSON.parse(readFileSync(join(root, "package.json"), "utf8")).wraith ?? {};
53
+ } catch {}
54
+ const entry = options.entry ?? ["src/main.ts", "src/main.js"].find((e) => existsSync(join(root, e))) ?? "src/main.ts";
55
+ // 32-bit only plugins get 4-byte pointers
56
+ const pointerSize = options.pointerSize ?? (manifest.arches?.length === 1 && manifest.arches[0] === "x86" ? 4 : 8);
57
+ return {
58
+ root,
59
+ name,
60
+ manifestFile,
61
+ manifest,
62
+ entry,
63
+ public: options.public ?? "public",
64
+ outDir: options.outDir ?? "dist",
65
+ pointerSize,
66
+ };
67
+ }
68
+
69
+ /** Parses wraith.json's text. Throws if it isn't JSON or doesn't fit the schema. */
70
+ export function readManifest(text, file = manifestFile) {
71
+ let manifest;
72
+ try {
73
+ manifest = JSON.parse(text);
74
+ } catch (e) {
75
+ throw new Error(`${file} isn't valid JSON: ${e.message}`);
76
+ }
77
+ const problems = validateManifest(manifest);
78
+ if (problems.length) throw new Error(`${file} doesn't fit ${schemaUrl}:\n ${problems.join("\n ")}`);
79
+ return manifest;
80
+ }
81
+
82
+ const idPattern = /^[a-z0-9][a-z0-9_-]{1,63}$/;
83
+ const versionPattern = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(-[0-9A-Za-z.-]+)?$/;
84
+ const wraithPattern = /^[0-9]+(\.[0-9]+){0,2}$/;
85
+ const gameIdPattern = /^[A-Za-z0-9][A-Za-z0-9_.+~-]{0,127}$/;
86
+ const exePattern = /^[^<>:"/\\|?*]{1,128}\.[eE][xX][eE]$/;
87
+ const buildPattern = /^[a-z]+:[A-Za-z0-9._-]{1,128}$/;
88
+ const hashPattern = /^[0-9a-fA-F]{128}$/;
89
+ const providerPattern = /^[a-z][a-z0-9_]{0,31}$/;
90
+ const dependPattern = /^[a-z0-9][a-z0-9_-]{1,63}(@[0-9]+(\.[0-9]+){0,2})?$/;
91
+
92
+ /**
93
+ * Checks a parsed manifest against the schema (schemaUrl).
94
+ * @returns {string[]} what's wrong, empty if nothing
95
+ */
96
+ export function validateManifest(m) {
97
+ if (typeof m !== "object" || m === null || Array.isArray(m)) return ["it must be an object"];
98
+ const problems = [];
99
+ const known = ["$schema", "id", "kind", "version", "title", "summary", "description", "license", "author", "homepage", "wraith", "game", "arches", "provider", "autoLoad", "depends"];
100
+ for (const key of Object.keys(m)) if (!known.includes(key)) problems.push(`"${key}" isn't a field`);
101
+ for (const key of ["id", "kind", "version", "title", "summary"]) if (m[key] === undefined) problems.push(`"${key}" is required`);
102
+
103
+ const string = (key, { pattern, min = 0, max = Infinity } = {}) => {
104
+ const v = m[key];
105
+ if (v === undefined) return;
106
+ if (typeof v !== "string") problems.push(`"${key}" must be a string`);
107
+ else if (v.length < min || v.length > max) problems.push(`"${key}" must be ${min}-${max} characters`);
108
+ else if (pattern && !pattern.test(v)) problems.push(`"${key}" must match ${pattern.source}`);
109
+ };
110
+ string("$schema");
111
+ string("id", { pattern: idPattern });
112
+ string("version", { pattern: versionPattern });
113
+ string("title", { min: 1, max: 80 });
114
+ string("summary", { min: 1, max: 200 });
115
+ string("description", { max: 20000 });
116
+ string("license", { max: 64 });
117
+ string("author", { max: 64 });
118
+ string("homepage", { pattern: /^https:\/\/[^\s]+$/, max: 256 });
119
+ string("wraith", { pattern: wraithPattern });
120
+ string("provider", { pattern: providerPattern });
121
+ if (m.kind !== undefined && m.kind !== "plugin" && m.kind !== "project") problems.push(`"kind" must be "plugin" or "project"`);
122
+ if (m.autoLoad !== undefined && typeof m.autoLoad !== "boolean") problems.push(`"autoLoad" must be true or false`);
123
+
124
+ if (m.game !== undefined) {
125
+ const g = m.game;
126
+ if (typeof g !== "object" || g === null || Array.isArray(g)) problems.push(`"game" must be an object`);
127
+ else {
128
+ for (const key of Object.keys(g)) if (!["ids", "exes", "builds", "hashes"].includes(key)) problems.push(`"game"."${key}" isn't a field`);
129
+ if (g.ids === undefined && g.exes === undefined) problems.push(`"game" needs "ids" or "exes"`);
130
+ const list = (key, pattern, like, min) => {
131
+ const v = g[key];
132
+ if (v === undefined) return;
133
+ if (!Array.isArray(v) || v.length < min || v.length > 64 || new Set(v).size !== v.length || !v.every((x) => typeof x === "string" && pattern.test(x))) {
134
+ problems.push(`"game"."${key}" must be a list of ${min}-64 different ones like ${like}`);
135
+ }
136
+ };
137
+ list("ids", gameIdPattern, "steam-1245620", 1);
138
+ list("exes", exePattern, "game.exe", 1);
139
+ list("builds", buildPattern, "steam:18234455", 0);
140
+ list("hashes", hashPattern, "an exe's SHA-512 in hex", 0);
141
+ }
142
+ }
143
+ if (m.arches !== undefined) {
144
+ const a = m.arches;
145
+ if (!Array.isArray(a) || !a.length || new Set(a).size !== a.length || !a.every((x) => x === "x64" || x === "x86")) {
146
+ problems.push(`"arches" must be a list of "x64" and/or "x86", each once`);
147
+ }
148
+ }
149
+ if (m.depends !== undefined) {
150
+ const d = m.depends;
151
+ if (!Array.isArray(d) || d.length > 32 || new Set(d).size !== d.length || !d.every((x) => typeof x === "string" && dependPattern.test(x))) {
152
+ problems.push(`"depends" must be a list of at most 32 different name or name@version`);
153
+ }
154
+ }
155
+ if (m.kind === "project") {
156
+ for (const key of ["arches", "provider", "autoLoad"]) if (m[key] !== undefined) problems.push(`"${key}" is for plugins only`);
157
+ }
158
+ return problems;
159
+ }
package/lib/wraith.js ADDED
@@ -0,0 +1,145 @@
1
+ // Finds Wraith. Tries WRAITH, the launcher's install and PATH, then the SDK cache or a download.
2
+
3
+ import { execFileSync } from "node:child_process";
4
+ import { createHash } from "node:crypto";
5
+ import { existsSync, mkdirSync, readFileSync, readdirSync, renameSync, rmSync, statSync } from "node:fs";
6
+ import { homedir } from "node:os";
7
+ import { delimiter, join } from "node:path";
8
+ import { extract } from "./zip.js";
9
+
10
+ const defaultDist = "https://dist.wraith.io/wraith";
11
+
12
+ /**
13
+ * @typedef {object} Wraith
14
+ * @property {string} exe
15
+ * @property {string} version
16
+ * @property {string} dir
17
+ * @property {string} modsDir
18
+ * @property {string} source
19
+ */
20
+
21
+ /**
22
+ * @param {{ download?: boolean, log?: (message: string) => void }} [options]
23
+ * @returns {Promise<Wraith>}
24
+ */
25
+ export async function findWraith(options = {}) {
26
+ const log = options.log ?? (() => {});
27
+ if (process.platform !== "win32") {
28
+ throw new Error("Wraith runs on Windows: build plugins there (in CI, a windows runner)");
29
+ }
30
+ const tried = [];
31
+ for (const [source, exe] of candidates()) {
32
+ if (!exe || !existsSync(exe)) continue;
33
+ const found = ask(exe, source);
34
+ if (found) return found;
35
+ tried.push(`${exe} (${source}) is too old to have \`wraith sdk\``);
36
+ }
37
+ if (options.download === false) {
38
+ throw new Error(["No Wraith found: install the Wraith app, or set WRAITH to its wraith.exe", ...tried].join("\n "));
39
+ }
40
+ for (const t of tried) log(t);
41
+ const exe = await download(log);
42
+ const found = ask(exe, "download");
43
+ if (!found) throw new Error(`The latest Wraith (${exe}) doesn't have \`wraith sdk\``);
44
+ return found;
45
+ }
46
+
47
+ /** [source, wraith.exe] pairs, in order. */
48
+ function* candidates() {
49
+ const env = process.env.WRAITH;
50
+ if (env) yield ["WRAITH", existsSync(env) && statSync(env).isDirectory() ? join(env, "wraith.exe") : env];
51
+ const installed = wraithRoot();
52
+ if (installed) {
53
+ const root = join(installed, "framework");
54
+ try {
55
+ const folder = readFileSync(join(root, "current.txt"), "utf8").trim();
56
+ yield ["app", join(root, folder, "wraith.exe")];
57
+ } catch {}
58
+ }
59
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) {
60
+ if (dir) yield ["PATH", join(dir, "wraith.exe")];
61
+ }
62
+ const cache = cacheDir();
63
+ if (existsSync(cache)) {
64
+ const versions = readdirSync(cache).filter((v) => v.startsWith("v") && existsSync(join(cache, v, "wraith.exe")));
65
+ versions.sort((a, b) => compareVersions(b.slice(1), a.slice(1)));
66
+ if (versions.length) yield ["cache", join(cache, versions[0], "wraith.exe")];
67
+ }
68
+ }
69
+
70
+ /** Null if it's too old to have `wraith sdk js info`. */
71
+ function ask(exe, source) {
72
+ let out;
73
+ try {
74
+ out = execFileSync(exe, ["sdk", "js", "info"], { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
75
+ } catch {
76
+ return null;
77
+ }
78
+ try {
79
+ const info = JSON.parse(out);
80
+ return { exe, version: info.version, dir: info.dir, modsDir: info.mods_dir, source };
81
+ } catch {
82
+ return null;
83
+ }
84
+ }
85
+
86
+ function wraithRoot() {
87
+ if (process.env.WRAITH_ROOT) return process.env.WRAITH_ROOT;
88
+ const local = process.env.LOCALAPPDATA ?? join(homedir(), "AppData", "Local");
89
+ return join(local, "Wraith");
90
+ }
91
+
92
+ export function cacheDir() {
93
+ if (process.env.WRAITH_SDK_CACHE) return process.env.WRAITH_SDK_CACHE;
94
+ return join(wraithRoot(), "cache", "sdk");
95
+ }
96
+
97
+ async function download(log) {
98
+ const dist = (process.env.WRAITH_DIST_URL ?? defaultDist).replace(/\/$/, "");
99
+ const release = await (await get(`${dist}/latest.json`)).json();
100
+ const dir = join(cacheDir(), `v${release.version}`);
101
+ const exe = join(dir, "wraith.exe");
102
+ if (existsSync(exe)) return exe;
103
+ log(`Downloading Wraith ${release.version} (${release.url})`);
104
+ const zip = Buffer.from(await (await get(release.url)).arrayBuffer());
105
+ const sha256 = createHash("sha256").update(zip).digest("hex");
106
+ if (sha256.toLowerCase() !== String(release.sha256).toLowerCase()) {
107
+ throw new Error(`Wraith ${release.version}'s download is corrupt (its SHA-256 is ${sha256}, not ${release.sha256})`);
108
+ }
109
+ // Unpack beside it first so a half-done unpack doesn't look downloaded
110
+ const partial = `${dir}.partial`;
111
+ rmSync(partial, { recursive: true, force: true });
112
+ mkdirSync(partial, { recursive: true });
113
+ try {
114
+ extract(zip, partial);
115
+ if (!existsSync(join(partial, "wraith.exe"))) throw new Error(`There's no wraith.exe in ${release.url}`);
116
+ renameSync(partial, dir);
117
+ } finally {
118
+ rmSync(partial, { recursive: true, force: true });
119
+ }
120
+ return exe;
121
+ }
122
+
123
+ async function get(url) {
124
+ const response = await fetch(url);
125
+ if (!response.ok) throw new Error(`${url} answered ${response.status}`);
126
+ return response;
127
+ }
128
+
129
+ /** Returns -1, 0 or 1. */
130
+ export function compareVersions(a, b) {
131
+ const pa = String(a).split(/[.+-]/).map((n) => parseInt(n, 10) || 0);
132
+ const pb = String(b).split(/[.+-]/).map((n) => parseInt(n, 10) || 0);
133
+ for (let i = 0; i < 3; i++) {
134
+ if ((pa[i] ?? 0) !== (pb[i] ?? 0)) return (pa[i] ?? 0) < (pb[i] ?? 0) ? -1 : 1;
135
+ }
136
+ return 0;
137
+ }
138
+
139
+ /** Builds from main are 0.0.0. */
140
+ export const isDevVersion = (version) => compareVersions(version, "0.0.0") === 0;
141
+
142
+ /** @param {Wraith} wraith */
143
+ export function sdk(wraith, args, cwd) {
144
+ execFileSync(wraith.exe, ["sdk", ...args], { cwd, stdio: "inherit", windowsHide: true });
145
+ }
package/lib/zip.js ADDED
@@ -0,0 +1,126 @@
1
+ // Dependency-free zips. Deflate or stored only, no ZIP64.
2
+
3
+ import { deflateRawSync, inflateRawSync } from "node:zlib";
4
+ import { mkdirSync, writeFileSync } from "node:fs";
5
+ import { dirname, resolve, sep } from "node:path";
6
+
7
+ const crcTable = new Uint32Array(256).map((_, n) => {
8
+ let c = n;
9
+ for (let k = 0; k < 8; k++) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
10
+ return c >>> 0;
11
+ });
12
+
13
+ function crc32(data) {
14
+ let c = 0xffffffff;
15
+ for (const byte of data) c = crcTable[(c ^ byte) & 0xff] ^ (c >>> 8);
16
+ return (c ^ 0xffffffff) >>> 0;
17
+ }
18
+
19
+ /**
20
+ * Deterministic, every date is 1980-01-01.
21
+ * @param {{ name: string, data: Uint8Array }[]} entries
22
+ * @returns {Buffer}
23
+ */
24
+ export function zip(entries) {
25
+ const locals = [];
26
+ const central = [];
27
+ let offset = 0;
28
+ const date = (1 << 5) | 1;
29
+ for (const { name, data } of entries) {
30
+ const nameBytes = Buffer.from(name, "utf8");
31
+ const deflated = deflateRawSync(data, { level: 9 });
32
+ const stored = deflated.length >= data.length;
33
+ const body = stored ? Buffer.from(data) : deflated;
34
+ const crc = crc32(data);
35
+
36
+ const local = Buffer.alloc(30);
37
+ local.writeUInt32LE(0x04034b50, 0);
38
+ local.writeUInt16LE(20, 4);
39
+ local.writeUInt16LE(0x0800, 6); // UTF-8 names
40
+ local.writeUInt16LE(stored ? 0 : 8, 8);
41
+ local.writeUInt16LE(date, 12);
42
+ local.writeUInt32LE(crc, 14);
43
+ local.writeUInt32LE(body.length, 18);
44
+ local.writeUInt32LE(data.length, 22);
45
+ local.writeUInt16LE(nameBytes.length, 26);
46
+ locals.push(local, nameBytes, body);
47
+
48
+ const entry = Buffer.alloc(46);
49
+ entry.writeUInt32LE(0x02014b50, 0);
50
+ entry.writeUInt16LE(20, 4);
51
+ entry.writeUInt16LE(20, 6);
52
+ entry.writeUInt16LE(0x0800, 8);
53
+ entry.writeUInt16LE(stored ? 0 : 8, 10);
54
+ entry.writeUInt16LE(date, 14);
55
+ entry.writeUInt32LE(crc, 16);
56
+ entry.writeUInt32LE(body.length, 20);
57
+ entry.writeUInt32LE(data.length, 24);
58
+ entry.writeUInt16LE(nameBytes.length, 28);
59
+ entry.writeUInt32LE(offset, 42);
60
+ central.push(entry, nameBytes);
61
+
62
+ offset += local.length + nameBytes.length + body.length;
63
+ }
64
+ const centralSize = central.reduce((n, b) => n + b.length, 0);
65
+ const end = Buffer.alloc(22);
66
+ end.writeUInt32LE(0x06054b50, 0);
67
+ end.writeUInt16LE(entries.length, 8);
68
+ end.writeUInt16LE(entries.length, 10);
69
+ end.writeUInt32LE(centralSize, 12);
70
+ end.writeUInt32LE(offset, 16);
71
+ return Buffer.concat([...locals, ...central, end]);
72
+ }
73
+
74
+ /**
75
+ * @param {Uint8Array} bytes
76
+ * @returns {{ name: string, data: Buffer }[]}
77
+ */
78
+ export function unzip(bytes) {
79
+ const buf = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
80
+ let end = -1;
81
+ for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 0xffff); i--) {
82
+ if (buf.readUInt32LE(i) === 0x06054b50) {
83
+ end = i;
84
+ break;
85
+ }
86
+ }
87
+ if (end < 0) throw new Error("not a zip");
88
+ const count = buf.readUInt16LE(end + 10);
89
+ let at = buf.readUInt32LE(end + 16);
90
+ const files = [];
91
+ for (let i = 0; i < count; i++) {
92
+ if (buf.readUInt32LE(at) !== 0x02014b50) throw new Error("a broken zip");
93
+ const method = buf.readUInt16LE(at + 10);
94
+ const compressed = buf.readUInt32LE(at + 20);
95
+ const size = buf.readUInt32LE(at + 24);
96
+ const nameLen = buf.readUInt16LE(at + 28);
97
+ const extraLen = buf.readUInt16LE(at + 30);
98
+ const commentLen = buf.readUInt16LE(at + 32);
99
+ const localAt = buf.readUInt32LE(at + 42);
100
+ const name = buf.toString("utf8", at + 46, at + 46 + nameLen).replaceAll("\\", "/");
101
+ at += 46 + nameLen + extraLen + commentLen;
102
+ if (name.endsWith("/")) continue;
103
+
104
+ // Local header sizes can be 0 if a data descriptor follows
105
+ const dataAt = localAt + 30 + buf.readUInt16LE(localAt + 26) + buf.readUInt16LE(localAt + 28);
106
+ const body = buf.subarray(dataAt, dataAt + compressed);
107
+ let data;
108
+ if (method === 0) data = Buffer.from(body);
109
+ else if (method === 8) data = inflateRawSync(body);
110
+ else throw new Error(`${name}: compressed in a way this can't read (method ${method})`);
111
+ if (data.length !== size) throw new Error(`${name}: a broken zip`);
112
+ files.push({ name, data });
113
+ }
114
+ return files;
115
+ }
116
+
117
+ /** Refuses files that would escape `dir`. */
118
+ export function extract(bytes, dir) {
119
+ const root = resolve(dir);
120
+ for (const { name, data } of unzip(bytes)) {
121
+ const target = resolve(root, name);
122
+ if (!target.startsWith(root + sep)) throw new Error(`${name} would go outside ${dir}`);
123
+ mkdirSync(dirname(target), { recursive: true });
124
+ writeFileSync(target, data);
125
+ }
126
+ }
package/package.json CHANGED
@@ -1,6 +1,50 @@
1
1
  {
2
2
  "name": "@ratatoskr.io/plugin-tools",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.0.2",
4
+ "description": "Builds JavaScript and TypeScript plugins for Wraith: typings from the installed Wraith, bundling, a dev loop and packing",
5
+ "keywords": [
6
+ "wraith",
7
+ "wraith-plugin",
8
+ "modding",
9
+ "game-modding",
10
+ "plugin",
11
+ "typescript",
12
+ "javascript",
13
+ "esbuild",
14
+ "cli"
15
+ ],
16
+ "homepage": "https://docs.wraith.io/plugins/js/setup/",
17
+ "bugs": {
18
+ "url": "https://github.com/ratatoskr/js-sdk/issues"
19
+ },
20
+ "author": "Asgard (https://github.com/asgardkat)",
21
+ "license": "MIT",
22
+ "repository": {
23
+ "type": "git",
24
+ "url": "git+https://github.com/ratatoskr/js-sdk.git",
25
+ "directory": "packages/plugin-tools"
26
+ },
27
+ "type": "module",
28
+ "exports": {
29
+ ".": "./lib/index.js"
30
+ },
31
+ "bin": {
32
+ "wraith-plugin": "./bin/wraith-plugin.js"
33
+ },
34
+ "files": [
35
+ "bin",
36
+ "lib"
37
+ ],
38
+ "engines": {
39
+ "node": ">=20"
40
+ },
41
+ "scripts": {
42
+ "test": "node --test"
43
+ },
44
+ "dependencies": {
45
+ "esbuild": "^0.28.2"
46
+ },
47
+ "devDependencies": {
48
+ "typescript": "^7.0.2"
49
+ }
50
+ }