@pollis-inc/cli 0.0.0-stage → 0.1.0

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.
@@ -0,0 +1,36 @@
1
+ /**
2
+ * `pollis app build`: TypeScript in, a sandboxed component and its manifest out.
3
+ *
4
+ * 1. Bundle the App with esbuild (refusing Node built-ins) and import it in
5
+ * Node to read `app({ manifest })`; check it and write `pollis-app.json`.
6
+ * 2. Bundle it again for the sandbox, behind a generated entry that exports
7
+ * the six `pollis:app@0.1.0` handlers.
8
+ * 3. Compile that with ComponentizeJS (StarlingMonkey), pre-initialized by
9
+ * `pollis-app-dev` with fixed randomness and clocks, in a fixed staging
10
+ * directory: the same source and lockfile give the same bytes.
11
+ * 4. Load the component in the real App host (`pollis-app-dev check`), so an
12
+ * App the runtime would refuse is refused here, and print its App hash.
13
+ */
14
+ import { type Plugin } from "esbuild";
15
+ import { type ResolvedManifest } from "@pollis-inc/app/manifest";
16
+ export interface BuildOptions {
17
+ /** Project directory (holds package.json). */
18
+ dir: string;
19
+ /** App entry, relative to `dir`. Default: package.json `pollis.entry`, else src/app.ts. */
20
+ entry?: string;
21
+ /** Output directory, relative to `dir`. Default dist. */
22
+ out?: string;
23
+ quiet?: boolean;
24
+ }
25
+ export interface BuildResult {
26
+ component: string;
27
+ manifestPath: string;
28
+ manifest: ResolvedManifest;
29
+ appHash: string;
30
+ bytes: number;
31
+ }
32
+ export declare class BuildError extends Error {
33
+ }
34
+ /** Refuses every Node built-in, naming the importer and saying why. */
35
+ export declare function noNodeBuiltins(): Plugin;
36
+ export declare function buildApp(options: BuildOptions): Promise<BuildResult>;
package/dist/build.js ADDED
@@ -0,0 +1,321 @@
1
+ /**
2
+ * `pollis app build`: TypeScript in, a sandboxed component and its manifest out.
3
+ *
4
+ * 1. Bundle the App with esbuild (refusing Node built-ins) and import it in
5
+ * Node to read `app({ manifest })`; check it and write `pollis-app.json`.
6
+ * 2. Bundle it again for the sandbox, behind a generated entry that exports
7
+ * the six `pollis:app@0.1.0` handlers.
8
+ * 3. Compile that with ComponentizeJS (StarlingMonkey), pre-initialized by
9
+ * `pollis-app-dev` with fixed randomness and clocks, in a fixed staging
10
+ * directory: the same source and lockfile give the same bytes.
11
+ * 4. Load the component in the real App host (`pollis-app-dev check`), so an
12
+ * App the runtime would refuse is refused here, and print its App hash.
13
+ */
14
+ import { builtinModules, createRequire } from "node:module";
15
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
16
+ import { tmpdir } from "node:os";
17
+ import { join, relative, resolve } from "node:path";
18
+ import { pathToFileURL } from "node:url";
19
+ import { build as esbuild } from "esbuild";
20
+ import { isApp } from "@pollis-inc/app";
21
+ import { HANDLER_FOR, ManifestError, resolveManifest } from "@pollis-inc/app/manifest";
22
+ import { devTool, findDevTool } from "./devtool.js";
23
+ export class BuildError extends Error {
24
+ }
25
+ /**
26
+ * Packages are resolved as for a browser: the sandbox has web basics
27
+ * (`crypto.getRandomValues`, TextEncoder, timers) and no Node built-ins, so a
28
+ * package's browser build is usually the one that works. HTTP is ctx.fetch.
29
+ */
30
+ const MAIN_FIELDS = ["browser", "module", "main"];
31
+ const CONDITIONS = ["browser", "import", "default"];
32
+ const BUILTINS = new Set(builtinModules.flatMap((m) => [m, `node:${m}`]));
33
+ /** What each Node built-in is usually reached for, and what to use instead. */
34
+ function builtinAdvice(name) {
35
+ const bare = name.replace(/^node:/, "").split("/")[0];
36
+ switch (bare) {
37
+ case "fs":
38
+ case "path":
39
+ return "Apps have no files. Keep data in ctx.state (sealed key-value state, `state.quota` in the manifest).";
40
+ case "net":
41
+ case "http":
42
+ case "https":
43
+ case "http2":
44
+ case "dgram":
45
+ case "dns":
46
+ case "tls":
47
+ return "Apps have no sockets. Use ctx.fetch, which reaches only the hosts listed in `egress`.";
48
+ case "child_process":
49
+ case "worker_threads":
50
+ case "cluster":
51
+ return "Apps cannot start processes or threads.";
52
+ case "crypto":
53
+ return "Use the web's crypto.getRandomValues() (built in) or a pure-JS library.";
54
+ default:
55
+ return "Apps run in a sandbox with no files, sockets or processes; only pure-JS packages work.";
56
+ }
57
+ }
58
+ /** Refuses every Node built-in, naming the importer and saying why. */
59
+ export function noNodeBuiltins() {
60
+ return {
61
+ name: "pollis-no-node-builtins",
62
+ setup(build) {
63
+ build.onResolve({ filter: /.*/ }, (args) => {
64
+ if (!BUILTINS.has(args.path)) {
65
+ return undefined;
66
+ }
67
+ return {
68
+ errors: [
69
+ {
70
+ text: `\`${args.path}\` is a Node built-in, and Pollis Apps cannot use Node built-ins. ${builtinAdvice(args.path)}`,
71
+ },
72
+ ],
73
+ };
74
+ });
75
+ },
76
+ };
77
+ }
78
+ function readJson(path) {
79
+ return JSON.parse(readFileSync(path, "utf8"));
80
+ }
81
+ function formatEsbuildError(e) {
82
+ const errors = e.errors;
83
+ if (!errors?.length) {
84
+ return e.message ?? String(e);
85
+ }
86
+ return errors
87
+ .map((err) => (err.location ? `${err.location.file}:${err.location.line}:${err.location.column}: ${err.text}` : err.text))
88
+ .join("\n");
89
+ }
90
+ /** Bundle for Node and import it, to read the App's definition. */
91
+ async function loadDefinition(dir, entry, scratch) {
92
+ const outfile = join(scratch, "manifest-probe.mjs");
93
+ try {
94
+ await esbuild({
95
+ absWorkingDir: dir,
96
+ entryPoints: [entry],
97
+ bundle: true,
98
+ platform: "neutral",
99
+ mainFields: MAIN_FIELDS,
100
+ conditions: CONDITIONS,
101
+ format: "esm",
102
+ target: "es2022",
103
+ outfile,
104
+ logLevel: "silent",
105
+ plugins: [noNodeBuiltins()],
106
+ });
107
+ }
108
+ catch (e) {
109
+ throw new BuildError(formatEsbuildError(e));
110
+ }
111
+ const mod = (await import(pathToFileURL(outfile).href + `?t=${Date.now()}`));
112
+ if (!isApp(mod.default)) {
113
+ throw new BuildError(`${entry} must \`export default app({ manifest, ...handlers })\` from "@pollis-inc/app"`);
114
+ }
115
+ return mod.default;
116
+ }
117
+ /** The generated module the component is built from. */
118
+ function entrySource(entry) {
119
+ const handlers = Object.values(HANDLER_FOR);
120
+ return [
121
+ `import definition from ${JSON.stringify("./" + entry.replace(/\\/g, "/"))};`,
122
+ `import { exportsFor } from "@pollis-inc/app/runtime";`,
123
+ `const handlers = exportsFor(definition);`,
124
+ ...handlers.map((h) => `export function ${h}(arg) { return handlers.${h}(arg); }`),
125
+ "",
126
+ ].join("\n");
127
+ }
128
+ /** Where ComponentizeJS runs. Fixed, because its paths end up in the component. */
129
+ function stageDir() {
130
+ return process.platform === "win32" ? join(tmpdir(), "pollis-app-build") : "/tmp/pollis-app-build";
131
+ }
132
+ /** Hold the staging directory for one build at a time. */
133
+ function lockStage(stage) {
134
+ const lock = `${stage}.lock`;
135
+ try {
136
+ mkdirSync(lock);
137
+ }
138
+ catch {
139
+ let owner = 0;
140
+ try {
141
+ owner = Number(readFileSync(join(lock, "pid"), "utf8"));
142
+ }
143
+ catch {
144
+ // Lock directory without a pid: a build that crashed while starting.
145
+ }
146
+ let alive = false;
147
+ if (owner > 0) {
148
+ try {
149
+ process.kill(owner, 0);
150
+ alive = true;
151
+ }
152
+ catch {
153
+ alive = false;
154
+ }
155
+ }
156
+ if (alive) {
157
+ throw new BuildError(`another \`pollis app build\` is running (pid ${owner}); run this one when it finishes`);
158
+ }
159
+ rmSync(lock, { recursive: true, force: true });
160
+ mkdirSync(lock);
161
+ }
162
+ writeFileSync(join(lock, "pid"), String(process.pid));
163
+ return () => rmSync(lock, { recursive: true, force: true });
164
+ }
165
+ /** A seeded `Math.random`, for ComponentizeJS's work-directory name. */
166
+ function seededRandom() {
167
+ let seed = 1;
168
+ return () => {
169
+ seed = (seed * 16807) % 2147483647;
170
+ return seed / 2147483647;
171
+ };
172
+ }
173
+ async function componentize(bundle, wit, wizerBin) {
174
+ const { componentize: run } = await import("@bytecodealliance/componentize-js");
175
+ const stage = stageDir();
176
+ const unlock = lockStage(stage);
177
+ const cwd = process.cwd();
178
+ const tmp = process.env.TMPDIR;
179
+ const random = Math.random;
180
+ try {
181
+ rmSync(stage, { recursive: true, force: true });
182
+ mkdirSync(join(stage, "src"), { recursive: true });
183
+ writeFileSync(join(stage, "src", "app.js"), bundle);
184
+ process.chdir(join(stage, "src"));
185
+ process.env.TMPDIR = stage;
186
+ Math.random = seededRandom();
187
+ // `witWorld` (the WIT as text) is supported but missing from the package's
188
+ // types. A path (`witPath`) would be read through ComponentizeJS's WASI
189
+ // shim, which cannot see arbitrary host paths.
190
+ const { component } = await run({
191
+ sourcePath: "app.js",
192
+ witWorld: wit,
193
+ worldName: "app",
194
+ // No wasi:http: the App host refuses it. Network access is ctx.fetch.
195
+ disableFeatures: ["http", "fetch-event"],
196
+ wizerBin,
197
+ });
198
+ return component;
199
+ }
200
+ finally {
201
+ Math.random = random;
202
+ process.chdir(cwd);
203
+ if (tmp === undefined) {
204
+ delete process.env.TMPDIR;
205
+ }
206
+ else {
207
+ process.env.TMPDIR = tmp;
208
+ }
209
+ rmSync(stage, { recursive: true, force: true });
210
+ unlock();
211
+ }
212
+ }
213
+ function log(quiet, line) {
214
+ if (!quiet) {
215
+ console.log(line);
216
+ }
217
+ }
218
+ export async function buildApp(options) {
219
+ const dir = resolve(options.dir);
220
+ const pkgPath = join(dir, "package.json");
221
+ if (!existsSync(pkgPath)) {
222
+ throw new BuildError(`no package.json in ${dir}; run this in your App's directory`);
223
+ }
224
+ const pkg = readJson(pkgPath);
225
+ const configured = pkg.pollis?.entry;
226
+ const entry = options.entry ?? configured ?? "src/app.ts";
227
+ if (!existsSync(join(dir, entry))) {
228
+ throw new BuildError(`no App entry at ${entry} (set "pollis": { "entry": "..." } in package.json)`);
229
+ }
230
+ const out = resolve(dir, options.out ?? "dist");
231
+ const bin = findDevTool();
232
+ mkdirSync(out, { recursive: true });
233
+ const scratch = join(out, ".build");
234
+ rmSync(scratch, { recursive: true, force: true });
235
+ mkdirSync(scratch, { recursive: true });
236
+ try {
237
+ // 1. The manifest, from the code.
238
+ const definition = await loadDefinition(dir, entry, scratch);
239
+ const handlers = Object.keys(definition).filter((k) => Object.values(HANDLER_FOR).includes(k) && typeof definition[k] === "function");
240
+ let manifest;
241
+ try {
242
+ manifest = resolveManifest(definition.manifest, handlers, {
243
+ name: pkg.name,
244
+ version: pkg.version,
245
+ description: pkg.description,
246
+ });
247
+ }
248
+ catch (e) {
249
+ if (e instanceof ManifestError) {
250
+ throw new BuildError(`manifest: ${e.message}`);
251
+ }
252
+ throw e;
253
+ }
254
+ const manifestPath = join(out, "pollis-app.json");
255
+ writeFileSync(manifestPath, JSON.stringify(manifest, null, 2) + "\n");
256
+ // 2. The sandbox bundle.
257
+ let bundle;
258
+ try {
259
+ const result = await esbuild({
260
+ absWorkingDir: dir,
261
+ stdin: { contents: entrySource(entry), resolveDir: dir, sourcefile: "pollis-app-entry.js", loader: "js" },
262
+ bundle: true,
263
+ write: false,
264
+ platform: "neutral",
265
+ mainFields: MAIN_FIELDS,
266
+ conditions: CONDITIONS,
267
+ format: "esm",
268
+ target: "es2022",
269
+ charset: "utf8",
270
+ legalComments: "none",
271
+ // Drops esbuild's "// path/to/file.ts" comments, whose paths depend on
272
+ // where the dependencies are installed; names stay readable.
273
+ minifyWhitespace: true,
274
+ external: ["pollis:app/*"],
275
+ logLevel: "silent",
276
+ plugins: [noNodeBuiltins()],
277
+ });
278
+ bundle = result.outputFiles[0].text;
279
+ }
280
+ catch (e) {
281
+ throw new BuildError(formatEsbuildError(e));
282
+ }
283
+ writeFileSync(join(scratch, "app.js"), bundle);
284
+ // 3. The component.
285
+ const require = createRequire(join(dir, "package.json"));
286
+ let witPath;
287
+ try {
288
+ witPath = require.resolve("@pollis-inc/app/wit/app.wit");
289
+ }
290
+ catch {
291
+ throw new BuildError("@pollis-inc/app is not installed in this project; add it with `pnpm add @pollis-inc/app`");
292
+ }
293
+ log(options.quiet, `compiling ${relative(process.cwd(), join(dir, entry)) || entry} to a component...`);
294
+ let component;
295
+ try {
296
+ component = await componentize(bundle, readFileSync(witPath, "utf8"), bin);
297
+ }
298
+ catch (e) {
299
+ throw new BuildError(`compiling to a component failed:\n${e.message}`);
300
+ }
301
+ const componentPath = join(out, "app.wasm");
302
+ writeFileSync(componentPath, component);
303
+ // A development signature from an earlier `pollis app dev` signs another App hash. Left beside
304
+ // this build it makes a development installation refuse the build as tampered instead of
305
+ // offering it to an admin; `pollis app dev` signs each new build itself.
306
+ rmSync(`${componentPath}.sig.json`, { force: true });
307
+ // 4. The real host's verdict, and the App hash.
308
+ try {
309
+ devTool(bin, ["check", componentPath, manifestPath]);
310
+ }
311
+ catch (e) {
312
+ rmSync(componentPath, { force: true });
313
+ throw new BuildError(`the App host refuses this build: ${e.message}`);
314
+ }
315
+ const appHash = devTool(bin, ["hash", componentPath, manifestPath]);
316
+ return { component: componentPath, manifestPath, manifest, appHash, bytes: component.length };
317
+ }
318
+ finally {
319
+ rmSync(scratch, { recursive: true, force: true });
320
+ }
321
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Finding and running `pollis-app-dev`, the native half of `pollis app`: the
3
+ * offline test runner (the real App host), the deterministic build step and
4
+ * the App hash. Built from the Pollis repo (`cargo build --release -p
5
+ * pollis-app-dev`).
6
+ */
7
+ export declare class DevToolMissing extends Error {
8
+ }
9
+ /** `$POLLIS_APP_DEV_BIN`, else `pollis-app-dev` on PATH, else a build in the Pollis repo this CLI lives in. */
10
+ export declare function findDevTool(): string;
11
+ /** Run a `pollis-app-dev` subcommand; returns stdout, throws with stderr on failure. */
12
+ export declare function devTool(bin: string, args: string[]): string;
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Finding and running `pollis-app-dev`, the native half of `pollis app`: the
3
+ * offline test runner (the real App host), the deterministic build step and
4
+ * the App hash. Built from the Pollis repo (`cargo build --release -p
5
+ * pollis-app-dev`).
6
+ */
7
+ import { spawnSync } from "node:child_process";
8
+ import { accessSync, constants, existsSync } from "node:fs";
9
+ import { delimiter, dirname, join } from "node:path";
10
+ import { fileURLToPath } from "node:url";
11
+ const EXE = process.platform === "win32" ? "pollis-app-dev.exe" : "pollis-app-dev";
12
+ export class DevToolMissing extends Error {
13
+ }
14
+ function executable(path) {
15
+ try {
16
+ accessSync(path, constants.X_OK);
17
+ return true;
18
+ }
19
+ catch {
20
+ return false;
21
+ }
22
+ }
23
+ /** `$POLLIS_APP_DEV_BIN`, else `pollis-app-dev` on PATH, else a build in the Pollis repo this CLI lives in. */
24
+ export function findDevTool() {
25
+ const fromEnv = process.env.POLLIS_APP_DEV_BIN;
26
+ if (fromEnv) {
27
+ if (!executable(fromEnv)) {
28
+ throw new DevToolMissing(`POLLIS_APP_DEV_BIN is ${fromEnv}, which is not an executable file`);
29
+ }
30
+ return fromEnv;
31
+ }
32
+ for (const dir of (process.env.PATH ?? "").split(delimiter)) {
33
+ if (dir && executable(join(dir, EXE))) {
34
+ return join(dir, EXE);
35
+ }
36
+ }
37
+ // Inside the Pollis repo (sdk/ts/cli/dist/devtool.js): its cargo target dir.
38
+ let dir = dirname(fileURLToPath(import.meta.url));
39
+ for (let i = 0; i < 6; i++) {
40
+ for (const profile of ["release", "debug"]) {
41
+ const candidate = join(dir, "target", profile, EXE);
42
+ if (existsSync(join(dir, "Cargo.toml")) && executable(candidate)) {
43
+ return candidate;
44
+ }
45
+ }
46
+ dir = dirname(dir);
47
+ }
48
+ throw new DevToolMissing("`pollis-app-dev` was not found. It runs your App in the real sandbox for `build` and `test`.\n" +
49
+ "Build it from the Pollis repo with `cargo build --release -p pollis-app-dev`, then put\n" +
50
+ "target/release on your PATH or set POLLIS_APP_DEV_BIN to the binary.");
51
+ }
52
+ /** Run a `pollis-app-dev` subcommand; returns stdout, throws with stderr on failure. */
53
+ export function devTool(bin, args) {
54
+ const result = spawnSync(bin, args, { encoding: "utf8" });
55
+ if (result.error) {
56
+ throw result.error;
57
+ }
58
+ if (result.status !== 0) {
59
+ throw new Error((result.stderr || result.stdout || `pollis-app-dev ${args[0]} failed`).trim());
60
+ }
61
+ return result.stdout.trim();
62
+ }
package/dist/main.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `pollis`: the Pollis command line for App developers.
4
+ *
5
+ * pollis app new <name> --lang ts a new App: one handler, a test, a README
6
+ * pollis app build compile to dist/app.wasm + dist/pollis-app.json, print the App hash
7
+ * pollis app test build, then run the tests offline in the real sandbox
8
+ * pollis app dev --installation ID development installation: rebuild and sign on save, in pollis-bot
9
+ * pollis app run --installation ID install the build in pollis-bot (prints the App hash) and run it
10
+ */
11
+ export {};
package/dist/main.js ADDED
@@ -0,0 +1,102 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * `pollis`: the Pollis command line for App developers.
4
+ *
5
+ * pollis app new <name> --lang ts a new App: one handler, a test, a README
6
+ * pollis app build compile to dist/app.wasm + dist/pollis-app.json, print the App hash
7
+ * pollis app test build, then run the tests offline in the real sandbox
8
+ * pollis app dev --installation ID development installation: rebuild and sign on save, in pollis-bot
9
+ * pollis app run --installation ID install the build in pollis-bot (prints the App hash) and run it
10
+ */
11
+ import { parseArgs } from "node:util";
12
+ import { BuildError, buildApp } from "./build.js";
13
+ import { DevToolMissing } from "./devtool.js";
14
+ import { NewError, newApp } from "./new.js";
15
+ import { devApp, runApp } from "./runtime.js";
16
+ import { testApp } from "./test.js";
17
+ const HELP = `pollis app <command>
18
+
19
+ new <name> --lang ts Create an App: one handler, a test and a README.
20
+ build Compile the App to dist/app.wasm and write dist/pollis-app.json.
21
+ Prints the App hash an admin approves.
22
+ test [files...] Build, then run the App's tests offline in the real sandbox.
23
+ dev --installation ID Run the App in this machine's bot as a development installation:
24
+ prints your developer key (an admin approves it once), then
25
+ rebuilds and signs on every save. Needs pollis-bot.
26
+ run --installation ID Hand the App to this machine's bot and run it. Prints the App hash
27
+ an admin approves on the bot's page. Needs pollis-bot.
28
+
29
+ Options:
30
+ --dir <path> The App's directory (default: the current directory).
31
+ --no-build test: use the existing dist/ instead of building first.
32
+ --sdk <path> new: use the SDK from a Pollis checkout (its sdk/ts directory).
33
+ --artifact <dir|url> run: a built App (a directory or an https:// URL) instead of building this one.
34
+ --data-dir <path> dev, run: pollis-bot's data directory, if not its default.
35
+
36
+ Guide: https://github.com/pollis-app/pollis/blob/main/docs/bots/developer-guide.md`;
37
+ async function main(argv) {
38
+ const { values, positionals } = parseArgs({
39
+ args: argv,
40
+ allowPositionals: true,
41
+ options: {
42
+ dir: { type: "string" },
43
+ lang: { type: "string" },
44
+ sdk: { type: "string" },
45
+ "no-build": { type: "boolean" },
46
+ installation: { type: "string" },
47
+ artifact: { type: "string" },
48
+ "data-dir": { type: "string" },
49
+ help: { type: "boolean", short: "h" },
50
+ },
51
+ });
52
+ const [group, command, ...rest] = positionals;
53
+ if (values.help || group !== "app" || !command) {
54
+ console.log(HELP);
55
+ return values.help ? 0 : 2;
56
+ }
57
+ const dir = values.dir ?? ".";
58
+ switch (command) {
59
+ case "new": {
60
+ const name = rest[0];
61
+ if (!name) {
62
+ console.error("usage: pollis app new <name> --lang ts");
63
+ return 2;
64
+ }
65
+ if (!values.lang) {
66
+ console.error("say which language with --lang (TypeScript: --lang ts)");
67
+ return 2;
68
+ }
69
+ const target = newApp({ name, lang: values.lang, parent: values.dir, sdk: values.sdk });
70
+ console.log(`Created ${target}\n\nNext:\n cd ${name}\n pnpm install\n pnpm test`);
71
+ return 0;
72
+ }
73
+ case "build": {
74
+ const built = await buildApp({ dir });
75
+ console.log(`built ${built.manifest.name} ${built.manifest.version}\n` +
76
+ ` dist/app.wasm ${(built.bytes / 1024 / 1024).toFixed(1)} MB\n` +
77
+ ` dist/pollis-app.json\n` +
78
+ `App hash: ${built.appHash}`);
79
+ return 0;
80
+ }
81
+ case "test":
82
+ return testApp({ dir, build: !values["no-build"], patterns: rest });
83
+ case "dev":
84
+ return devApp({ dir, installation: values.installation, dataDir: values["data-dir"] });
85
+ case "run":
86
+ return runApp({ dir, installation: values.installation, dataDir: values["data-dir"], artifact: values.artifact });
87
+ default:
88
+ console.error(`unknown command \`pollis app ${command}\`\n\n${HELP}`);
89
+ return 2;
90
+ }
91
+ }
92
+ main(process.argv.slice(2)).then((code) => {
93
+ process.exitCode = code;
94
+ }, (e) => {
95
+ if (e instanceof BuildError || e instanceof NewError || e instanceof DevToolMissing) {
96
+ console.error(`error: ${e.message}`);
97
+ }
98
+ else {
99
+ console.error(e);
100
+ }
101
+ process.exitCode = 1;
102
+ });
package/dist/new.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * `pollis app new <name> --lang ts`: a new App from the template: one
3
+ * handler, a test and a README.
4
+ */
5
+ export declare class NewError extends Error {
6
+ }
7
+ export interface NewOptions {
8
+ name: string;
9
+ lang: string;
10
+ /** Parent directory. Default: the current directory. */
11
+ parent?: string;
12
+ /**
13
+ * Use local copies of the SDK packages (a path to the Pollis repo's
14
+ * `sdk/ts`), for working before or beside the npm releases.
15
+ */
16
+ sdk?: string;
17
+ }
18
+ export declare function newApp(options: NewOptions): string;
package/dist/new.js ADDED
@@ -0,0 +1,48 @@
1
+ /**
2
+ * `pollis app new <name> --lang ts`: 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
+ export function newApp(options) {
20
+ if (options.lang !== "ts") {
21
+ throw new NewError(`--lang ${options.lang} is not available; TypeScript (--lang ts) is. Rust Apps arrive with the Rust SDK.`);
22
+ }
23
+ if (!NAME.test(options.name)) {
24
+ throw new NewError(`"${options.name}" is not a valid App name: lowercase letters, digits and '-', starting with a letter or digit`);
25
+ }
26
+ const target = resolve(options.parent ?? ".", options.name);
27
+ if (existsSync(target) && readdirSync(target).length > 0) {
28
+ throw new NewError(`${target} already exists and is not empty`);
29
+ }
30
+ cpSync(join(templates(), "ts"), target, { recursive: true });
31
+ renameSync(join(target, "gitignore"), join(target, ".gitignore"));
32
+ let app = sdkVersion();
33
+ let cli = sdkVersion();
34
+ if (options.sdk) {
35
+ const sdk = resolve(options.sdk);
36
+ if (!existsSync(join(sdk, "app", "package.json")) || !existsSync(join(sdk, "cli", "package.json"))) {
37
+ throw new NewError(`--sdk ${options.sdk}: expected the Pollis repo's sdk/ts directory (with app/ and cli/)`);
38
+ }
39
+ app = `link:${relative(target, join(sdk, "app"))}`;
40
+ cli = `link:${relative(target, join(sdk, "cli"))}`;
41
+ }
42
+ const fill = (text) => text.replaceAll("{{name}}", options.name).replaceAll("{{app}}", app).replaceAll("{{cli}}", cli);
43
+ const tmpl = join(target, "package.json.tmpl");
44
+ writeFileSync(join(target, "package.json"), fill(readFileSync(tmpl, "utf8")));
45
+ unlinkSync(tmpl);
46
+ writeFileSync(join(target, "README.md"), fill(readFileSync(join(target, "README.md"), "utf8")));
47
+ return target;
48
+ }
@@ -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>;
@@ -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"].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/test.d.ts ADDED
@@ -0,0 +1,11 @@
1
+ /**
2
+ * `pollis app test`: build the App, then run its `*.test.ts` files with Node's
3
+ * test runner, wired to the build through `@pollis-inc/app/testing`.
4
+ */
5
+ export interface TestOptions {
6
+ dir: string;
7
+ build: boolean;
8
+ /** Test file globs, relative to `dir`. */
9
+ patterns: string[];
10
+ }
11
+ export declare function testApp(options: TestOptions): Promise<number>;
package/dist/test.js ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * `pollis app test`: build the App, then run its `*.test.ts` files with Node's
3
+ * test runner, wired to the build through `@pollis-inc/app/testing`.
4
+ */
5
+ import { spawnSync } from "node:child_process";
6
+ import { globSync } from "node:fs";
7
+ import { join, resolve } from "node:path";
8
+ import { buildApp } from "./build.js";
9
+ import { findDevTool } from "./devtool.js";
10
+ export async function testApp(options) {
11
+ const dir = resolve(options.dir);
12
+ const bin = findDevTool();
13
+ const component = join(dir, "dist", "app.wasm");
14
+ const manifest = join(dir, "dist", "pollis-app.json");
15
+ if (options.build) {
16
+ const built = await buildApp({ dir, quiet: true });
17
+ console.log(`built ${built.manifest.name} ${built.manifest.version} (App hash ${built.appHash})`);
18
+ }
19
+ const patterns = options.patterns.length > 0 ? options.patterns : ["src/**/*.test.ts", "test/**/*.test.ts"];
20
+ const files = patterns.flatMap((p) => globSync(p, { cwd: dir })).sort();
21
+ if (files.length === 0) {
22
+ console.error(`no test files matching ${patterns.join(", ")}`);
23
+ return 1;
24
+ }
25
+ const result = spawnSync(process.execPath, ["--test", "--test-concurrency=1", ...files], {
26
+ cwd: dir,
27
+ stdio: "inherit",
28
+ env: {
29
+ ...process.env,
30
+ // Report to this terminal even when `pollis app test` itself runs under
31
+ // a test runner.
32
+ NODE_TEST_CONTEXT: undefined,
33
+ POLLIS_APP_COMPONENT: component,
34
+ POLLIS_APP_MANIFEST: manifest,
35
+ POLLIS_APP_DEV_BIN: bin,
36
+ },
37
+ });
38
+ return result.status ?? 1;
39
+ }
package/package.json CHANGED
@@ -1,6 +1,30 @@
1
1
  {
2
2
  "name": "@pollis-inc/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "0.1.0",
4
+ "description": "The `pollis app` command: create, build and test Pollis Apps.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "bin": {
8
+ "pollis": "./dist/main.js"
9
+ },
10
+ "files": [
11
+ "dist",
12
+ "templates"
13
+ ],
14
+ "engines": {
15
+ "node": ">=22.18"
16
+ },
17
+ "dependencies": {
18
+ "@bytecodealliance/componentize-js": "0.23.0",
19
+ "esbuild": "0.28.2",
20
+ "@pollis-inc/app": "0.1.0"
21
+ },
22
+ "devDependencies": {
23
+ "@types/node": "^22.19.0",
24
+ "typescript": "5.9.3"
25
+ },
26
+ "scripts": {
27
+ "build": "tsc -p tsconfig.json",
28
+ "test": "pnpm -s build && node --test --test-concurrency=1 test/*.test.ts"
29
+ }
6
30
  }
@@ -0,0 +1,17 @@
1
+ # {{name}}
2
+
3
+ A [Pollis](https://pollis.com) App. It answers `/hello` with a greeting.
4
+
5
+ ```sh
6
+ pnpm install
7
+ pnpm test # build, then run src/app.test.ts against the built App, offline
8
+ pnpm build # writes dist/app.wasm and dist/pollis-app.json, prints the App hash
9
+ ```
10
+
11
+ - `src/app.ts`: the App. Its `manifest` says what it needs; its handlers say what it does.
12
+ - `src/app.test.ts`: tests. Each one runs the built App in the same sandbox the bot
13
+ runtime uses, so anything the manifest does not allow fails here too.
14
+ - `dist/`: build output. The App hash identifies exactly this build; an admin approves it.
15
+
16
+ The developer guide explains every handler, what `ctx` can do, the manifest and the
17
+ sandbox's limits: https://github.com/pollis-app/pollis/blob/main/docs/bots/developer-guide.md
@@ -0,0 +1,2 @@
1
+ node_modules/
2
+ dist/
@@ -0,0 +1,20 @@
1
+ {
2
+ "name": "{{name}}",
3
+ "version": "0.1.0",
4
+ "description": "A Pollis App.",
5
+ "private": true,
6
+ "type": "module",
7
+ "scripts": {
8
+ "build": "pollis app build",
9
+ "test": "pollis app test",
10
+ "typecheck": "tsc"
11
+ },
12
+ "dependencies": {
13
+ "@pollis-inc/app": "{{app}}"
14
+ },
15
+ "devDependencies": {
16
+ "@pollis-inc/cli": "{{cli}}",
17
+ "@types/node": "^22.19.0",
18
+ "typescript": "5.9.3"
19
+ }
20
+ }
@@ -0,0 +1,22 @@
1
+ import { test } from "node:test";
2
+ import assert from "node:assert/strict";
3
+ import { testApp } from "@pollis-inc/app/testing";
4
+
5
+ // Runs the built App in the same sandbox the bot runtime uses, offline.
6
+ const app = await testApp();
7
+
8
+ test("/hello greets by name", async () => {
9
+ const result = await app.command("hello", "Sam");
10
+ assert.ok(result.ok, result.error?.message);
11
+ assert.deepEqual(result.replies, ["Hello, Sam!"]);
12
+ });
13
+
14
+ test("/hello with no name greets the sender", async () => {
15
+ const result = await app.command("hello", "", { message: { author: { displayName: "Ann" } } });
16
+ assert.deepEqual(result.replies, ["Hello, Ann!"]);
17
+ });
18
+
19
+ test("a command the App did not declare never reaches it", async () => {
20
+ const result = await app.command("weather");
21
+ assert.deepEqual(result.actions, []);
22
+ });
@@ -0,0 +1,23 @@
1
+ import { app } from "@pollis-inc/app";
2
+
3
+ export default app({
4
+ manifest: {
5
+ // Where the App works. "*" means: whichever channels the admin picks
6
+ // when approving it. Use "#name" to ask for one channel by name.
7
+ read: { channels: ["*"] },
8
+ // What the App may do there. The admin sees this list before approving.
9
+ actions: ["reply"],
10
+ // No `egress`: this App cannot send anything outside the group.
11
+ // The slash commands members can pick in the composer.
12
+ commands: [{ name: "hello", description: "Say hello", arg_hint: "[name]" }],
13
+ },
14
+
15
+ // Runs when a member sends one of the commands above, e.g. "/hello Sam".
16
+ async onCommand(cmd, ctx) {
17
+ if (cmd.name !== "hello") {
18
+ return;
19
+ }
20
+ const who = cmd.args.trim() || cmd.message.author.displayName;
21
+ await ctx.reply(cmd.message, `Hello, ${who}!`);
22
+ },
23
+ });
@@ -0,0 +1,12 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2022",
4
+ "module": "NodeNext",
5
+ "moduleResolution": "NodeNext",
6
+ "strict": true,
7
+ "noEmit": true,
8
+ "skipLibCheck": true,
9
+ "types": ["node"]
10
+ },
11
+ "include": ["src"]
12
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.