phibac 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.
- package/LICENSE +202 -0
- package/README.md +51 -2
- package/dist/api.d.ts +96 -0
- package/dist/api.js +174 -0
- package/dist/api.js.map +1 -0
- package/dist/brand.d.ts +19 -0
- package/dist/brand.js +20 -0
- package/dist/brand.js.map +1 -0
- package/dist/cli.d.ts +4 -0
- package/dist/cli.js +66 -0
- package/dist/cli.js.map +1 -0
- package/dist/commands/deploy.d.ts +3 -0
- package/dist/commands/deploy.js +83 -0
- package/dist/commands/deploy.js.map +1 -0
- package/dist/commands/dev.d.ts +3 -0
- package/dist/commands/dev.js +132 -0
- package/dist/commands/dev.js.map +1 -0
- package/dist/commands/generate.d.ts +4 -0
- package/dist/commands/generate.js +33 -0
- package/dist/commands/generate.js.map +1 -0
- package/dist/commands/init.d.ts +3 -0
- package/dist/commands/init.js +62 -0
- package/dist/commands/init.js.map +1 -0
- package/dist/commands/mcp.d.ts +3 -0
- package/dist/commands/mcp.js +151 -0
- package/dist/commands/mcp.js.map +1 -0
- package/dist/commands/native.d.ts +3 -0
- package/dist/commands/native.js +114 -0
- package/dist/commands/native.js.map +1 -0
- package/dist/compile.d.ts +37 -0
- package/dist/compile.js +187 -0
- package/dist/compile.js.map +1 -0
- package/dist/config.d.ts +58 -0
- package/dist/config.js +24 -0
- package/dist/config.js.map +1 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +24 -0
- package/dist/index.js.map +1 -0
- package/package.json +45 -4
- package/src/api.ts +216 -0
- package/src/brand.ts +23 -0
- package/src/cli.ts +66 -0
- package/src/commands/deploy.ts +88 -0
- package/src/commands/dev.ts +127 -0
- package/src/commands/generate.ts +35 -0
- package/src/commands/init.ts +67 -0
- package/src/commands/mcp.ts +145 -0
- package/src/commands/native.ts +125 -0
- package/src/compile.ts +217 -0
- package/src/config.ts +73 -0
- package/src/index.ts +26 -0
package/src/api.ts
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
import type { spawn } from "node:child_process";
|
|
2
|
+
import { parseArgs } from "node:util";
|
|
3
|
+
import { BRAND, CLI_NAME, DEFAULT_BASE_URL } from "./brand.js";
|
|
4
|
+
|
|
5
|
+
export type Env = Record<string, string | undefined>;
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Context is everything a command needs from its surroundings, so tests can
|
|
9
|
+
* call a command directly: its arguments (after the command name), the
|
|
10
|
+
* environment, the working directory, output (one line at a time), and the
|
|
11
|
+
* outside world (fetch, spawn, stdin, platform).
|
|
12
|
+
*/
|
|
13
|
+
export interface Context {
|
|
14
|
+
args: string[];
|
|
15
|
+
env: Env;
|
|
16
|
+
cwd: string;
|
|
17
|
+
/** Writes one line to stdout. */
|
|
18
|
+
out: (line: string) => void;
|
|
19
|
+
/** Writes one line to stderr. */
|
|
20
|
+
err: (line: string) => void;
|
|
21
|
+
fetch: typeof fetch;
|
|
22
|
+
stdin: AsyncIterable<string | Uint8Array>;
|
|
23
|
+
spawn: typeof spawn;
|
|
24
|
+
/** The CLI's version. */
|
|
25
|
+
version: string;
|
|
26
|
+
platform: NodeJS.Platform;
|
|
27
|
+
arch: string;
|
|
28
|
+
homedir: string;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** CliError is a failure to report to the user (exit code 1). */
|
|
32
|
+
export class CliError extends Error {
|
|
33
|
+
override name = "CliError";
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** UsageError is a mistake in how the command was invoked (exit code 2). */
|
|
37
|
+
export class UsageError extends Error {
|
|
38
|
+
override name = "UsageError";
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** NetworkError is a failure to reach the server at all. */
|
|
42
|
+
export class NetworkError extends CliError {
|
|
43
|
+
override name = "NetworkError";
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** ApiError is an error body the server returned. */
|
|
47
|
+
export class ApiError extends CliError {
|
|
48
|
+
override name = "ApiError";
|
|
49
|
+
constructor(
|
|
50
|
+
readonly status: number,
|
|
51
|
+
readonly code: string,
|
|
52
|
+
message: string,
|
|
53
|
+
readonly hint: string,
|
|
54
|
+
readonly reasons: string[],
|
|
55
|
+
) {
|
|
56
|
+
super(message);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** The base URL of the server, without a trailing slash. */
|
|
61
|
+
export function baseUrl(env: Env): string {
|
|
62
|
+
const v = env.PB_BASE_URL?.trim();
|
|
63
|
+
return (v || DEFAULT_BASE_URL).replace(/\/+$/, "");
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** The developer token, or an error saying where to create one. */
|
|
67
|
+
export function requireToken(env: Env): string {
|
|
68
|
+
const t = env.PB_TOKEN?.trim();
|
|
69
|
+
if (t) return t;
|
|
70
|
+
throw new CliError(
|
|
71
|
+
`PB_TOKEN is not set. Create a developer token in the developer section of your account page at ${baseUrl(env)}/account/developer, then run: export PB_TOKEN=pbd_...`,
|
|
72
|
+
);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** Replaces every occurrence of secret in text. */
|
|
76
|
+
export function redact(text: string, secret: string | undefined): string {
|
|
77
|
+
return secret ? text.split(secret).join("[redacted]") : text;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface RequestOptions {
|
|
81
|
+
body?: unknown;
|
|
82
|
+
query?: Record<string, string>;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Client talks to the server's HTTP API. With a token it sends it as a bearer
|
|
87
|
+
* token; the token is never put in a URL and is removed from any text the
|
|
88
|
+
* client produces.
|
|
89
|
+
*/
|
|
90
|
+
export class Client {
|
|
91
|
+
readonly baseUrl: string;
|
|
92
|
+
private readonly token: string | undefined;
|
|
93
|
+
private readonly doFetch: typeof fetch;
|
|
94
|
+
|
|
95
|
+
/** auth: true needs PB_TOKEN; false sends no credentials. */
|
|
96
|
+
constructor(ctx: Pick<Context, "env" | "fetch">, auth: boolean) {
|
|
97
|
+
this.baseUrl = baseUrl(ctx.env);
|
|
98
|
+
this.token = auth ? requireToken(ctx.env) : undefined;
|
|
99
|
+
this.doFetch = ctx.fetch;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
private url(path: string, query?: Record<string, string>): string {
|
|
103
|
+
const q = query ? "?" + new URLSearchParams(query).toString() : "";
|
|
104
|
+
return this.baseUrl + path + q;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** send performs the request and returns the response if it is 2xx. */
|
|
108
|
+
async send(method: string, path: string, opts: RequestOptions & { headers?: Record<string, string> } = {}): Promise<Response> {
|
|
109
|
+
const url = this.url(path, opts.query);
|
|
110
|
+
const headers: Record<string, string> = { ...opts.headers };
|
|
111
|
+
if (this.token) headers.Authorization = `Bearer ${this.token}`;
|
|
112
|
+
const init: RequestInit = { method, headers };
|
|
113
|
+
if (opts.body !== undefined) {
|
|
114
|
+
headers["Content-Type"] = "application/json";
|
|
115
|
+
init.body = typeof opts.body === "string" ? opts.body : JSON.stringify(opts.body);
|
|
116
|
+
}
|
|
117
|
+
let res: Response;
|
|
118
|
+
try {
|
|
119
|
+
res = await this.doFetch(url, init);
|
|
120
|
+
} catch (e) {
|
|
121
|
+
throw this.networkError(e);
|
|
122
|
+
}
|
|
123
|
+
if (!res.ok) throw await this.responseError(res, url);
|
|
124
|
+
return res;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** request performs the request and returns the parsed JSON body. */
|
|
128
|
+
async request<T>(method: string, path: string, opts: RequestOptions = {}): Promise<T> {
|
|
129
|
+
const res = await this.send(method, path, { ...opts, headers: { Accept: "application/json" } });
|
|
130
|
+
try {
|
|
131
|
+
return (await res.json()) as T;
|
|
132
|
+
} catch {
|
|
133
|
+
throw new CliError(`the server at ${this.baseUrl} sent a response that is not JSON (${method} ${path}); check that PB_BASE_URL points at a ${BRAND} server`);
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
networkError(e: unknown): NetworkError {
|
|
138
|
+
const cause = e instanceof Error ? (e.cause as { code?: unknown } | undefined) : undefined;
|
|
139
|
+
const code = typeof cause?.code === "string" ? ` (${cause.code})` : "";
|
|
140
|
+
return new NetworkError(
|
|
141
|
+
`could not reach the server at ${this.baseUrl}${code}. Check that PB_BASE_URL is right and the server is running (${CLI_NAME} dev starts a local one).`,
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
/** responseError turns a non-2xx response into an ApiError, or a CliError if the body is not an error body. */
|
|
146
|
+
async responseError(res: Response, url: string): Promise<CliError> {
|
|
147
|
+
return this.errorFromText(res.status, await res.text().catch(() => ""), url);
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** errorFromText is responseError for a body that has already been read. */
|
|
151
|
+
errorFromText(status: number, rawText: string, url: string): CliError {
|
|
152
|
+
const text = redact(rawText, this.token);
|
|
153
|
+
let body: { error?: { code?: unknown; message?: unknown; hint?: unknown; reasons?: unknown } } | undefined;
|
|
154
|
+
try {
|
|
155
|
+
body = JSON.parse(text);
|
|
156
|
+
} catch {
|
|
157
|
+
body = undefined;
|
|
158
|
+
}
|
|
159
|
+
const e = body?.error;
|
|
160
|
+
if (e && typeof e.code === "string") {
|
|
161
|
+
const reasons = Array.isArray(e.reasons) ? e.reasons.filter((r): r is string => typeof r === "string") : [];
|
|
162
|
+
return new ApiError(status, e.code, String(e.message ?? ""), String(e.hint ?? ""), reasons);
|
|
163
|
+
}
|
|
164
|
+
const snippet = text.trim().slice(0, 200);
|
|
165
|
+
return new CliError(`HTTP ${status} from ${redact(url, this.token)}, which is not a ${BRAND} error response${snippet ? `: ${snippet}` : ""}`);
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
/** formatApiError renders an error as its code, message, hint and reasons. */
|
|
170
|
+
export function formatApiError(e: ApiError): string[] {
|
|
171
|
+
const lines = [`error: ${e.code}: ${e.message}`];
|
|
172
|
+
if (e.hint) lines.push(`hint: ${e.hint}`);
|
|
173
|
+
if (e.reasons.length > 0) {
|
|
174
|
+
lines.push("reasons:");
|
|
175
|
+
for (const r of e.reasons) lines.push(` - ${r}`);
|
|
176
|
+
}
|
|
177
|
+
return lines;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/** parseFlags parses a command's flags; any problem is a UsageError. */
|
|
181
|
+
export function parseFlags<O extends Record<string, { type: "string" | "boolean"; short?: string }>>(
|
|
182
|
+
args: string[],
|
|
183
|
+
options: O,
|
|
184
|
+
): { values: { [K in keyof O]?: O[K]["type"] extends "string" ? string : boolean } } {
|
|
185
|
+
try {
|
|
186
|
+
const { values } = parseArgs({ args, options, strict: true, allowPositionals: false });
|
|
187
|
+
return { values: values as never };
|
|
188
|
+
} catch (e) {
|
|
189
|
+
throw new UsageError(e instanceof Error ? e.message : String(e));
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* guard runs a command body and turns the errors commands throw into
|
|
195
|
+
* messages on stderr and an exit code: 2 for a usage error, 1 for a failure.
|
|
196
|
+
*/
|
|
197
|
+
export async function guard(ctx: Pick<Context, "err">, usage: string, body: () => Promise<number>): Promise<number> {
|
|
198
|
+
try {
|
|
199
|
+
return await body();
|
|
200
|
+
} catch (e) {
|
|
201
|
+
if (e instanceof UsageError) {
|
|
202
|
+
ctx.err(`error: ${e.message}`);
|
|
203
|
+
for (const l of usage.split("\n")) ctx.err(l);
|
|
204
|
+
return 2;
|
|
205
|
+
}
|
|
206
|
+
if (e instanceof ApiError) {
|
|
207
|
+
for (const l of formatApiError(e)) ctx.err(l);
|
|
208
|
+
return 1;
|
|
209
|
+
}
|
|
210
|
+
if (e instanceof CliError) {
|
|
211
|
+
ctx.err(`error: ${e.message}`);
|
|
212
|
+
return 1;
|
|
213
|
+
}
|
|
214
|
+
throw e;
|
|
215
|
+
}
|
|
216
|
+
}
|
package/src/brand.ts
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* BRAND is the product name shown in user-facing CLI text (messages and the
|
|
3
|
+
* generated pb.config.ts). It is also the internal code name behind the
|
|
4
|
+
* config file, the server binary and the cache folder. Change it here; never
|
|
5
|
+
* write the name anywhere else.
|
|
6
|
+
*/
|
|
7
|
+
export const BRAND = "pb";
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* CLI_NAME is the CLI's npm package name, its command name (package.json
|
|
11
|
+
* "bin") and the module pb.config.ts imports the helpers from. A test checks
|
|
12
|
+
* it against package.json.
|
|
13
|
+
*/
|
|
14
|
+
export const CLI_NAME = "phibac";
|
|
15
|
+
|
|
16
|
+
/** DEFAULT_BASE_URL is the local development server. */
|
|
17
|
+
export const DEFAULT_BASE_URL = "http://localhost:8787";
|
|
18
|
+
|
|
19
|
+
/** SERVER_BIN is the base name of the server binary release assets. */
|
|
20
|
+
export const SERVER_BIN = `${BRAND}-server`;
|
|
21
|
+
|
|
22
|
+
/** CONFIG_FILE is the name of the app config file in a project. */
|
|
23
|
+
export const CONFIG_FILE = `${BRAND}.config.ts`;
|
package/src/cli.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { guard, type Context } from "./api.js";
|
|
2
|
+
import { CLI_NAME, CONFIG_FILE } from "./brand.js";
|
|
3
|
+
import * as deploy from "./commands/deploy.js";
|
|
4
|
+
import * as dev from "./commands/dev.js";
|
|
5
|
+
import * as generate from "./commands/generate.js";
|
|
6
|
+
import * as init from "./commands/init.js";
|
|
7
|
+
import * as mcp from "./commands/mcp.js";
|
|
8
|
+
import * as native from "./commands/native.js";
|
|
9
|
+
|
|
10
|
+
const COMMANDS: Record<string, { run: (ctx: Context) => Promise<number>; USAGE: string }> = {
|
|
11
|
+
init: { run: init.init, USAGE: init.USAGE },
|
|
12
|
+
deploy: { run: deploy.deploy, USAGE: deploy.USAGE },
|
|
13
|
+
generate: { run: generate.generate, USAGE: generate.USAGE },
|
|
14
|
+
dev: { run: dev.dev, USAGE: dev.USAGE },
|
|
15
|
+
mcp: { run: mcp.mcp, USAGE: mcp.USAGE },
|
|
16
|
+
native: { run: native.native, USAGE: native.USAGE },
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
export const USAGE = `Usage: ${CLI_NAME} <command> [options]
|
|
20
|
+
|
|
21
|
+
Commands:
|
|
22
|
+
${CLI_NAME} init --name <name> [--origin <url>] create an app and write ${CONFIG_FILE}
|
|
23
|
+
${CLI_NAME} deploy preview, then publish the collections in ${CONFIG_FILE}
|
|
24
|
+
${CLI_NAME} generate [--out <file>] write TypeScript types for those collections
|
|
25
|
+
${CLI_NAME} dev run a local server (billing off, data in ./.pb)
|
|
26
|
+
${CLI_NAME} mcp bridge an agent's stdio MCP to the server's /mcp endpoint
|
|
27
|
+
${CLI_NAME} native set|show register the iOS and Android apps that are this app
|
|
28
|
+
|
|
29
|
+
Run "${CLI_NAME} <command> --help" for a command's options. ${CLI_NAME} --version prints the version.
|
|
30
|
+
|
|
31
|
+
Environment:
|
|
32
|
+
PB_BASE_URL the server (default http://localhost:8787)
|
|
33
|
+
PB_TOKEN developer token (pbd_...), from the developer section of your account page;
|
|
34
|
+
needed by init, deploy, mcp and native
|
|
35
|
+
PB_SERVER_BIN ${CLI_NAME} dev: path of the server binary to run
|
|
36
|
+
PB_RELEASES_URL ${CLI_NAME} dev: https address to download the server binary from, if PB_SERVER_BIN is not set
|
|
37
|
+
|
|
38
|
+
Exit codes: 0 success, 1 failure, 2 usage error.`;
|
|
39
|
+
|
|
40
|
+
/** run dispatches argv (the arguments after the program name) to a command. */
|
|
41
|
+
export async function run(argv: string[], ctx: Context): Promise<number> {
|
|
42
|
+
const [name, ...rest] = argv;
|
|
43
|
+
if (name === undefined) {
|
|
44
|
+
for (const l of USAGE.split("\n")) ctx.err(l);
|
|
45
|
+
return 2;
|
|
46
|
+
}
|
|
47
|
+
if (name === "--help" || name === "-h" || name === "help") {
|
|
48
|
+
ctx.out(USAGE);
|
|
49
|
+
return 0;
|
|
50
|
+
}
|
|
51
|
+
if (name === "--version" || name === "-v" || name === "-V") {
|
|
52
|
+
ctx.out(ctx.version);
|
|
53
|
+
return 0;
|
|
54
|
+
}
|
|
55
|
+
const command = Object.hasOwn(COMMANDS, name) ? COMMANDS[name] : undefined;
|
|
56
|
+
if (!command) {
|
|
57
|
+
ctx.err(`error: unknown command "${name}"`);
|
|
58
|
+
for (const l of USAGE.split("\n")) ctx.err(l);
|
|
59
|
+
return 2;
|
|
60
|
+
}
|
|
61
|
+
if (rest.includes("--help") || rest.includes("-h")) {
|
|
62
|
+
ctx.out(command.USAGE);
|
|
63
|
+
return 0;
|
|
64
|
+
}
|
|
65
|
+
return guard(ctx, command.USAGE, () => command.run({ ...ctx, args: rest }));
|
|
66
|
+
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { join } from "node:path";
|
|
2
|
+
import { ApiError, CliError, Client, guard, parseFlags, type Context } from "../api.js";
|
|
3
|
+
import { CLI_NAME, CONFIG_FILE } from "../brand.js";
|
|
4
|
+
import { compileConfig, type WireCollection } from "../compile.js";
|
|
5
|
+
|
|
6
|
+
export const USAGE = `Usage: ${CLI_NAME} deploy
|
|
7
|
+
|
|
8
|
+
Compiles ${CONFIG_FILE} and publishes its collections. Every collection is
|
|
9
|
+
previewed first (a dry run). If any change is breaking, or any preview fails,
|
|
10
|
+
nothing is published and the exit code is 1. Collections that are unchanged
|
|
11
|
+
are skipped.
|
|
12
|
+
Needs PB_TOKEN (a developer token); PB_BASE_URL defaults to the local server.`;
|
|
13
|
+
|
|
14
|
+
/** PublishResult is the server's answer to a publish or dry run. */
|
|
15
|
+
interface PublishResult {
|
|
16
|
+
collection: string;
|
|
17
|
+
major: number;
|
|
18
|
+
minor: number;
|
|
19
|
+
kind: "same" | "additive";
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
const path = (app: string, name: string) => `/v1/apps/${encodeURIComponent(app)}/collections/${encodeURIComponent(name)}`;
|
|
23
|
+
const plural = (n: number, word: string) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
24
|
+
|
|
25
|
+
export function deploy(ctx: Context): Promise<number> {
|
|
26
|
+
return guard(ctx, USAGE, async () => {
|
|
27
|
+
parseFlags(ctx.args, {});
|
|
28
|
+
const config = await compileConfig(join(ctx.cwd, CONFIG_FILE));
|
|
29
|
+
if (config.collections.length === 0) {
|
|
30
|
+
ctx.out(`${CONFIG_FILE} defines no collections, so there is nothing to publish. Add a collection (see the commented example), then run ${CLI_NAME} deploy again.`);
|
|
31
|
+
return 0;
|
|
32
|
+
}
|
|
33
|
+
const client = new Client(ctx, true);
|
|
34
|
+
const width = Math.max(...config.collections.map((c) => c.name.length));
|
|
35
|
+
const line = (name: string, text: string) => ctx.out(`${name.padEnd(width)} ${text}`);
|
|
36
|
+
|
|
37
|
+
ctx.out(`Previewing ${plural(config.collections.length, "collection")} for app ${config.app} on ${client.baseUrl}`);
|
|
38
|
+
const toPublish: WireCollection[] = [];
|
|
39
|
+
const blocked: string[] = [];
|
|
40
|
+
for (const c of config.collections) {
|
|
41
|
+
try {
|
|
42
|
+
const r = await client.request<PublishResult>("PUT", path(config.app, c.name), { body: c, query: { dryRun: "true" } });
|
|
43
|
+
if (r.kind === "same") {
|
|
44
|
+
line(c.name, `same (version ${r.major}.${r.minor}, nothing to publish)`);
|
|
45
|
+
} else {
|
|
46
|
+
line(c.name, `additive (will become version ${r.major}.${r.minor})`);
|
|
47
|
+
toPublish.push(c);
|
|
48
|
+
}
|
|
49
|
+
} catch (e) {
|
|
50
|
+
if (!(e instanceof ApiError)) throw e;
|
|
51
|
+
blocked.push(c.name);
|
|
52
|
+
if (e.code === "schema_incompatible") {
|
|
53
|
+
line(c.name, "breaking");
|
|
54
|
+
for (const reason of e.reasons) ctx.out(` - ${reason}`);
|
|
55
|
+
ctx.out(` Publish it as the next major version: set "version": ${c.version + 1} on this collection in ${CONFIG_FILE}, or remove the changes listed above.`);
|
|
56
|
+
} else {
|
|
57
|
+
line(c.name, `failed (${e.code})`);
|
|
58
|
+
ctx.err(`${c.name}: ${e.code}: ${e.message}`);
|
|
59
|
+
if (e.hint) ctx.err(` hint: ${e.hint}`);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (blocked.length > 0) {
|
|
64
|
+
throw new CliError(`nothing was published: ${blocked.join(", ")} cannot be published (see above). Fix ${plural(blocked.length, "collection")} and run ${CLI_NAME} deploy again.`);
|
|
65
|
+
}
|
|
66
|
+
if (toPublish.length === 0) {
|
|
67
|
+
ctx.out("Nothing to publish: every collection is already up to date.");
|
|
68
|
+
return 0;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const done: string[] = [];
|
|
72
|
+
for (const c of toPublish) {
|
|
73
|
+
try {
|
|
74
|
+
const r = await client.request<PublishResult>("PUT", path(config.app, c.name), { body: c });
|
|
75
|
+
done.push(c.name);
|
|
76
|
+
ctx.out(`published ${c.name} version ${r.major}.${r.minor}`);
|
|
77
|
+
} catch (e) {
|
|
78
|
+
const left = toPublish.slice(done.length).map((x) => x.name);
|
|
79
|
+
ctx.err(`published: ${done.length ? done.join(", ") : "none"}`);
|
|
80
|
+
ctx.err(`not published: ${left.join(", ")}`);
|
|
81
|
+
ctx.err(`Fix the error below, then run ${CLI_NAME} deploy again; collections already published are skipped as unchanged.`);
|
|
82
|
+
throw e;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
ctx.out(`Published ${plural(done.length, "collection")}.`);
|
|
86
|
+
return 0;
|
|
87
|
+
});
|
|
88
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { existsSync } from "node:fs";
|
|
3
|
+
import { chmod, mkdir, rename, rm, writeFile } from "node:fs/promises";
|
|
4
|
+
import { constants as osConstants } from "node:os";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { CliError, guard, parseFlags, type Context } from "../api.js";
|
|
7
|
+
import { BRAND, CLI_NAME, SERVER_BIN } from "../brand.js";
|
|
8
|
+
|
|
9
|
+
export const USAGE = `Usage: ${CLI_NAME} dev
|
|
10
|
+
|
|
11
|
+
Runs a ${BRAND} server for local development (billing off, data in ./.pb, port 8787)
|
|
12
|
+
with PB_MODE=dev PB_DATA_DIR=./.pb PB_PORT=8787 PB_BASE_URL=http://localhost:8787.
|
|
13
|
+
Your other environment variables are passed to the server (a PB_BASE_URL you set
|
|
14
|
+
for ${CLI_NAME} deploy is not: the local server always gets its own address). Press Ctrl-C to stop it; ${CLI_NAME} exits with the server's exit code.
|
|
15
|
+
|
|
16
|
+
Which server binary runs:
|
|
17
|
+
PB_SERVER_BIN=<path> run this binary
|
|
18
|
+
PB_RELEASES_URL=<url> otherwise download ${SERVER_BIN}_<os>_<arch> for this CLI's
|
|
19
|
+
version from <url>/v<version>/ once, check it against the
|
|
20
|
+
SHA-256 in <that file>.sha256, cache it in ~/.cache/${BRAND}/ and run it
|
|
21
|
+
(https only; http://localhost is allowed for tests)
|
|
22
|
+
If neither is set, ${CLI_NAME} dev cannot start a server.`;
|
|
23
|
+
|
|
24
|
+
// The local development server's port and address.
|
|
25
|
+
const DEV_PORT = 8787;
|
|
26
|
+
const DEV_BASE_URL = `http://localhost:${DEV_PORT}`;
|
|
27
|
+
|
|
28
|
+
const OS_NAMES: Partial<Record<NodeJS.Platform, string>> = { darwin: "darwin", linux: "linux", win32: "windows" };
|
|
29
|
+
const ARCH_NAMES: Record<string, string> = { x64: "amd64", arm64: "arm64" };
|
|
30
|
+
|
|
31
|
+
function checkUrl(raw: string): URL {
|
|
32
|
+
let u: URL;
|
|
33
|
+
try {
|
|
34
|
+
u = new URL(raw);
|
|
35
|
+
} catch {
|
|
36
|
+
throw new CliError(`PB_RELEASES_URL ${JSON.stringify(raw)} is not a URL. Use an https:// address.`);
|
|
37
|
+
}
|
|
38
|
+
if (u.protocol !== "https:" && !(u.protocol === "http:" && u.hostname === "localhost")) {
|
|
39
|
+
throw new CliError(`PB_RELEASES_URL must start with https:// (http:// is only allowed for localhost); refusing to download a server binary over ${u.protocol.replace(":", "")}.`);
|
|
40
|
+
}
|
|
41
|
+
return u;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** serverBinary returns the path of the binary to run, downloading it if needed. */
|
|
45
|
+
async function serverBinary(ctx: Context): Promise<string> {
|
|
46
|
+
const given = ctx.env.PB_SERVER_BIN?.trim();
|
|
47
|
+
if (given) return given;
|
|
48
|
+
const releases = ctx.env.PB_RELEASES_URL?.trim();
|
|
49
|
+
if (!releases) {
|
|
50
|
+
throw new CliError(
|
|
51
|
+
`there is no server to run. Set PB_SERVER_BIN to the path of a ${SERVER_BIN} binary (build one with "make build" in the server repository), ` +
|
|
52
|
+
`or set PB_RELEASES_URL to the https address that hosts the ${BRAND} server releases so ${CLI_NAME} dev can download one.`,
|
|
53
|
+
);
|
|
54
|
+
}
|
|
55
|
+
checkUrl(releases);
|
|
56
|
+
const os = OS_NAMES[ctx.platform];
|
|
57
|
+
const arch = ARCH_NAMES[ctx.arch];
|
|
58
|
+
if (!os || !arch) throw new CliError(`there is no ${SERVER_BIN} release for ${ctx.platform}/${ctx.arch}; set PB_SERVER_BIN to a binary you built.`);
|
|
59
|
+
const asset = `${SERVER_BIN}_${os}_${arch}${os === "windows" ? ".exe" : ""}`;
|
|
60
|
+
const dest = join(ctx.homedir, ".cache", BRAND, `v${ctx.version}`, asset);
|
|
61
|
+
if (existsSync(dest)) return dest;
|
|
62
|
+
|
|
63
|
+
const url = `${releases.replace(/\/+$/, "")}/v${ctx.version}/${asset}`;
|
|
64
|
+
const get = async (u: string, what: string): Promise<Response> => {
|
|
65
|
+
let res: Response;
|
|
66
|
+
try {
|
|
67
|
+
res = await ctx.fetch(u);
|
|
68
|
+
} catch (e) {
|
|
69
|
+
throw new CliError(`could not download the ${what} from ${u}: ${e instanceof Error ? e.message : String(e)}`);
|
|
70
|
+
}
|
|
71
|
+
if (!res.ok) throw new CliError(`could not download the ${what} from ${u}: HTTP ${res.status}`);
|
|
72
|
+
return res;
|
|
73
|
+
};
|
|
74
|
+
const bin = Buffer.from(await (await get(url, "server binary")).arrayBuffer());
|
|
75
|
+
const sumRes = await get(`${url}.sha256`, "checksum file").catch((e: CliError) => {
|
|
76
|
+
throw new CliError(`${e.message}. Refusing to run a server binary without its checksum.`);
|
|
77
|
+
});
|
|
78
|
+
const expected = (await sumRes.text()).trim().split(/\s+/)[0]?.toLowerCase() ?? "";
|
|
79
|
+
if (!/^[0-9a-f]{64}$/.test(expected)) throw new CliError(`the checksum file ${url}.sha256 does not hold a SHA-256 checksum; refusing to run the downloaded binary.`);
|
|
80
|
+
const actual = createHash("sha256").update(bin).digest("hex");
|
|
81
|
+
if (actual !== expected) {
|
|
82
|
+
throw new CliError(`checksum mismatch for ${url}: expected ${expected}, got ${actual}. The download is not what was released; refusing to run it.`);
|
|
83
|
+
}
|
|
84
|
+
await mkdir(dirname(dest), { recursive: true });
|
|
85
|
+
const part = `${dest}.part-${process.pid}`;
|
|
86
|
+
try {
|
|
87
|
+
await writeFile(part, bin);
|
|
88
|
+
await chmod(part, 0o755);
|
|
89
|
+
await rename(part, dest);
|
|
90
|
+
} catch (e) {
|
|
91
|
+
await rm(part, { force: true });
|
|
92
|
+
throw new CliError(`could not save the server binary to ${dest}: ${e instanceof Error ? e.message : String(e)}`);
|
|
93
|
+
}
|
|
94
|
+
ctx.out(`Downloaded ${asset} v${ctx.version} to ${dest} (checksum verified).`);
|
|
95
|
+
return dest;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export function dev(ctx: Context): Promise<number> {
|
|
99
|
+
return guard(ctx, USAGE, async () => {
|
|
100
|
+
parseFlags(ctx.args, {});
|
|
101
|
+
const bin = await serverBinary(ctx);
|
|
102
|
+
const env = { ...ctx.env, PB_MODE: "dev", PB_DATA_DIR: "./.pb", PB_PORT: String(DEV_PORT), PB_BASE_URL: DEV_BASE_URL } as Record<string, string>;
|
|
103
|
+
const given = ctx.env.PB_BASE_URL?.trim();
|
|
104
|
+
if (given && given.replace(/\/+$/, "") !== DEV_BASE_URL) {
|
|
105
|
+
ctx.out(`PB_BASE_URL (${given}) is for ${CLI_NAME} deploy; the local server uses ${DEV_BASE_URL}.`);
|
|
106
|
+
}
|
|
107
|
+
ctx.out(`Starting ${bin} (PB_MODE=dev, data in ./.pb, ${DEV_BASE_URL}). Press Ctrl-C to stop.`);
|
|
108
|
+
const child = ctx.spawn(bin, [], { env, cwd: ctx.cwd, stdio: "inherit" });
|
|
109
|
+
// Ctrl-C reaches the server through the terminal; a signal sent to this
|
|
110
|
+
// process alone is passed on.
|
|
111
|
+
const signals = ["SIGINT", "SIGTERM"] as const;
|
|
112
|
+
const forward = (sig: NodeJS.Signals) => () => child.kill?.(sig);
|
|
113
|
+
const handlers = signals.map((s) => [s, forward(s)] as const);
|
|
114
|
+
for (const [s, h] of handlers) process.on(s, h);
|
|
115
|
+
try {
|
|
116
|
+
return await new Promise<number>((resolve, reject) => {
|
|
117
|
+
child.once("error", (e: Error) => reject(new CliError(`could not start ${bin}: ${e.message}`)));
|
|
118
|
+
child.once("exit", (code: number | null, signal: NodeJS.Signals | null) => {
|
|
119
|
+
if (code !== null) resolve(code);
|
|
120
|
+
else resolve(128 + (signal ? (osConstants.signals[signal] ?? 0) : 1));
|
|
121
|
+
});
|
|
122
|
+
});
|
|
123
|
+
} finally {
|
|
124
|
+
for (const [s, h] of handlers) process.off(s, h);
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import { mkdir, writeFile } from "node:fs/promises";
|
|
2
|
+
import { dirname, join, resolve } from "node:path";
|
|
3
|
+
import { CliError, Client, guard, parseFlags, type Context } from "../api.js";
|
|
4
|
+
import { CLI_NAME, CONFIG_FILE } from "../brand.js";
|
|
5
|
+
import { compileConfig } from "../compile.js";
|
|
6
|
+
|
|
7
|
+
export const DEFAULT_OUT = "src/pb-types.ts";
|
|
8
|
+
|
|
9
|
+
export const USAGE = `Usage: ${CLI_NAME} generate [--out <file>]
|
|
10
|
+
|
|
11
|
+
Writes TypeScript types for the collections in ${CONFIG_FILE}, at the major
|
|
12
|
+
versions it names, from the published schemas. Publish first with ${CLI_NAME} deploy.
|
|
13
|
+
--out <file> where to write them (default ${DEFAULT_OUT}); directories are created
|
|
14
|
+
and an existing file is overwritten
|
|
15
|
+
Needs no token; PB_BASE_URL defaults to the local server.`;
|
|
16
|
+
|
|
17
|
+
export function generate(ctx: Context): Promise<number> {
|
|
18
|
+
return guard(ctx, USAGE, async () => {
|
|
19
|
+
const { values } = parseFlags(ctx.args, { out: { type: "string" } });
|
|
20
|
+
const out = values.out ?? DEFAULT_OUT;
|
|
21
|
+
const config = await compileConfig(join(ctx.cwd, CONFIG_FILE));
|
|
22
|
+
if (config.collections.length === 0) {
|
|
23
|
+
throw new CliError(`${CONFIG_FILE} defines no collections, so there are no types to generate. Add a collection and run ${CLI_NAME} deploy first.`);
|
|
24
|
+
}
|
|
25
|
+
const items = config.collections.map((c) => `${c.name}@${c.version}`);
|
|
26
|
+
const client = new Client(ctx, false);
|
|
27
|
+
const res = await client.send("GET", "/v1/types", { query: { collections: items.join(",") } });
|
|
28
|
+
const ts = await res.text();
|
|
29
|
+
const file = resolve(ctx.cwd, out);
|
|
30
|
+
await mkdir(dirname(file), { recursive: true });
|
|
31
|
+
await writeFile(file, ts);
|
|
32
|
+
ctx.out(`Wrote ${out} (${items.length} ${items.length === 1 ? "collection" : "collections"}: ${items.join(", ")}).`);
|
|
33
|
+
return 0;
|
|
34
|
+
});
|
|
35
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { existsSync } from "node:fs";
|
|
2
|
+
import { writeFile } from "node:fs/promises";
|
|
3
|
+
import { join } from "node:path";
|
|
4
|
+
import { Client, UsageError, CliError, guard, parseFlags, type Context } from "../api.js";
|
|
5
|
+
import { BRAND, CLI_NAME, CONFIG_FILE } from "../brand.js";
|
|
6
|
+
|
|
7
|
+
export const USAGE = `Usage: ${CLI_NAME} init --name <name> [--origin <url>]
|
|
8
|
+
|
|
9
|
+
Creates an app on the server and writes ${CONFIG_FILE} with its app ID.
|
|
10
|
+
--name <name> the name users see on the consent page
|
|
11
|
+
--origin <url> an origin the app is served from, e.g. https://journal.example.com
|
|
12
|
+
(http://localhost:<port> may be used for development). Leave it
|
|
13
|
+
out for an app that is only a mobile app; register that with
|
|
14
|
+
${CLI_NAME} native set.
|
|
15
|
+
Needs PB_TOKEN (a developer token); PB_BASE_URL defaults to the local server.`;
|
|
16
|
+
|
|
17
|
+
interface CreatedApp {
|
|
18
|
+
id: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The scaffold: valid as written, and the commented example works once uncommented. */
|
|
22
|
+
function scaffold(appId: string): string {
|
|
23
|
+
return `// App config for ${BRAND}. Describe your collections inside collections, then run: ${CLI_NAME} deploy
|
|
24
|
+
// To try the example, remove the leading "// " from the lines inside collections
|
|
25
|
+
// and change the collection name to one you own: a reverse-domain name of at
|
|
26
|
+
// least three lowercase parts, e.g. com.yourname.notes.note
|
|
27
|
+
import { defineApp, collection, string, boolean } from "${CLI_NAME}";
|
|
28
|
+
|
|
29
|
+
export default defineApp({
|
|
30
|
+
app: ${JSON.stringify(appId)},
|
|
31
|
+
collections: {
|
|
32
|
+
// "com.example.notes.note": collection({
|
|
33
|
+
// version: 1,
|
|
34
|
+
// description: "A note written by the user",
|
|
35
|
+
// fields: {
|
|
36
|
+
// text: string({ description: "Note text", maxLength: 20000, required: true }),
|
|
37
|
+
// pinned: boolean({ description: "Whether the note is pinned" }),
|
|
38
|
+
// },
|
|
39
|
+
// }),
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export function init(ctx: Context): Promise<number> {
|
|
46
|
+
return guard(ctx, USAGE, async () => {
|
|
47
|
+
const { values } = parseFlags(ctx.args, { name: { type: "string" }, origin: { type: "string" } });
|
|
48
|
+
const name = values.name?.trim();
|
|
49
|
+
const origin = values.origin?.trim();
|
|
50
|
+
if (!name) throw new UsageError("--name is required");
|
|
51
|
+
|
|
52
|
+
const file = join(ctx.cwd, CONFIG_FILE);
|
|
53
|
+
if (existsSync(file)) {
|
|
54
|
+
throw new CliError(`${CONFIG_FILE} already exists in ${ctx.cwd}; not overwriting it. Delete or rename it to start over, or keep using it (its \`app\` value is the app ID).`);
|
|
55
|
+
}
|
|
56
|
+
const app = await new Client(ctx, true).request<CreatedApp>("POST", "/v1/apps", { body: { name, origins: origin ? [origin] : [] } });
|
|
57
|
+
try {
|
|
58
|
+
await writeFile(file, scaffold(app.id), { flag: "wx" });
|
|
59
|
+
} catch (e) {
|
|
60
|
+
throw new CliError(`created app ${app.id} but could not write ${file}: ${e instanceof Error ? e.message : String(e)}. Create the file yourself with app: "${app.id}".`);
|
|
61
|
+
}
|
|
62
|
+
ctx.out(`Created app ${app.id} (${name}, ${origin ? `origin ${origin}` : "no web address"}).`);
|
|
63
|
+
ctx.out(`Wrote ${CONFIG_FILE}.`);
|
|
64
|
+
ctx.out(`Next: define your collections in ${CONFIG_FILE} (see the commented example), then run: ${CLI_NAME} deploy`);
|
|
65
|
+
return 0;
|
|
66
|
+
});
|
|
67
|
+
}
|