rpg-engine 0.2.0 → 0.2.1

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.
@@ -1,12 +1,13 @@
1
1
  import { z } from "zod";
2
- import type { PackageInfo } from "../core/context.ts";
3
2
  import { type Extension } from "../extensions/index.ts";
4
3
  type PackageResult = {
5
4
  kind: "list";
6
- installed: Listed[];
7
- listedMissing: string[];
8
- available: PackageInfo[];
9
- searchFailed?: string;
5
+ installed: Installed[];
6
+ missing: string[];
7
+ } | {
8
+ kind: "available";
9
+ packages: Available[];
10
+ failed?: string;
10
11
  } | {
11
12
  kind: "installed";
12
13
  extension: Extension;
@@ -19,22 +20,43 @@ type PackageResult = {
19
20
  } | {
20
21
  kind: "removed";
21
22
  name: string;
23
+ } | {
24
+ kind: "uninstalled";
25
+ name: string;
26
+ wasUsed: boolean;
22
27
  };
23
- /** A package on this computer as package list gives it; broken when it does not read. */
24
- type Listed = {
28
+ /** A package on this computer, as list gives it to the master and to the dashboard; broken when it does not read (D-442). */
29
+ type Installed = {
25
30
  name: string;
31
+ package: string;
26
32
  version: string;
33
+ title: string;
34
+ about: string;
27
35
  verified: boolean;
28
36
  used: boolean;
29
37
  } | {
30
38
  name: string;
39
+ package: string;
31
40
  broken: string;
32
41
  };
42
+ /** A package on npm for this rpg-engine, with the version installed here, if any, and whether it is newer (D-442). */
43
+ interface Available {
44
+ name: string;
45
+ package: string;
46
+ version: string;
47
+ description?: string;
48
+ author?: string;
49
+ verified: boolean;
50
+ installed?: string;
51
+ update: boolean;
52
+ }
33
53
  export declare const packageCommand: import("../core/registry.ts").Command<z.ZodObject<{
34
54
  action: z.ZodEnum<{
35
55
  remove: "remove";
36
56
  list: "list";
37
57
  install: "install";
58
+ available: "available";
59
+ uninstall: "uninstall";
38
60
  }>;
39
61
  name: z.ZodOptional<z.ZodString>;
40
62
  "accept-risk": z.ZodOptional<z.ZodBoolean>;
@@ -13,33 +13,42 @@ import { newDatedLogEntry } from "./game-time.js";
13
13
  import { campaignWorld } from "./game-world.js";
14
14
  export const packageCommand = defineCommand({
15
15
  name: "package",
16
- description: "Install, list or remove the packages of the campaign: extensions such as weather, from npm. "
17
- + "list says those on this computer, those the campaign uses and those npm has. install adds one to this computer and to the campaign, only once the player wants it; "
18
- + "one not published by RPG Engine (@rpgengine/…) is someone else's: the player is asked on their dashboard or in a form, or installs it from their terminal. "
19
- + "remove takes one out of the campaign. Example: package install weather.",
16
+ description: "The packages of the campaign: extensions such as weather, from npm. "
17
+ + "list says those on this computer and those the campaign uses; available, those npm has, and updates. install adds or updates one, on this computer and in the campaign, "
18
+ + "only once the player wants it; one not published by RPG Engine (@rpgengine/…) is someone else's: the player is asked on their dashboard or in a form, or installs it from their terminal. "
19
+ + "remove takes one out of the campaign; uninstall takes it off this computer. Example: package install weather.",
20
20
  group: "campaign",
21
21
  positionals: ["action", "name"],
22
22
  slow: true,
23
23
  input: z.object({
24
- action: z.enum(["list", "install", "remove"]).describe("list, install or remove"),
24
+ action: z.enum(["list", "available", "install", "remove", "uninstall"]).describe("list, available, install, remove or uninstall"),
25
25
  name: z.string().optional().describe("the package: its name alone for one of ours, such as weather; another's npm name with its scope, or npm:name without one, its version if wanted; or a folder on this computer"),
26
26
  "accept-risk": z.boolean().optional().describe("on the command line only: the player's own yes to a package not published by RPG Engine, at their own risk"),
27
27
  }),
28
28
  async run(input, context) {
29
29
  const root = requireCampaign(context.folder);
30
30
  if (input.action === "list") {
31
- return await listed(root, context);
31
+ return listed(root, context);
32
+ }
33
+ if (input.action === "available") {
34
+ return await available(context);
32
35
  }
33
36
  const name = input.name?.trim();
34
37
  if (name === undefined || name === "") {
35
38
  throw new Error(`Give the package to ${input.action}, such as package ${input.action} weather.`);
36
39
  }
37
- return input.action === "install" ? await installed(root, context, name, context.terminal === true && input["accept-risk"] === true) : removed(root, context, name);
40
+ if (input.action === "install") {
41
+ return await installed(root, context, name, context.terminal === true && input["accept-risk"] === true);
42
+ }
43
+ return input.action === "remove" ? removed(root, context, name) : await uninstalled(root, context, name);
38
44
  },
39
45
  format(result) {
40
46
  if (result.kind === "removed") {
41
47
  return `The campaign no longer uses ${result.name}: its commands and its parts of your instructions are gone; what it kept in the campaign stays, and comes back if it is installed again.`;
42
48
  }
49
+ if (result.kind === "uninstalled") {
50
+ return `${result.name} is off this computer${result.wasUsed ? ", and the campaign no longer uses it" : ""}: another campaign that lists it asks to install it again.`;
51
+ }
43
52
  if (result.kind === "installed") {
44
53
  const { extension } = result;
45
54
  const what = `${extension.name} ${extension.version}${result.verified ? ", verified" : ", not verified: at the player's risk"}`;
@@ -51,36 +60,76 @@ export const packageCommand = defineCommand({
51
60
  ].filter((line) => line !== "").join(" ");
52
61
  return result.part === undefined ? said : `${said}\n\nIts part for now:\n\n${result.part}`;
53
62
  }
63
+ if (result.kind === "available") {
64
+ if (result.failed !== undefined) {
65
+ return `npm could not be asked: ${result.failed}.`;
66
+ }
67
+ const lines = result.packages.map((one) => {
68
+ const here = one.installed === undefined ? "" : one.update ? `, installed ${one.installed}: an update` : ", installed";
69
+ const by = one.author === undefined ? "" : ` by ${one.author}`;
70
+ return `${one.name} ${one.version}${one.verified ? "" : " (not verified)"}${by}${here}${one.description === undefined ? "" : `: ${one.description.replace(/\.$/, "")}`}`;
71
+ });
72
+ return `On npm: ${lines.length === 0 ? "none" : lines.join("; ")}.`;
73
+ }
54
74
  const installedLines = result.installed.map((one) => "broken" in one ? `${one.name} (broken: ${one.broken}; install it again)` : `${one.name} ${one.version}${one.verified ? "" : " (not verified)"}${one.used ? ", used by the campaign" : ""}`);
55
- const available = result.available.map((one) => `${shortName(one.name)} ${one.version}${one.name.startsWith(verifiedScope) ? "" : " (not verified)"}${one.description === undefined ? "" : `: ${one.description}`}`);
56
75
  return [
57
76
  `On this computer: ${installedLines.length === 0 ? "none" : installedLines.join("; ")}.`,
58
- result.listedMissing.length === 0 ? "" : `The campaign lists, not installed here: ${result.listedMissing.join(", ")}; install each with package install.`,
59
- result.searchFailed === undefined ? `On npm: ${available.length === 0 ? "none more" : available.join("; ")}.` : `npm could not be asked: ${result.searchFailed}.`,
77
+ result.missing.length === 0 ? "" : `The campaign lists, not installed here: ${result.missing.join(", ")}; install each with package install.`,
78
+ "package available says those npm has, and updates.",
60
79
  ].filter((line) => line !== "").join("\n");
61
80
  },
62
81
  });
63
- /** The packages on this computer, those the campaign lists and does not find, and those npm has besides, for this rpg-engine. */
64
- async function listed(root, context) {
82
+ /** The packages on this computer, and those the campaign lists and does not find there: at once, without npm (D-442). */
83
+ function listed(root, context) {
65
84
  const used = Object.keys(listedExtensions(root));
66
85
  const here = installedExtensions(context.extensionFolders ?? []).map((found) => {
67
86
  try {
68
87
  const extension = readExtension(found.folder);
69
- return { name: extension.name, version: extension.version, verified: isVerified(extension.package, extension.linked), used: used.includes(extension.package) };
88
+ return {
89
+ name: extension.name,
90
+ package: extension.package,
91
+ version: extension.version,
92
+ title: extension.title,
93
+ about: extension.about,
94
+ verified: isVerified(extension.package, extension.linked),
95
+ used: used.includes(extension.package),
96
+ };
70
97
  }
71
98
  catch (error) {
72
- return { name: shortName(found.package), broken: error instanceof Error ? error.message : String(error) };
99
+ return { name: shortName(found.package), package: found.package, broken: error instanceof Error ? error.message : String(error) };
73
100
  }
74
101
  });
102
+ return { kind: "list", installed: here, missing: used.filter((name) => !here.some((one) => one.package === name)) };
103
+ }
104
+ /** The extensions npm has for this rpg-engine's API, ours first, each with the version installed here and whether npm has a newer one (D-442). */
105
+ async function available(context) {
75
106
  const searched = context.packages === undefined ? { failed: "only the game's server and the command line reach npm" } : await context.packages.search();
76
- const isHere = (name) => here.some((one) => one.name === shortName(name));
77
- return {
78
- kind: "list",
79
- installed: here,
80
- listedMissing: used.filter((name) => !isHere(name)),
81
- available: "failed" in searched ? [] : searched.filter((one) => !isHere(one.name) && one.kind === "extension" && one.api === extensionApi),
82
- ...("failed" in searched ? { searchFailed: searched.failed } : {}),
83
- };
107
+ if ("failed" in searched) {
108
+ return { kind: "available", packages: [], failed: searched.failed };
109
+ }
110
+ const here = installedExtensions(context.extensionFolders ?? []);
111
+ const packages = searched.filter((one) => one.kind === "extension" && one.api === extensionApi).map((one) => {
112
+ const installed = here.find((found) => found.package === one.name);
113
+ const version = installed === undefined ? undefined : usable(context, one.name)?.version;
114
+ return {
115
+ name: shortName(one.name),
116
+ package: one.name,
117
+ version: one.version,
118
+ ...(one.description === undefined ? {} : { description: one.description }),
119
+ ...(one.author === undefined ? {} : { author: one.author }),
120
+ verified: one.name.startsWith(verifiedScope),
121
+ ...(installed === undefined ? {} : { installed: version ?? "broken" }),
122
+ update: version !== undefined && newer(one.version, version),
123
+ };
124
+ });
125
+ return { kind: "available", packages: packages.sort((first, second) => Number(second.verified) - Number(first.verified) || first.name.localeCompare(second.name)) };
126
+ }
127
+ /** Whether a version is newer than another, by its numbers: 0.2.0 after 0.1.10. */
128
+ function newer(version, than) {
129
+ const numbers = (text) => text.split(/[.+-]/).slice(0, 3).map((part) => Number.parseInt(part, 10) || 0);
130
+ const [one, other] = [numbers(version), numbers(than)];
131
+ const differs = one.findIndex((part, index) => part !== other[index]);
132
+ return differs !== -1 && one[differs] > other[differs];
84
133
  }
85
134
  /** Installs a package on this computer and adds it to the campaign (D-27, D-428, D-441): ours, or another once the player wants it; an extension, for this game. */
86
135
  async function installed(root, context, name, acceptRisk) {
@@ -218,3 +267,27 @@ function removed(root, context, name) {
218
267
  appendLogEntry(root, newDatedLogEntry(root, context, "package-removed", "public", { package: found }));
219
268
  return { kind: "removed", name: shortName(found) };
220
269
  }
270
+ /** Takes a package off this computer with npm, and out of the campaign when it uses it (D-442); other campaigns that list it ask to install it again. */
271
+ async function uninstalled(root, context, name) {
272
+ const packages = context.packages;
273
+ const found = installedExtensions(context.extensionFolders ?? []).find((one) => one.package === name || comparableText(shortName(one.package)) === comparableText(name));
274
+ if (found === undefined) {
275
+ const here = installedExtensions(context.extensionFolders ?? []).map((one) => shortName(one.package));
276
+ throw new Error(`${name} is not on this computer${here.length === 0 ? ": no package is" : `; these are: ${here.join(", ")}`}. Nothing changed.`);
277
+ }
278
+ if (packages === undefined) {
279
+ throw new Error("Packages are uninstalled only by the game's server or the command line, which reach npm.");
280
+ }
281
+ const why = await packages.uninstall(found.package);
282
+ if (why !== undefined) {
283
+ throw new Error(`${found.package} could not be uninstalled: ${why}. Nothing changed.`);
284
+ }
285
+ (context.extensionFolders ?? []).forEach((folder) => files().refresh(folder));
286
+ const listed = listedExtensions(root);
287
+ const wasUsed = Object.hasOwn(listed, found.package);
288
+ if (wasUsed) {
289
+ changeExtensions(root, Object.fromEntries(Object.entries(listed).filter(([candidate]) => candidate !== found.package)));
290
+ }
291
+ appendLogEntry(root, newDatedLogEntry(root, context, "package-uninstalled", "public", { package: found.package }));
292
+ return { kind: "uninstalled", name: shortName(found.package), wasUsed };
293
+ }
@@ -66,6 +66,8 @@ export interface PackageInfo {
66
66
  /** The version of the extensions' API it is made for (D-441). */
67
67
  api?: number;
68
68
  description?: string;
69
+ /** Who wrote it, as npm gives it. */
70
+ author?: string;
69
71
  }
70
72
  /** npm for the packages (D-436): what one is before it is installed, installing it in the engine's folder without running its scripts, and the search. */
71
73
  export interface PackageManager {
@@ -76,6 +78,8 @@ export interface PackageManager {
76
78
  }>;
77
79
  /** Installs it: undefined once it is installed, else why not. */
78
80
  install(spec: string): Promise<string | undefined>;
81
+ /** Takes an installed package off this computer, by its name: undefined once it is gone, else why not. */
82
+ uninstall(name: string): Promise<string | undefined>;
79
83
  /** The packages for rpg-engine npm has, by their keyword and what their package.json says. */
80
84
  search(): Promise<PackageInfo[] | {
81
85
  failed: string;
@@ -19,11 +19,20 @@ export function npmPackages(folder) {
19
19
  const ran = await npm(`install --prefix ${quotedFolder(folder)} ${what} --ignore-scripts --save-exact --no-audit --no-fund --json --loglevel=error`);
20
20
  return ran.code === 0 ? undefined : `npm said: ${npmError(ran)}`;
21
21
  },
22
+ uninstall: async (name) => {
23
+ const ran = await npm(`uninstall --prefix ${quotedFolder(folder)} ${checkedSpec(name)} --ignore-scripts --no-audit --no-fund --json --loglevel=error`);
24
+ return ran.code === 0 ? undefined : `npm said: ${npmError(ran)}`;
25
+ },
22
26
  search: async () => {
23
27
  try {
24
28
  const found = await json(`${registry}/-/v1/search?text=keywords:${packageKeyword}&size=250`);
25
29
  // The keyword is only a hint: each package's latest package.json must say what it is for rpg-engine.
26
- const described = await Promise.all((found?.objects ?? []).map(async (object) => await registryPackage(object.package.name)));
30
+ const described = await Promise.all((found?.objects ?? []).map(async ({ package: listed }) => {
31
+ const read = await registryPackage(listed.name ?? "");
32
+ // Who wrote it, as its package.json says; never who published it, which may be a workflow.
33
+ const author = authorOf(listed);
34
+ return "failed" in read || read.author !== undefined || author === undefined ? read : { ...read, author };
35
+ }));
27
36
  return described.filter((one) => !("failed" in one) && one.kind !== undefined);
28
37
  }
29
38
  catch (error) {
@@ -71,8 +80,13 @@ function infoOf(read) {
71
80
  ...(typeof marker?.kind === "string" ? { kind: marker.kind } : {}),
72
81
  ...(typeof marker?.api === "number" ? { api: marker.api } : {}),
73
82
  ...(read.description === undefined ? {} : { description: read.description }),
83
+ ...(authorOf(read) === undefined ? {} : { author: authorOf(read) }),
74
84
  };
75
85
  }
86
+ /** Who wrote a package, as its package.json or the registry gives it. */
87
+ function authorOf(read) {
88
+ return typeof read.author === "string" ? read.author : read.author?.name;
89
+ }
76
90
  /** A JSON answer of the registry; undefined when it has none, 404. */
77
91
  async function json(url) {
78
92
  const answer = await fetch(url, { headers: { accept: "application/json" }, signal: AbortSignal.timeout(20_000) });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rpg-engine",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "Play a tabletop role-playing game with an AI as your game master: the AI tells the story; RPG Engine remembers the world, rolls the dice and keeps the accounts.",
5
5
  "type": "module",
6
6
  "bin": {