@pollis-inc/cli 0.0.0-stage → 0.1.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.
- package/dist/build.d.ts +39 -0
- package/dist/build.js +351 -0
- package/dist/devtool.d.ts +12 -0
- package/dist/devtool.js +62 -0
- package/dist/errors.d.ts +3 -0
- package/dist/errors.js +3 -0
- package/dist/main.d.ts +11 -0
- package/dist/main.js +104 -0
- package/dist/new.d.ts +18 -0
- package/dist/new.js +85 -0
- package/dist/runtime.d.ts +34 -0
- package/dist/runtime.js +160 -0
- package/dist/rust.d.ts +22 -0
- package/dist/rust.js +150 -0
- package/dist/test.d.ts +13 -0
- package/dist/test.js +49 -0
- package/package.json +33 -3
- package/templates/rust/Cargo.toml.tmpl +25 -0
- package/templates/rust/README.md +18 -0
- package/templates/rust/gitignore +2 -0
- package/templates/rust/rust-toolchain.toml +5 -0
- package/templates/rust/src/lib.rs +26 -0
- package/templates/rust/tests/hello.rs +24 -0
- package/templates/ts/README.md +17 -0
- package/templates/ts/gitignore +2 -0
- package/templates/ts/package.json.tmpl +20 -0
- package/templates/ts/src/app.test.ts +22 -0
- package/templates/ts/src/app.ts +23 -0
- package/templates/ts/tsconfig.json +12 -0
- package/README.md +0 -3
package/dist/new.js
ADDED
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `pollis app new <name> --lang ts|rust`: a new App from the template: one
|
|
3
|
+
* handler, a test and a README.
|
|
4
|
+
*/
|
|
5
|
+
import { cpSync, existsSync, readFileSync, readdirSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
|
|
6
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
7
|
+
import { fileURLToPath } from "node:url";
|
|
8
|
+
export class NewError extends Error {
|
|
9
|
+
}
|
|
10
|
+
const NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
11
|
+
function templates() {
|
|
12
|
+
return join(dirname(dirname(fileURLToPath(import.meta.url))), "templates");
|
|
13
|
+
}
|
|
14
|
+
/** The SDK packages are released together, at this CLI's version. */
|
|
15
|
+
function sdkVersion() {
|
|
16
|
+
const path = join(dirname(dirname(fileURLToPath(import.meta.url))), "package.json");
|
|
17
|
+
return `^${JSON.parse(readFileSync(path, "utf8")).version}`;
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* The `pollis-app` dependency line of a new Rust App. With `--sdk` the crate is
|
|
21
|
+
* copied into the App: Cargo hashes the absolute path of a dependency outside
|
|
22
|
+
* the project into the build, so a link would change the App hash with the
|
|
23
|
+
* location of the checkout.
|
|
24
|
+
*/
|
|
25
|
+
function rustDependency(target, sdk) {
|
|
26
|
+
if (!sdk) {
|
|
27
|
+
// The crate shares the CLI's major.minor; its patch releases are its own,
|
|
28
|
+
// so a CLI patch release never asks for a crate version that does not exist.
|
|
29
|
+
const [major, minor] = sdkVersion().slice(1).split(".");
|
|
30
|
+
return JSON.stringify(`${major}.${minor}`);
|
|
31
|
+
}
|
|
32
|
+
const crate = join(resolve(sdk), "..", "rust", "pollis-app");
|
|
33
|
+
if (!existsSync(join(crate, "Cargo.toml"))) {
|
|
34
|
+
throw new NewError(`--sdk ${sdk}: expected the Pollis repo's sdk/ts directory (with ../rust/pollis-app beside it)`);
|
|
35
|
+
}
|
|
36
|
+
cpSync(crate, join(target, "vendor", "pollis-app"), {
|
|
37
|
+
recursive: true,
|
|
38
|
+
filter: (source) => !["target", "Cargo.lock"].includes(relative(crate, source)),
|
|
39
|
+
});
|
|
40
|
+
return '{ path = "vendor/pollis-app" }';
|
|
41
|
+
}
|
|
42
|
+
function newRustApp(target, options) {
|
|
43
|
+
cpSync(join(templates(), "rust"), target, { recursive: true });
|
|
44
|
+
const dependency = rustDependency(target, options.sdk);
|
|
45
|
+
renameSync(join(target, "gitignore"), join(target, ".gitignore"));
|
|
46
|
+
const fill = (text) => text.replaceAll("{{name}}", options.name).replaceAll("{{pollis_app}}", dependency);
|
|
47
|
+
const tmpl = join(target, "Cargo.toml.tmpl");
|
|
48
|
+
writeFileSync(join(target, "Cargo.toml"), fill(readFileSync(tmpl, "utf8")));
|
|
49
|
+
unlinkSync(tmpl);
|
|
50
|
+
writeFileSync(join(target, "README.md"), fill(readFileSync(join(target, "README.md"), "utf8")));
|
|
51
|
+
}
|
|
52
|
+
export function newApp(options) {
|
|
53
|
+
if (options.lang !== "ts" && options.lang !== "rust") {
|
|
54
|
+
throw new NewError(`--lang ${options.lang} is not available; use TypeScript (--lang ts) or Rust (--lang rust).`);
|
|
55
|
+
}
|
|
56
|
+
if (!NAME.test(options.name)) {
|
|
57
|
+
throw new NewError(`"${options.name}" is not a valid App name: lowercase letters, digits and '-', starting with a letter or digit`);
|
|
58
|
+
}
|
|
59
|
+
const target = resolve(options.parent ?? ".", options.name);
|
|
60
|
+
if (existsSync(target) && readdirSync(target).length > 0) {
|
|
61
|
+
throw new NewError(`${target} already exists and is not empty`);
|
|
62
|
+
}
|
|
63
|
+
if (options.lang === "rust") {
|
|
64
|
+
newRustApp(target, options);
|
|
65
|
+
return target;
|
|
66
|
+
}
|
|
67
|
+
cpSync(join(templates(), "ts"), target, { recursive: true });
|
|
68
|
+
renameSync(join(target, "gitignore"), join(target, ".gitignore"));
|
|
69
|
+
let app = sdkVersion();
|
|
70
|
+
let cli = sdkVersion();
|
|
71
|
+
if (options.sdk) {
|
|
72
|
+
const sdk = resolve(options.sdk);
|
|
73
|
+
if (!existsSync(join(sdk, "app", "package.json")) || !existsSync(join(sdk, "cli", "package.json"))) {
|
|
74
|
+
throw new NewError(`--sdk ${options.sdk}: expected the Pollis repo's sdk/ts directory (with app/ and cli/)`);
|
|
75
|
+
}
|
|
76
|
+
app = `link:${relative(target, join(sdk, "app"))}`;
|
|
77
|
+
cli = `link:${relative(target, join(sdk, "cli"))}`;
|
|
78
|
+
}
|
|
79
|
+
const fill = (text) => text.replaceAll("{{name}}", options.name).replaceAll("{{app}}", app).replaceAll("{{cli}}", cli);
|
|
80
|
+
const tmpl = join(target, "package.json.tmpl");
|
|
81
|
+
writeFileSync(join(target, "package.json"), fill(readFileSync(tmpl, "utf8")));
|
|
82
|
+
unlinkSync(tmpl);
|
|
83
|
+
writeFileSync(join(target, "README.md"), fill(readFileSync(join(target, "README.md"), "utf8")));
|
|
84
|
+
return target;
|
|
85
|
+
}
|
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `pollis app run` and `pollis app dev`: hand a built App to the bot runtime,
|
|
3
|
+
* `pollis-bot`, on this machine.
|
|
4
|
+
*
|
|
5
|
+
* - `run`: `pollis-bot app install --artifact <dir|url>` (prints the App hash
|
|
6
|
+
* an admin approves on the bot's page), then `pollis-bot run`.
|
|
7
|
+
* - `dev`: for a development installation, whose approval names a developer
|
|
8
|
+
* key instead of one hash. `pollis-bot app dev-key` (created once, printed
|
|
9
|
+
* for the admin to approve), `app install --artifact dist`, then
|
|
10
|
+
* `pollis-bot run`, rebuilding and `pollis-bot app sign --artifact dist`
|
|
11
|
+
* on every save. The runtime checks the file and its signature before each
|
|
12
|
+
* job, so the next job runs the new build.
|
|
13
|
+
*/
|
|
14
|
+
/** `$POLLIS_BOT_BIN`, else `pollis-bot` on PATH, else a build in the Pollis repo this CLI lives in. */
|
|
15
|
+
export declare function findBot(): string;
|
|
16
|
+
export interface RuntimeOptions {
|
|
17
|
+
dir: string;
|
|
18
|
+
installation?: string;
|
|
19
|
+
/** `pollis-bot --data-dir`, if not the default. */
|
|
20
|
+
dataDir?: string;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* `pollis app run`: install an artifact (default: build this App and use
|
|
24
|
+
* `dist/`) for an installation, then run the runtime.
|
|
25
|
+
*/
|
|
26
|
+
export declare function runApp(options: RuntimeOptions & {
|
|
27
|
+
artifact?: string;
|
|
28
|
+
}): Promise<number>;
|
|
29
|
+
/**
|
|
30
|
+
* `pollis app dev`: a development installation that follows your edits.
|
|
31
|
+
* Rebuilds and re-signs on every save under the App's source; the runtime
|
|
32
|
+
* picks the new build up at its next job.
|
|
33
|
+
*/
|
|
34
|
+
export declare function devApp(options: RuntimeOptions): Promise<number>;
|
package/dist/runtime.js
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `pollis app run` and `pollis app dev`: hand a built App to the bot runtime,
|
|
3
|
+
* `pollis-bot`, on this machine.
|
|
4
|
+
*
|
|
5
|
+
* - `run`: `pollis-bot app install --artifact <dir|url>` (prints the App hash
|
|
6
|
+
* an admin approves on the bot's page), then `pollis-bot run`.
|
|
7
|
+
* - `dev`: for a development installation, whose approval names a developer
|
|
8
|
+
* key instead of one hash. `pollis-bot app dev-key` (created once, printed
|
|
9
|
+
* for the admin to approve), `app install --artifact dist`, then
|
|
10
|
+
* `pollis-bot run`, rebuilding and `pollis-bot app sign --artifact dist`
|
|
11
|
+
* on every save. The runtime checks the file and its signature before each
|
|
12
|
+
* job, so the next job runs the new build.
|
|
13
|
+
*/
|
|
14
|
+
import { spawn, spawnSync } from "node:child_process";
|
|
15
|
+
import { accessSync, constants, existsSync, watch } from "node:fs";
|
|
16
|
+
import { delimiter, dirname, join, resolve } from "node:path";
|
|
17
|
+
import { fileURLToPath } from "node:url";
|
|
18
|
+
import { BuildError, buildApp } from "./build.js";
|
|
19
|
+
const EXE = process.platform === "win32" ? "pollis-bot.exe" : "pollis-bot";
|
|
20
|
+
function executable(path) {
|
|
21
|
+
try {
|
|
22
|
+
accessSync(path, constants.X_OK);
|
|
23
|
+
return true;
|
|
24
|
+
}
|
|
25
|
+
catch {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
/** `$POLLIS_BOT_BIN`, else `pollis-bot` on PATH, else a build in the Pollis repo this CLI lives in. */
|
|
30
|
+
export function findBot() {
|
|
31
|
+
const fromEnv = process.env.POLLIS_BOT_BIN;
|
|
32
|
+
if (fromEnv) {
|
|
33
|
+
if (!executable(fromEnv)) {
|
|
34
|
+
throw new BuildError(`POLLIS_BOT_BIN is ${fromEnv}, which is not an executable file`);
|
|
35
|
+
}
|
|
36
|
+
return fromEnv;
|
|
37
|
+
}
|
|
38
|
+
for (const dir of (process.env.PATH ?? "").split(delimiter)) {
|
|
39
|
+
if (dir && executable(join(dir, EXE))) {
|
|
40
|
+
return join(dir, EXE);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
let dir = dirname(fileURLToPath(import.meta.url));
|
|
44
|
+
for (let i = 0; i < 6; i++) {
|
|
45
|
+
for (const profile of ["release", "debug"]) {
|
|
46
|
+
const candidate = join(dir, "target", profile, EXE);
|
|
47
|
+
if (existsSync(join(dir, "Cargo.toml")) && executable(candidate)) {
|
|
48
|
+
return candidate;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
dir = dirname(dir);
|
|
52
|
+
}
|
|
53
|
+
throw new BuildError("`pollis-bot` was not found. It is the runtime that runs your App for a group.\n" +
|
|
54
|
+
"Install it (docs/bots/self-hosting.md), put it on your PATH, or set POLLIS_BOT_BIN.");
|
|
55
|
+
}
|
|
56
|
+
function botArgs(options, args) {
|
|
57
|
+
return options.dataDir ? ["--data-dir", options.dataDir, ...args] : args;
|
|
58
|
+
}
|
|
59
|
+
function installation(options) {
|
|
60
|
+
if (!options.installation) {
|
|
61
|
+
throw new BuildError("say which installation with --installation <id> (`pollis-bot status` lists them)");
|
|
62
|
+
}
|
|
63
|
+
return options.installation;
|
|
64
|
+
}
|
|
65
|
+
/** Run a `pollis-bot` step to completion with its output on this terminal. */
|
|
66
|
+
function step(bot, options, args) {
|
|
67
|
+
const result = spawnSync(bot, botArgs(options, args), { stdio: "inherit" });
|
|
68
|
+
if (result.error) {
|
|
69
|
+
throw result.error;
|
|
70
|
+
}
|
|
71
|
+
if (result.status !== 0) {
|
|
72
|
+
throw new BuildError(`\`pollis-bot ${args.slice(0, 2).join(" ")}\` failed (exit ${result.status})`);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
/** `pollis-bot run` in the foreground; resolves with its exit code. */
|
|
76
|
+
function runBot(bot, options) {
|
|
77
|
+
const child = spawn(bot, botArgs(options, ["run"]), { stdio: "inherit" });
|
|
78
|
+
const done = new Promise((resolveDone, reject) => {
|
|
79
|
+
child.on("error", reject);
|
|
80
|
+
child.on("exit", (code, signal) => resolveDone(code ?? (signal ? 1 : 0)));
|
|
81
|
+
});
|
|
82
|
+
for (const sig of ["SIGINT", "SIGTERM"]) {
|
|
83
|
+
process.once(sig, () => child.kill(sig));
|
|
84
|
+
}
|
|
85
|
+
return { child, done };
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* `pollis app run`: install an artifact (default: build this App and use
|
|
89
|
+
* `dist/`) for an installation, then run the runtime.
|
|
90
|
+
*/
|
|
91
|
+
export async function runApp(options) {
|
|
92
|
+
const bot = findBot();
|
|
93
|
+
const id = installation(options);
|
|
94
|
+
let artifact = options.artifact;
|
|
95
|
+
if (!artifact) {
|
|
96
|
+
const built = await buildApp({ dir: options.dir, quiet: true });
|
|
97
|
+
console.log(`built ${built.manifest.name} ${built.manifest.version} (App hash ${built.appHash})`);
|
|
98
|
+
artifact = dirname(built.component);
|
|
99
|
+
}
|
|
100
|
+
else if (!/^https:\/\//.test(artifact)) {
|
|
101
|
+
artifact = resolve(artifact);
|
|
102
|
+
}
|
|
103
|
+
step(bot, options, ["app", "install", "--installation", id, "--artifact", artifact]);
|
|
104
|
+
return runBot(bot, options).done;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* `pollis app dev`: a development installation that follows your edits.
|
|
108
|
+
* Rebuilds and re-signs on every save under the App's source; the runtime
|
|
109
|
+
* picks the new build up at its next job.
|
|
110
|
+
*/
|
|
111
|
+
export async function devApp(options) {
|
|
112
|
+
const bot = findBot();
|
|
113
|
+
const id = installation(options);
|
|
114
|
+
const dir = resolve(options.dir);
|
|
115
|
+
console.log("Your developer key (an admin approves it once, with Development installation on, on the bot's page):");
|
|
116
|
+
step(bot, options, ["app", "dev-key"]);
|
|
117
|
+
const build = async () => {
|
|
118
|
+
try {
|
|
119
|
+
const built = await buildApp({ dir, quiet: true });
|
|
120
|
+
step(bot, options, ["app", "sign", "--artifact", dirname(built.component)]);
|
|
121
|
+
console.log(`[pollis app dev] built and signed ${built.manifest.name} ${built.manifest.version} (App hash ${built.appHash})`);
|
|
122
|
+
return true;
|
|
123
|
+
}
|
|
124
|
+
catch (e) {
|
|
125
|
+
console.error(`[pollis app dev] build failed; the bot keeps the last good build:\n${e.message}`);
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
};
|
|
129
|
+
if (!(await build())) {
|
|
130
|
+
return 1;
|
|
131
|
+
}
|
|
132
|
+
step(bot, options, ["app", "install", "--installation", id, "--artifact", join(dir, "dist")]);
|
|
133
|
+
// Rebuild on save: one build at a time, and edits made during a build
|
|
134
|
+
// trigger exactly one more.
|
|
135
|
+
let building = false;
|
|
136
|
+
let again = false;
|
|
137
|
+
const rebuild = async () => {
|
|
138
|
+
if (building) {
|
|
139
|
+
again = true;
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
building = true;
|
|
143
|
+
do {
|
|
144
|
+
again = false;
|
|
145
|
+
await build();
|
|
146
|
+
} while (again);
|
|
147
|
+
building = false;
|
|
148
|
+
};
|
|
149
|
+
const watched = ["src", "package.json", "Cargo.toml", "Cargo.lock"].map((p) => join(dir, p)).filter((p) => existsSync(p));
|
|
150
|
+
const watchers = watched.map((p) => watch(p, { recursive: true }, () => {
|
|
151
|
+
void rebuild();
|
|
152
|
+
}));
|
|
153
|
+
console.log(`[pollis app dev] watching ${watched.map((p) => p.slice(dir.length + 1)).join(", ")}; Ctrl+C stops`);
|
|
154
|
+
const { done } = runBot(bot, options);
|
|
155
|
+
const code = await done;
|
|
156
|
+
for (const w of watchers) {
|
|
157
|
+
w.close();
|
|
158
|
+
}
|
|
159
|
+
return code;
|
|
160
|
+
}
|
package/dist/rust.d.ts
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `pollis app build` and `test` for an App written in Rust.
|
|
3
|
+
*
|
|
4
|
+
* 1. Run the App's generated `__pollis_app_describe` test natively, which
|
|
5
|
+
* writes what `pollis_app::app!` declares, and resolve the manifest with the
|
|
6
|
+
* same code a TypeScript App uses.
|
|
7
|
+
* 2. `cargo build --target wasm32-wasip2`: rustc links a component directly, so
|
|
8
|
+
* an App developer needs no extra tool. Source paths are remapped out of the
|
|
9
|
+
* binary and the lockfile is enforced, so the same source, lockfile and
|
|
10
|
+
* toolchain give the same bytes wherever they are built.
|
|
11
|
+
*/
|
|
12
|
+
import { type ResolvedManifest } from "@pollis-inc/app/manifest";
|
|
13
|
+
/** Whether `dir` holds a Rust App: a crate that depends on `pollis-app`. */
|
|
14
|
+
export declare function isRustApp(dir: string): boolean;
|
|
15
|
+
export interface RustBuild {
|
|
16
|
+
manifest: ResolvedManifest;
|
|
17
|
+
component: Uint8Array;
|
|
18
|
+
}
|
|
19
|
+
/** Compile the Rust App in `dir` to a component and read its manifest. */
|
|
20
|
+
export declare function compileRust(dir: string, scratch: string): RustBuild;
|
|
21
|
+
/** Run the App's Rust tests against the build in `dist/`. */
|
|
22
|
+
export declare function testRust(dir: string, patterns: string[], env: NodeJS.ProcessEnv): number;
|
package/dist/rust.js
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `pollis app build` and `test` for an App written in Rust.
|
|
3
|
+
*
|
|
4
|
+
* 1. Run the App's generated `__pollis_app_describe` test natively, which
|
|
5
|
+
* writes what `pollis_app::app!` declares, and resolve the manifest with the
|
|
6
|
+
* same code a TypeScript App uses.
|
|
7
|
+
* 2. `cargo build --target wasm32-wasip2`: rustc links a component directly, so
|
|
8
|
+
* an App developer needs no extra tool. Source paths are remapped out of the
|
|
9
|
+
* binary and the lockfile is enforced, so the same source, lockfile and
|
|
10
|
+
* toolchain give the same bytes wherever they are built.
|
|
11
|
+
*/
|
|
12
|
+
import { spawnSync } from "node:child_process";
|
|
13
|
+
import { existsSync, readFileSync, realpathSync } from "node:fs";
|
|
14
|
+
import { homedir } from "node:os";
|
|
15
|
+
import { dirname, join } from "node:path";
|
|
16
|
+
import { ManifestError, resolveManifest } from "@pollis-inc/app/manifest";
|
|
17
|
+
import { BuildError } from "./errors.js";
|
|
18
|
+
const TARGET = "wasm32-wasip2";
|
|
19
|
+
const NO_CARGO = "`cargo` was not found. Rust Apps need Rust: install it from https://rustup.rs";
|
|
20
|
+
/** Whether `dir` holds a Rust App: a crate that depends on `pollis-app`. */
|
|
21
|
+
export function isRustApp(dir) {
|
|
22
|
+
const path = join(dir, "Cargo.toml");
|
|
23
|
+
return existsSync(path) && /^\s*(pollis-app\s*[=.]|\[dependencies\.pollis-app\])/m.test(readFileSync(path, "utf8"));
|
|
24
|
+
}
|
|
25
|
+
function cargo(dir, args, env = {}) {
|
|
26
|
+
const result = spawnSync("cargo", args, {
|
|
27
|
+
cwd: dir,
|
|
28
|
+
encoding: "utf8",
|
|
29
|
+
maxBuffer: 256 * 1024 * 1024,
|
|
30
|
+
env: { ...process.env, ...env },
|
|
31
|
+
});
|
|
32
|
+
if (result.error?.code === "ENOENT") {
|
|
33
|
+
throw new BuildError(NO_CARGO);
|
|
34
|
+
}
|
|
35
|
+
if (result.error) {
|
|
36
|
+
throw result.error;
|
|
37
|
+
}
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
/** Cargo's error, with the fix for the mistakes a new App developer is likely to hit. */
|
|
41
|
+
function cargoFailure(what, stderr) {
|
|
42
|
+
let advice = "";
|
|
43
|
+
if (/no matching package named `pollis-app`/.test(stderr)) {
|
|
44
|
+
advice =
|
|
45
|
+
"\n\nThe `pollis-app` crate could not be downloaded. To use the copy in a Pollis checkout, create the App " +
|
|
46
|
+
"with `pollis app new <name> --lang rust --sdk <checkout>/sdk/ts`.";
|
|
47
|
+
}
|
|
48
|
+
else if (/can't find crate for `(core|std)`|target may not be installed/.test(stderr)) {
|
|
49
|
+
advice = `\n\nThe WebAssembly target is missing. Install it with: rustup target add ${TARGET}`;
|
|
50
|
+
}
|
|
51
|
+
else if (/lock file .* needs to be updated|--locked was passed/.test(stderr)) {
|
|
52
|
+
advice = "\n\nCargo.lock does not match Cargo.toml. Run `cargo update --workspace`, then commit Cargo.lock.";
|
|
53
|
+
}
|
|
54
|
+
return new BuildError(`${what} failed:\n${stderr.trim()}${advice}`);
|
|
55
|
+
}
|
|
56
|
+
function metadata(dir) {
|
|
57
|
+
const result = cargo(dir, ["metadata", "--format-version", "1", "--locked"]);
|
|
58
|
+
if (result.status !== 0) {
|
|
59
|
+
throw cargoFailure("`cargo metadata`", result.stderr);
|
|
60
|
+
}
|
|
61
|
+
const meta = JSON.parse(result.stdout);
|
|
62
|
+
const manifest = join(realpathSync(dir), "Cargo.toml");
|
|
63
|
+
const root = meta.packages.find((p) => p.manifest_path === manifest);
|
|
64
|
+
if (!root) {
|
|
65
|
+
throw new BuildError(`no package in ${manifest}; a Rust App is a single crate, not a virtual workspace`);
|
|
66
|
+
}
|
|
67
|
+
return { root, packages: meta.packages, targetDir: meta.target_directory };
|
|
68
|
+
}
|
|
69
|
+
/** Handler names as Rust spells them, in a message written for TypeScript. */
|
|
70
|
+
function rustNames(message) {
|
|
71
|
+
return message.replace(/\bon[A-Z][a-z]+\b/g, (name) => name.replace(/[A-Z]/g, (c) => `_${c.toLowerCase()}`));
|
|
72
|
+
}
|
|
73
|
+
/** Read the manifest out of the code, by running the App's describe test natively. */
|
|
74
|
+
function describe(dir, scratch) {
|
|
75
|
+
const out = join(scratch, "describe.json");
|
|
76
|
+
const result = cargo(dir, ["test", "--locked", "--lib", "--quiet", "--", "__pollis_app_describe"], {
|
|
77
|
+
POLLIS_APP_DESCRIBE_OUT: out,
|
|
78
|
+
});
|
|
79
|
+
if (result.status !== 0) {
|
|
80
|
+
throw cargoFailure("compiling the App", result.stderr || result.stdout);
|
|
81
|
+
}
|
|
82
|
+
if (!existsSync(out)) {
|
|
83
|
+
throw new BuildError("src/lib.rs must call `pollis_app::app! { manifest: ..., on_command: ... }` at the root of the crate");
|
|
84
|
+
}
|
|
85
|
+
const described = JSON.parse(readFileSync(out, "utf8"));
|
|
86
|
+
try {
|
|
87
|
+
return resolveManifest(described.manifest, described.handlers, described.package);
|
|
88
|
+
}
|
|
89
|
+
catch (e) {
|
|
90
|
+
if (e instanceof ManifestError) {
|
|
91
|
+
throw new BuildError(`manifest: ${rustNames(e.message)}`);
|
|
92
|
+
}
|
|
93
|
+
throw e;
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The flags that keep machine-specific paths out of the component. Later
|
|
98
|
+
* remaps win, so the more specific paths come after the App's own directory.
|
|
99
|
+
*/
|
|
100
|
+
function rustFlags(dir, packages, targetDir) {
|
|
101
|
+
const cargoHome = process.env.CARGO_HOME ?? join(homedir(), ".cargo");
|
|
102
|
+
const remaps = [
|
|
103
|
+
[realpathSync(dir), "/app"],
|
|
104
|
+
[cargoHome, "/cargo"],
|
|
105
|
+
...packages
|
|
106
|
+
.filter((p) => p.source === null)
|
|
107
|
+
.map((p) => [dirname(p.manifest_path), `/path/${p.name}`]),
|
|
108
|
+
[targetDir, "/target"],
|
|
109
|
+
];
|
|
110
|
+
const flags = ["-Cdebuginfo=0", "-Cstrip=symbols", ...remaps.map(([from, to]) => `--remap-path-prefix=${from}=${to}`)];
|
|
111
|
+
// CARGO_ENCODED_RUSTFLAGS replaces anything set in RUSTFLAGS or .cargo/config.toml.
|
|
112
|
+
return flags.join("\x1f");
|
|
113
|
+
}
|
|
114
|
+
/** Compile the Rust App in `dir` to a component and read its manifest. */
|
|
115
|
+
export function compileRust(dir, scratch) {
|
|
116
|
+
if (!existsSync(join(dir, "Cargo.lock"))) {
|
|
117
|
+
const locked = cargo(dir, ["generate-lockfile"]);
|
|
118
|
+
if (locked.status !== 0) {
|
|
119
|
+
throw cargoFailure("`cargo generate-lockfile`", locked.stderr);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const { root, packages, targetDir } = metadata(dir);
|
|
123
|
+
const lib = root.targets.find((t) => t.crate_types.includes("cdylib"));
|
|
124
|
+
if (!lib) {
|
|
125
|
+
throw new BuildError('Cargo.toml needs a component library: add `[lib]` with `crate-type = ["cdylib"]`');
|
|
126
|
+
}
|
|
127
|
+
const manifest = describe(dir, scratch);
|
|
128
|
+
const result = cargo(dir, ["build", "--locked", "--release", "--lib", "--target", TARGET], {
|
|
129
|
+
CARGO_ENCODED_RUSTFLAGS: rustFlags(dir, packages, targetDir),
|
|
130
|
+
SOURCE_DATE_EPOCH: "0",
|
|
131
|
+
});
|
|
132
|
+
if (result.status !== 0) {
|
|
133
|
+
throw cargoFailure("compiling to a component", result.stderr);
|
|
134
|
+
}
|
|
135
|
+
const wasm = join(targetDir, TARGET, "release", `${lib.name.replaceAll("-", "_")}.wasm`);
|
|
136
|
+
return { manifest, component: readFileSync(wasm) };
|
|
137
|
+
}
|
|
138
|
+
/** Run the App's Rust tests against the build in `dist/`. */
|
|
139
|
+
export function testRust(dir, patterns, env) {
|
|
140
|
+
const filters = patterns.length > 0 ? ["--", ...patterns] : [];
|
|
141
|
+
const result = spawnSync("cargo", ["test", "--locked", ...filters], {
|
|
142
|
+
cwd: dir,
|
|
143
|
+
stdio: "inherit",
|
|
144
|
+
env: { ...process.env, ...env },
|
|
145
|
+
});
|
|
146
|
+
if (result.error?.code === "ENOENT") {
|
|
147
|
+
throw new BuildError(NO_CARGO);
|
|
148
|
+
}
|
|
149
|
+
return result.status ?? 1;
|
|
150
|
+
}
|
package/dist/test.d.ts
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `pollis app test`: build the App, then run its tests against the build. A
|
|
3
|
+
* TypeScript App's `*.test.ts` files run under Node's test runner, wired up
|
|
4
|
+
* through `@pollis-inc/app/testing`; a Rust App's run under `cargo test`, wired
|
|
5
|
+
* up through `pollis_app::testing`.
|
|
6
|
+
*/
|
|
7
|
+
export interface TestOptions {
|
|
8
|
+
dir: string;
|
|
9
|
+
build: boolean;
|
|
10
|
+
/** Test file globs, relative to `dir`. For a Rust App, `cargo test` name filters. */
|
|
11
|
+
patterns: string[];
|
|
12
|
+
}
|
|
13
|
+
export declare function testApp(options: TestOptions): Promise<number>;
|
package/dist/test.js
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `pollis app test`: build the App, then run its tests against the build. A
|
|
3
|
+
* TypeScript App's `*.test.ts` files run under Node's test runner, wired up
|
|
4
|
+
* through `@pollis-inc/app/testing`; a Rust App's run under `cargo test`, wired
|
|
5
|
+
* up through `pollis_app::testing`.
|
|
6
|
+
*/
|
|
7
|
+
import { spawnSync } from "node:child_process";
|
|
8
|
+
import { globSync } from "node:fs";
|
|
9
|
+
import { join, resolve } from "node:path";
|
|
10
|
+
import { buildApp } from "./build.js";
|
|
11
|
+
import { findDevTool } from "./devtool.js";
|
|
12
|
+
import { isRustApp, testRust } from "./rust.js";
|
|
13
|
+
export async function testApp(options) {
|
|
14
|
+
const dir = resolve(options.dir);
|
|
15
|
+
const bin = findDevTool();
|
|
16
|
+
const component = join(dir, "dist", "app.wasm");
|
|
17
|
+
const manifest = join(dir, "dist", "pollis-app.json");
|
|
18
|
+
if (options.build) {
|
|
19
|
+
const built = await buildApp({ dir, quiet: true });
|
|
20
|
+
console.log(`built ${built.manifest.name} ${built.manifest.version} (App hash ${built.appHash})`);
|
|
21
|
+
}
|
|
22
|
+
if (isRustApp(dir)) {
|
|
23
|
+
return testRust(dir, options.patterns, {
|
|
24
|
+
POLLIS_APP_COMPONENT: component,
|
|
25
|
+
POLLIS_APP_MANIFEST: manifest,
|
|
26
|
+
POLLIS_APP_DEV_BIN: bin,
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
const patterns = options.patterns.length > 0 ? options.patterns : ["src/**/*.test.ts", "test/**/*.test.ts"];
|
|
30
|
+
const files = patterns.flatMap((p) => globSync(p, { cwd: dir })).sort();
|
|
31
|
+
if (files.length === 0) {
|
|
32
|
+
console.error(`no test files matching ${patterns.join(", ")}`);
|
|
33
|
+
return 1;
|
|
34
|
+
}
|
|
35
|
+
const result = spawnSync(process.execPath, ["--test", "--test-concurrency=1", ...files], {
|
|
36
|
+
cwd: dir,
|
|
37
|
+
stdio: "inherit",
|
|
38
|
+
env: {
|
|
39
|
+
...process.env,
|
|
40
|
+
// Report to this terminal even when `pollis app test` itself runs under
|
|
41
|
+
// a test runner.
|
|
42
|
+
NODE_TEST_CONTEXT: undefined,
|
|
43
|
+
POLLIS_APP_COMPONENT: component,
|
|
44
|
+
POLLIS_APP_MANIFEST: manifest,
|
|
45
|
+
POLLIS_APP_DEV_BIN: bin,
|
|
46
|
+
},
|
|
47
|
+
});
|
|
48
|
+
return result.status ?? 1;
|
|
49
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,36 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pollis-inc/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "The `pollis app` command: create, build and test Pollis Apps.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"homepage": "https://pollis.com/bots-developers.html",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/pollis-app/pollis.git",
|
|
10
|
+
"directory": "sdk/ts/cli"
|
|
11
|
+
},
|
|
12
|
+
"type": "module",
|
|
13
|
+
"bin": {
|
|
14
|
+
"pollis": "./dist/main.js"
|
|
15
|
+
},
|
|
16
|
+
"files": [
|
|
17
|
+
"dist",
|
|
18
|
+
"templates"
|
|
19
|
+
],
|
|
20
|
+
"engines": {
|
|
21
|
+
"node": ">=22.18"
|
|
22
|
+
},
|
|
23
|
+
"dependencies": {
|
|
24
|
+
"@bytecodealliance/componentize-js": "0.23.0",
|
|
25
|
+
"esbuild": "0.28.2",
|
|
26
|
+
"@pollis-inc/app": "0.1.1"
|
|
27
|
+
},
|
|
28
|
+
"devDependencies": {
|
|
29
|
+
"@types/node": "^22.19.0",
|
|
30
|
+
"typescript": "5.9.3"
|
|
31
|
+
},
|
|
32
|
+
"scripts": {
|
|
33
|
+
"build": "tsc -p tsconfig.json",
|
|
34
|
+
"test": "pnpm -s build && node --test --test-concurrency=1 test/*.test.ts"
|
|
35
|
+
}
|
|
6
36
|
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
[package]
|
|
2
|
+
name = "{{name}}"
|
|
3
|
+
version = "0.1.0"
|
|
4
|
+
edition = "2021"
|
|
5
|
+
description = "A Pollis App."
|
|
6
|
+
publish = false
|
|
7
|
+
|
|
8
|
+
[lib]
|
|
9
|
+
name = "app"
|
|
10
|
+
crate-type = ["cdylib"]
|
|
11
|
+
|
|
12
|
+
[dependencies]
|
|
13
|
+
pollis-app = {{pollis_app}}
|
|
14
|
+
|
|
15
|
+
# Small and reproducible: the same source and Cargo.lock give the same App hash.
|
|
16
|
+
[profile.release]
|
|
17
|
+
opt-level = "s"
|
|
18
|
+
lto = true
|
|
19
|
+
codegen-units = 1
|
|
20
|
+
panic = "abort"
|
|
21
|
+
strip = true
|
|
22
|
+
|
|
23
|
+
# This App stands alone, even inside another Cargo workspace.
|
|
24
|
+
[workspace]
|
|
25
|
+
exclude = ["vendor"]
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# {{name}}
|
|
2
|
+
|
|
3
|
+
A [Pollis](https://pollis.com) App, in Rust. It answers `/hello` with a greeting.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npx pollis app test # build, then run tests/hello.rs against the built App, offline
|
|
7
|
+
npx pollis app build # writes dist/app.wasm and dist/pollis-app.json, prints the App hash
|
|
8
|
+
```
|
|
9
|
+
|
|
10
|
+
- `src/lib.rs`: the App. Its `manifest` says what it needs; its handlers say what it does.
|
|
11
|
+
- `tests/hello.rs`: tests. Each one runs the built App in the same sandbox the bot
|
|
12
|
+
runtime uses, so anything the manifest does not allow fails here too.
|
|
13
|
+
- `Cargo.lock` and `rust-toolchain.toml`: commit both. With them, anyone can rebuild this
|
|
14
|
+
App from source and get the same App hash.
|
|
15
|
+
- `dist/`: build output. The App hash identifies exactly this build; an admin approves it.
|
|
16
|
+
|
|
17
|
+
The developer guide explains every handler, what `ctx` can do, the manifest and the
|
|
18
|
+
sandbox's limits: https://github.com/pollis-app/pollis/blob/main/docs/bots/developer-guide.md
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
use pollis_app::{Action, Command, CommandSpec, Context, Manifest};
|
|
2
|
+
|
|
3
|
+
// Runs when a member sends one of the commands declared below, e.g. "/hello Sam".
|
|
4
|
+
fn on_command(cmd: Command, ctx: &Context) -> pollis_app::Result {
|
|
5
|
+
if cmd.name != "hello" {
|
|
6
|
+
return Ok(());
|
|
7
|
+
}
|
|
8
|
+
let who = match cmd.args.trim() {
|
|
9
|
+
"" => cmd.message.author.display_name.as_str(),
|
|
10
|
+
name => name,
|
|
11
|
+
};
|
|
12
|
+
ctx.reply(&cmd.message, format!("Hello, {who}!"))
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
pollis_app::app! {
|
|
16
|
+
manifest: Manifest::new()
|
|
17
|
+
// Where the App works. "*" means: whichever channels the admin picks
|
|
18
|
+
// when approving it. Use "#name" to ask for one channel by name.
|
|
19
|
+
.channels(["*"])
|
|
20
|
+
// What the App may do there. The admin sees this list before approving.
|
|
21
|
+
.actions([Action::Reply])
|
|
22
|
+
// No `.egress(...)`: this App cannot send anything outside the group.
|
|
23
|
+
// The slash commands members can pick in the composer.
|
|
24
|
+
.command(CommandSpec::new("hello", "Say hello").arg_hint("[name]")),
|
|
25
|
+
on_command: on_command,
|
|
26
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
use pollis_app::testing::{AuthorInput, JobOptions, MessageInput, TestApp};
|
|
2
|
+
|
|
3
|
+
// Each test runs the built App in the same sandbox the bot runtime uses, offline.
|
|
4
|
+
|
|
5
|
+
#[test]
|
|
6
|
+
fn hello_greets_by_name() {
|
|
7
|
+
let result = TestApp::new().command("hello", "Sam");
|
|
8
|
+
assert!(result.ok, "{:?}", result.error);
|
|
9
|
+
assert_eq!(result.replies, ["Hello, Sam!"]);
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
#[test]
|
|
13
|
+
fn hello_with_no_name_greets_the_sender() {
|
|
14
|
+
let app = TestApp::new();
|
|
15
|
+
let sender = MessageInput::default().author(AuthorInput::named("Ann"));
|
|
16
|
+
let result = app.with(JobOptions::new()).command_from("hello", "", sender);
|
|
17
|
+
assert_eq!(result.replies, ["Hello, Ann!"]);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
#[test]
|
|
21
|
+
fn a_command_the_app_did_not_declare_never_reaches_it() {
|
|
22
|
+
let result = TestApp::new().command("weather", "");
|
|
23
|
+
assert!(result.actions.is_empty());
|
|
24
|
+
}
|