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.
Files changed (51) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +51 -2
  3. package/dist/api.d.ts +96 -0
  4. package/dist/api.js +174 -0
  5. package/dist/api.js.map +1 -0
  6. package/dist/brand.d.ts +19 -0
  7. package/dist/brand.js +20 -0
  8. package/dist/brand.js.map +1 -0
  9. package/dist/cli.d.ts +4 -0
  10. package/dist/cli.js +66 -0
  11. package/dist/cli.js.map +1 -0
  12. package/dist/commands/deploy.d.ts +3 -0
  13. package/dist/commands/deploy.js +83 -0
  14. package/dist/commands/deploy.js.map +1 -0
  15. package/dist/commands/dev.d.ts +3 -0
  16. package/dist/commands/dev.js +132 -0
  17. package/dist/commands/dev.js.map +1 -0
  18. package/dist/commands/generate.d.ts +4 -0
  19. package/dist/commands/generate.js +33 -0
  20. package/dist/commands/generate.js.map +1 -0
  21. package/dist/commands/init.d.ts +3 -0
  22. package/dist/commands/init.js +62 -0
  23. package/dist/commands/init.js.map +1 -0
  24. package/dist/commands/mcp.d.ts +3 -0
  25. package/dist/commands/mcp.js +151 -0
  26. package/dist/commands/mcp.js.map +1 -0
  27. package/dist/commands/native.d.ts +3 -0
  28. package/dist/commands/native.js +114 -0
  29. package/dist/commands/native.js.map +1 -0
  30. package/dist/compile.d.ts +37 -0
  31. package/dist/compile.js +187 -0
  32. package/dist/compile.js.map +1 -0
  33. package/dist/config.d.ts +58 -0
  34. package/dist/config.js +24 -0
  35. package/dist/config.js.map +1 -0
  36. package/dist/index.d.ts +2 -0
  37. package/dist/index.js +24 -0
  38. package/dist/index.js.map +1 -0
  39. package/package.json +45 -4
  40. package/src/api.ts +216 -0
  41. package/src/brand.ts +23 -0
  42. package/src/cli.ts +66 -0
  43. package/src/commands/deploy.ts +88 -0
  44. package/src/commands/dev.ts +127 -0
  45. package/src/commands/generate.ts +35 -0
  46. package/src/commands/init.ts +67 -0
  47. package/src/commands/mcp.ts +145 -0
  48. package/src/commands/native.ts +125 -0
  49. package/src/compile.ts +217 -0
  50. package/src/config.ts +73 -0
  51. package/src/index.ts +26 -0
@@ -0,0 +1,145 @@
1
+ import { ApiError, Client, formatApiError, guard, parseFlags, redact, requireToken, type Context } from "../api.js";
2
+ import { CLI_NAME } from "../brand.js";
3
+
4
+ export const USAGE = `Usage: ${CLI_NAME} mcp
5
+
6
+ A bridge for agents that speak MCP over stdio. Each newline-delimited JSON-RPC
7
+ message read from stdin is POSTed to PB_BASE_URL/mcp with your developer token,
8
+ and each response message is written to stdout as one line. Diagnostics go to
9
+ stderr. It exits when stdin closes.
10
+ Needs PB_TOKEN (a developer token); PB_BASE_URL defaults to the local server.`;
11
+
12
+ /** The JSON-RPC server-error code used for transport failures. */
13
+ const TRANSPORT_ERROR = -32000;
14
+ const PARSE_ERROR = -32700;
15
+
16
+ type Json = Record<string, unknown>;
17
+
18
+ function isRpc(text: string): boolean {
19
+ try {
20
+ return (JSON.parse(text) as Json | null)?.jsonrpc === "2.0";
21
+ } catch {
22
+ return false;
23
+ }
24
+ }
25
+
26
+ /** Reads the data fields of server-sent events from a stream, calling onData for each event. */
27
+ async function readEvents(body: ReadableStream<Uint8Array>, onData: (data: string) => void): Promise<void> {
28
+ const decoder = new TextDecoder();
29
+ const reader = body.getReader();
30
+ let buf = "";
31
+ const flush = (block: string) => {
32
+ const data = block
33
+ .split("\n")
34
+ .filter((l) => l.startsWith("data:"))
35
+ .map((l) => l.slice(5).replace(/^ /, ""))
36
+ .join("\n");
37
+ if (data !== "") onData(data);
38
+ };
39
+ for (;;) {
40
+ const { done, value } = await reader.read();
41
+ buf += decoder.decode(value, { stream: !done }).replace(/\r\n?/g, "\n");
42
+ let i: number;
43
+ while ((i = buf.indexOf("\n\n")) >= 0) {
44
+ flush(buf.slice(0, i));
45
+ buf = buf.slice(i + 2);
46
+ }
47
+ if (done) break;
48
+ }
49
+ if (buf.trim() !== "") flush(buf);
50
+ }
51
+
52
+ export function mcp(ctx: Context): Promise<number> {
53
+ return guard(ctx, USAGE, async () => {
54
+ parseFlags(ctx.args, {});
55
+ const token = requireToken(ctx.env);
56
+ const client = new Client(ctx, true);
57
+ const url = `${client.baseUrl}/mcp`;
58
+
59
+ const emit = (msg: unknown) => ctx.out(JSON.stringify(msg));
60
+ const rpcError = (id: unknown, code: number, message: string) => emit({ jsonrpc: "2.0", id, error: { code, message } });
61
+ /** fail reports a failed request: to the caller when it has an id, else on stderr. */
62
+ const fail = (id: unknown, message: string) => {
63
+ const text = redact(message, token);
64
+ if (id !== undefined) rpcError(id, TRANSPORT_ERROR, text);
65
+ else ctx.err(`${CLI_NAME} mcp: ${text}`);
66
+ };
67
+ const emitMessage = (text: string) => {
68
+ let parsed: unknown;
69
+ try {
70
+ parsed = JSON.parse(text);
71
+ } catch {
72
+ ctx.err(`${CLI_NAME} mcp: the server sent a message that is not JSON; dropped it`);
73
+ return;
74
+ }
75
+ for (const m of Array.isArray(parsed) ? parsed : [parsed]) emit(m);
76
+ };
77
+
78
+ const handle = async (line: string): Promise<void> => {
79
+ let msg: unknown;
80
+ try {
81
+ msg = JSON.parse(line);
82
+ } catch {
83
+ rpcError(null, PARSE_ERROR, "the message is not valid JSON");
84
+ return;
85
+ }
86
+ const id = typeof msg === "object" && msg !== null && "id" in msg ? (msg as Json).id : undefined;
87
+ let res: Response;
88
+ try {
89
+ res = await ctx.fetch(url, {
90
+ method: "POST",
91
+ headers: {
92
+ Authorization: `Bearer ${token}`,
93
+ "Content-Type": "application/json",
94
+ Accept: "application/json, text/event-stream",
95
+ },
96
+ body: line,
97
+ });
98
+ } catch (e) {
99
+ fail(id, client.networkError(e).message);
100
+ return;
101
+ }
102
+ try {
103
+ if (!res.ok) {
104
+ const text = await res.text().catch(() => "");
105
+ // A JSON-RPC error body (for example for a malformed request) is passed on as it is.
106
+ if (isRpc(text)) {
107
+ emitMessage(text);
108
+ return;
109
+ }
110
+ const err = client.errorFromText(res.status, text, url);
111
+ fail(id, err instanceof ApiError ? formatApiError(err).join(" ").replace(/^error: /, "") : err.message);
112
+ return;
113
+ }
114
+ if (res.status === 202 || res.status === 204 || !res.body) return;
115
+ if ((res.headers.get("content-type") ?? "").includes("text/event-stream")) {
116
+ await readEvents(res.body, emitMessage);
117
+ } else {
118
+ const text = await res.text();
119
+ if (text.trim() !== "") emitMessage(text);
120
+ }
121
+ } catch (e) {
122
+ fail(id, `the response could not be read: ${e instanceof Error ? e.message : String(e)}`);
123
+ }
124
+ };
125
+
126
+ const pending: Promise<void>[] = [];
127
+ const decoder = new TextDecoder();
128
+ let buf = "";
129
+ const take = (line: string) => {
130
+ if (line.trim() !== "") pending.push(handle(line.trim()));
131
+ };
132
+ for await (const chunk of ctx.stdin) {
133
+ buf += typeof chunk === "string" ? chunk : decoder.decode(chunk, { stream: true });
134
+ let i: number;
135
+ while ((i = buf.indexOf("\n")) >= 0) {
136
+ take(buf.slice(0, i));
137
+ buf = buf.slice(i + 1);
138
+ }
139
+ }
140
+ buf += decoder.decode();
141
+ take(buf);
142
+ await Promise.all(pending);
143
+ return 0;
144
+ });
145
+ }
@@ -0,0 +1,125 @@
1
+ import { join } from "node:path";
2
+ import { parseArgs } from "node:util";
3
+ import { Client, UsageError, guard, type Context } from "../api.js";
4
+ import { CLI_NAME, CONFIG_FILE } from "../brand.js";
5
+ import { compileConfig } from "../compile.js";
6
+
7
+ export const USAGE = `Usage: ${CLI_NAME} native set [--ios <team>.<bundle>]... [--android <package>=<fingerprint>[,<fingerprint>]...]...
8
+ ${CLI_NAME} native show
9
+
10
+ Registers the iOS and Android apps that are the app in ${CONFIG_FILE}, so that
11
+ a phone hands a sign-in back to those apps and no other.
12
+ set replaces the list of each platform that is given; a platform that is
13
+ not given is left as it is. "--ios none" or "--android none" clears it.
14
+ --ios A1B2C3D4E5.com.example.notes
15
+ the Apple team ID, a dot, the bundle ID
16
+ --android com.example.notes=14:6D:...,AA:BB:...
17
+ the package name, "=", the SHA-256 fingerprints of the
18
+ certificates the app is signed with (a debug build, an upload
19
+ key and the store's signing key each have their own)
20
+ show prints what is registered and the address a sign-in returns to.
21
+ Needs PB_TOKEN (a developer token); PB_BASE_URL defaults to the local server.`;
22
+
23
+ interface IOSApp {
24
+ teamId: string;
25
+ bundleId: string;
26
+ }
27
+ interface AndroidApp {
28
+ package: string;
29
+ sha256: string[];
30
+ }
31
+ interface App {
32
+ id: string;
33
+ name: string;
34
+ ios?: IOSApp[];
35
+ android?: AndroidApp[];
36
+ nativeReturnUrl?: string;
37
+ }
38
+
39
+ const NONE = "none";
40
+
41
+ /** list reads one platform's flag values: undefined when not given, [] for "none". */
42
+ function list<T>(flag: string, values: string[] | undefined, parse: (v: string) => T): T[] | undefined {
43
+ if (values === undefined) return undefined;
44
+ if (values.includes(NONE)) {
45
+ if (values.length > 1) throw new UsageError(`${flag} ${NONE} cannot be combined with other ${flag} values`);
46
+ return [];
47
+ }
48
+ return values.map(parse);
49
+ }
50
+
51
+ function ios(v: string): IOSApp {
52
+ const dot = v.indexOf(".");
53
+ const teamId = v.slice(0, dot);
54
+ const bundleId = v.slice(dot + 1);
55
+ // A bundle ID has a dot of its own, so "com.example.notes" alone is a team "com".
56
+ if (dot < 0 || !/^[A-Z0-9]{10}$/.test(teamId) || bundleId === "") {
57
+ throw new UsageError(`--ios ${v}: want <team ID>.<bundle ID>, e.g. A1B2C3D4E5.com.example.notes`);
58
+ }
59
+ return { teamId, bundleId };
60
+ }
61
+
62
+ function android(v: string): AndroidApp {
63
+ const eq = v.indexOf("=");
64
+ const pkg = v.slice(0, eq);
65
+ const sha256 = v
66
+ .slice(eq + 1)
67
+ .split(",")
68
+ .map((f) => f.trim())
69
+ .filter((f) => f !== "");
70
+ if (eq <= 0 || sha256.length === 0) {
71
+ throw new UsageError(`--android ${v}: want <package>=<fingerprint>[,<fingerprint>], e.g. com.example.notes=14:6D:...`);
72
+ }
73
+ return { package: pkg, sha256 };
74
+ }
75
+
76
+ function print(ctx: Context, app: App): void {
77
+ const none = !app.ios?.length && !app.android?.length;
78
+ for (const i of app.ios ?? []) ctx.out(`iOS ${i.teamId}.${i.bundleId}`);
79
+ for (const a of app.android ?? []) {
80
+ ctx.out(`Android ${a.package}`);
81
+ for (const f of a.sha256) ctx.out(` ${f}`);
82
+ }
83
+ if (none) {
84
+ ctx.out("No iOS or Android app is registered.");
85
+ } else if (app.nativeReturnUrl) {
86
+ ctx.out(`Return address: ${app.nativeReturnUrl}`);
87
+ } else {
88
+ ctx.out("This server is not set up for released mobile apps (PB_APP_LINKS_DOMAIN). Development sign-in still works.");
89
+ }
90
+ }
91
+
92
+ export function native(ctx: Context): Promise<number> {
93
+ return guard(ctx, USAGE, async () => {
94
+ const [sub, ...rest] = ctx.args;
95
+ if (sub !== "set" && sub !== "show") throw new UsageError(sub === undefined ? "say set or show" : `unknown subcommand "${sub}"`);
96
+ let values: { ios?: string[] | undefined; android?: string[] | undefined };
97
+ try {
98
+ const parsed = parseArgs({
99
+ args: rest,
100
+ options: sub === "set" ? { ios: { type: "string", multiple: true }, android: { type: "string", multiple: true } } : {},
101
+ strict: true,
102
+ allowPositionals: false,
103
+ });
104
+ values = parsed.values as unknown as typeof values;
105
+ } catch (e) {
106
+ throw new UsageError(e instanceof Error ? e.message : String(e));
107
+ }
108
+ const body: { ios?: IOSApp[]; android?: AndroidApp[] } = {};
109
+ if (sub === "set") {
110
+ const i = list("--ios", values.ios, ios);
111
+ const a = list("--android", values.android, android);
112
+ if (i === undefined && a === undefined) throw new UsageError("give --ios, --android or both");
113
+ if (i !== undefined) body.ios = i;
114
+ if (a !== undefined) body.android = a;
115
+ }
116
+
117
+ const config = await compileConfig(join(ctx.cwd, CONFIG_FILE));
118
+ const client = new Client(ctx, true);
119
+ const path = `/v1/apps/${encodeURIComponent(config.app)}`;
120
+ const app = sub === "set" ? await client.request<App>("PATCH", path, { body }) : await client.request<App>("GET", path);
121
+ if (sub === "show") ctx.out(`App ${app.id} (${app.name}) on ${client.baseUrl}`);
122
+ print(ctx, app);
123
+ return 0;
124
+ });
125
+ }
package/src/compile.ts ADDED
@@ -0,0 +1,217 @@
1
+ import { existsSync } from "node:fs";
2
+ import { resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { createJiti } from "jiti";
5
+ import { CliError } from "./api.js";
6
+ import { CLI_NAME } from "./brand.js";
7
+ import type { AppDef, CollectionDef, FieldDef } from "./config.js";
8
+
9
+ /** WireField is a field as the server's schema JSON has it. */
10
+ export interface WireField {
11
+ type: string;
12
+ description: string;
13
+ required?: boolean;
14
+ maxLength?: number;
15
+ min?: number;
16
+ max?: number;
17
+ values?: string[];
18
+ indexed?: boolean;
19
+ sensitive?: boolean;
20
+ }
21
+
22
+ /** WireCollection is a collection definition exactly as the server takes it. */
23
+ export interface WireCollection {
24
+ name: string;
25
+ version: number;
26
+ description: string;
27
+ fields: Record<string, WireField>;
28
+ }
29
+
30
+ export interface CompiledConfig {
31
+ app: string;
32
+ collections: WireCollection[];
33
+ }
34
+
35
+ /** ConfigError is a problem in the developer's config file. */
36
+ export class ConfigError extends CliError {
37
+ override name = "ConfigError";
38
+ }
39
+
40
+ // The server's rules (server/internal/schemas): keep these in step.
41
+ const MAX_NAME_LEN = 128;
42
+ const MAX_FIELD_NAME_LEN = 64;
43
+ const NAME_RE = /^[a-z][a-z0-9-]*(\.[a-z][a-z0-9-]*){2,}$/;
44
+ const FIELD_NAME_RE = new RegExp(`^[a-zA-Z][a-zA-Z0-9_]{0,${MAX_FIELD_NAME_LEN - 1}}$`);
45
+ const RESERVED_FIELDS = ["createdAt", "updatedAt"];
46
+ const RESERVED_PREFIXES = ["core.", "sandbox."];
47
+ const FIELD_TYPES = ["string", "number", "integer", "boolean", "datetime", "enum", "json", "fileRef", "recordRef"];
48
+ /** The wire key order of a field. */
49
+ const FIELD_KEYS = ["type", "description", "required", "maxLength", "min", "max", "values", "indexed", "sensitive"] as const;
50
+
51
+ const isObject = (v: unknown): v is Record<string, unknown> => typeof v === "object" && v !== null && !Array.isArray(v);
52
+ const blank = (v: unknown): boolean => typeof v !== "string" || v.trim() === "";
53
+
54
+ /** configPath returns where the helpers imported from the CLI package are loaded from. */
55
+ function helpersPath(): string {
56
+ for (const ext of ["js", "ts"]) {
57
+ const p = fileURLToPath(new URL(`./config.${ext}`, import.meta.url));
58
+ if (existsSync(p)) return p;
59
+ }
60
+ throw new Error("the config helpers module is missing from this installation");
61
+ }
62
+
63
+ function compileField(collName: string, name: string, raw: unknown): WireField {
64
+ const where = `collection "${collName}", field "${name}"`;
65
+ if (!FIELD_NAME_RE.test(name)) {
66
+ throw new ConfigError(`${where}: invalid field name. Field names start with a letter and use only letters, digits and _ (at most ${MAX_FIELD_NAME_LEN} characters).`);
67
+ }
68
+ if (RESERVED_FIELDS.includes(name)) {
69
+ throw new ConfigError(`${where}: name is reserved. ${name} is a system field; choose another name.`);
70
+ }
71
+ if (!isObject(raw)) {
72
+ throw new ConfigError(`${where}: not a field definition. Build fields with string(), integer(), enumOf() and the other helpers.`);
73
+ }
74
+ const f = raw as Partial<FieldDef> & Record<string, unknown>;
75
+ for (const k of Object.keys(f)) {
76
+ if (!(FIELD_KEYS as readonly string[]).includes(k)) {
77
+ throw new ConfigError(`${where}: unknown option "${k}". Allowed options: ${FIELD_KEYS.slice(1).join(", ")} (names are case-sensitive).`);
78
+ }
79
+ }
80
+ if (typeof f.type !== "string" || !FIELD_TYPES.includes(f.type)) {
81
+ throw new ConfigError(`${where}: unknown type ${JSON.stringify(f.type)}. Use one of the helpers: ${FIELD_TYPES.map((t) => (t === "enum" ? "enumOf" : t)).join(", ")}.`);
82
+ }
83
+ if (blank(f.description)) {
84
+ throw new ConfigError(`${where}: missing description. Add description: "..." to the field's options; consent prompts and agent docs are generated from it.`);
85
+ }
86
+ for (const k of ["required", "indexed", "sensitive"] as const) {
87
+ if (f[k] !== undefined && typeof f[k] !== "boolean") {
88
+ throw new ConfigError(`${where}: ${k} must be true or false.`);
89
+ }
90
+ }
91
+ if (f.maxLength !== undefined) {
92
+ if (f.type !== "string") {
93
+ throw new ConfigError(`${where}: maxLength is only allowed on string fields. Remove maxLength or change the type to string.`);
94
+ }
95
+ if (!Number.isInteger(f.maxLength) || f.maxLength < 1) {
96
+ throw new ConfigError(`${where}: maxLength must be a whole number of at least 1. Set it to 1 or more, or remove it.`);
97
+ }
98
+ }
99
+ if (f.min !== undefined || f.max !== undefined) {
100
+ if (f.type !== "number" && f.type !== "integer") {
101
+ throw new ConfigError(`${where}: min and max are only allowed on number and integer fields. Remove them or change the type.`);
102
+ }
103
+ for (const k of ["min", "max"] as const) {
104
+ if (f[k] !== undefined && (typeof f[k] !== "number" || !Number.isFinite(f[k]))) {
105
+ throw new ConfigError(`${where}: ${k} must be a finite number.`);
106
+ }
107
+ }
108
+ if (f.min !== undefined && f.max !== undefined && f.min > f.max) {
109
+ throw new ConfigError(`${where}: min is greater than max. Make min less than or equal to max.`);
110
+ }
111
+ }
112
+ if (f.type === "enum") {
113
+ if (!Array.isArray(f.values) || f.values.length === 0) {
114
+ throw new ConfigError(`${where}: enumOf needs at least one value. Write enumOf(["a", "b"], { description: "..." }).`);
115
+ }
116
+ const seen = new Set<string>();
117
+ for (const v of f.values) {
118
+ if (typeof v !== "string" || v === "") {
119
+ throw new ConfigError(`${where}: enumOf values must be non-empty strings. Remove the empty or non-string value.`);
120
+ }
121
+ if (seen.has(v)) {
122
+ throw new ConfigError(`${where}: enumOf values contain "${v}" twice. Make every value unique.`);
123
+ }
124
+ seen.add(v);
125
+ }
126
+ } else if (f.values !== undefined) {
127
+ throw new ConfigError(`${where}: values is only allowed on enumOf fields.`);
128
+ }
129
+ if (f.indexed === true && f.type === "json") {
130
+ throw new ConfigError(`${where}: json fields cannot be indexed. Remove indexed, or store the searchable part in a separate string, number or enumOf field.`);
131
+ }
132
+ const out: Record<string, unknown> = {};
133
+ for (const k of FIELD_KEYS) {
134
+ if (f[k] !== undefined) out[k] = f[k];
135
+ }
136
+ return out as unknown as WireField;
137
+ }
138
+
139
+ function compileCollection(name: string, raw: unknown): WireCollection {
140
+ if (name.length > MAX_NAME_LEN || !NAME_RE.test(name)) {
141
+ throw new ConfigError(
142
+ `collection name "${name}" is invalid. Use a reverse-domain name of at least three lowercase segments, e.g. com.example.journal.entry (letters, digits and - only; at most ${MAX_NAME_LEN} characters).`,
143
+ );
144
+ }
145
+ if (RESERVED_PREFIXES.some((p) => name.startsWith(p))) {
146
+ throw new ConfigError(`collection "${name}" is in a reserved namespace. core.* and sandbox.* belong to the platform; use your own reverse-domain name.`);
147
+ }
148
+ if (!isObject(raw)) {
149
+ throw new ConfigError(`collection "${name}": not a collection definition. Build it with collection({ version, description, fields }).`);
150
+ }
151
+ const c = raw as Partial<CollectionDef>;
152
+ if (typeof c.version !== "number" || !Number.isInteger(c.version) || c.version < 1) {
153
+ throw new ConfigError(`collection "${name}": version must be a whole number of at least 1. Set version: 1 for a new collection.`);
154
+ }
155
+ if (blank(c.description)) {
156
+ throw new ConfigError(`collection "${name}" has no description. Add description: "..." saying what the collection holds; consent prompts are generated from it.`);
157
+ }
158
+ if (!isObject(c.fields) || Object.keys(c.fields).length === 0) {
159
+ throw new ConfigError(`collection "${name}" has no fields. Define at least one field under fields.`);
160
+ }
161
+ const fields: Record<string, WireField> = {};
162
+ for (const fname of Object.keys(c.fields)) {
163
+ fields[fname] = compileField(name, fname, c.fields[fname]);
164
+ }
165
+ return { name, version: c.version, description: c.description as string, fields };
166
+ }
167
+
168
+ /** compileApp validates an app description and returns the wire form. */
169
+ export function compileApp(def: unknown): CompiledConfig {
170
+ if (!isObject(def) || typeof def.app !== "string" || !isObject(def.collections)) {
171
+ throw new ConfigError("the default export is not an app description. Export defineApp({ app, collections }).");
172
+ }
173
+ const d = def as unknown as AppDef;
174
+ if (d.app.trim() === "") {
175
+ throw new ConfigError(`app is empty. Set app to the app ID (starts with app_) printed by "${CLI_NAME} init".`);
176
+ }
177
+ const collections = Object.keys(d.collections)
178
+ .sort()
179
+ .map((name) => compileCollection(name, d.collections[name]));
180
+ return { app: d.app, collections };
181
+ }
182
+
183
+ /**
184
+ * compileConfig loads the config file at path (TypeScript or JavaScript,
185
+ * through jiti) and returns the app ID and each collection in the server's
186
+ * wire JSON, in name order. Anything the server's schema parser would reject
187
+ * is an error here that names the collection and field.
188
+ */
189
+ export async function compileConfig(path: string): Promise<CompiledConfig> {
190
+ const file = resolve(path);
191
+ if (!existsSync(file)) {
192
+ throw new ConfigError(`config file ${file} not found. Create it with "${CLI_NAME} init --name <name> --origin <url>", or run this command in the directory that holds it.`);
193
+ }
194
+ const jiti = createJiti(file, {
195
+ // The helpers are imported from the package name; resolve that to this
196
+ // installation so a config works wherever the CLI was installed from.
197
+ alias: { [CLI_NAME]: helpersPath() },
198
+ moduleCache: false,
199
+ fsCache: false,
200
+ });
201
+ let mod: unknown;
202
+ try {
203
+ mod = await jiti.import(file);
204
+ } catch (e) {
205
+ throw new ConfigError(`could not load ${file}: ${e instanceof Error ? e.message : String(e)}`);
206
+ }
207
+ const def = isObject(mod) ? mod.default : undefined;
208
+ if (def === undefined) {
209
+ throw new ConfigError(`${file} has no default export. End it with: export default defineApp({ app: "app_...", collections: { ... } });`);
210
+ }
211
+ try {
212
+ return compileApp(def);
213
+ } catch (e) {
214
+ if (e instanceof ConfigError) throw new ConfigError(`${file}: ${e.message}`);
215
+ throw e;
216
+ }
217
+ }
package/src/config.ts ADDED
@@ -0,0 +1,73 @@
1
+ /**
2
+ * The helpers a pb.config.ts is written with. Each returns a plain,
3
+ * serialisable description; nothing is checked here beyond the shape. The
4
+ * rules the server enforces are checked by compileConfig (compile.ts), which
5
+ * can name the collection and field.
6
+ */
7
+
8
+ export type FieldType = "string" | "number" | "integer" | "boolean" | "datetime" | "enum" | "json" | "fileRef" | "recordRef";
9
+
10
+ /** Options every field helper accepts. */
11
+ export interface BaseOptions {
12
+ /** What the field holds. Required: consent prompts and agent docs are generated from it. */
13
+ description: string;
14
+ required?: boolean;
15
+ indexed?: boolean;
16
+ sensitive?: boolean;
17
+ }
18
+
19
+ export interface StringOptions extends BaseOptions {
20
+ maxLength?: number;
21
+ }
22
+
23
+ export interface NumberOptions extends BaseOptions {
24
+ min?: number;
25
+ max?: number;
26
+ }
27
+
28
+ /** FieldDef is the description a field helper returns. */
29
+ export interface FieldDef {
30
+ type: FieldType;
31
+ description: string;
32
+ required?: boolean;
33
+ maxLength?: number;
34
+ min?: number;
35
+ max?: number;
36
+ values?: string[];
37
+ indexed?: boolean;
38
+ sensitive?: boolean;
39
+ }
40
+
41
+ export interface CollectionDef {
42
+ /** The major version. */
43
+ version: number;
44
+ description: string;
45
+ fields: Record<string, FieldDef>;
46
+ }
47
+
48
+ export interface AppDef {
49
+ /** The app ID from `init` (starts with app_). */
50
+ app: string;
51
+ collections: Record<string, CollectionDef>;
52
+ }
53
+
54
+ export const string = (options: StringOptions): FieldDef => ({ type: "string", ...options });
55
+ export const number = (options: NumberOptions): FieldDef => ({ type: "number", ...options });
56
+ export const integer = (options: NumberOptions): FieldDef => ({ type: "integer", ...options });
57
+ export const boolean = (options: BaseOptions): FieldDef => ({ type: "boolean", ...options });
58
+ export const datetime = (options: BaseOptions): FieldDef => ({ type: "datetime", ...options });
59
+ export const json = (options: Omit<BaseOptions, "indexed">): FieldDef => ({ type: "json", ...options });
60
+ export const fileRef = (options: BaseOptions): FieldDef => ({ type: "fileRef", ...options });
61
+ export const recordRef = (options: BaseOptions): FieldDef => ({ type: "recordRef", ...options });
62
+
63
+ /** enumOf is a field that holds one of the listed strings (wire type "enum"). */
64
+ export const enumOf = (values: readonly string[], options: BaseOptions): FieldDef => ({
65
+ type: "enum",
66
+ ...options,
67
+ values: [...values],
68
+ });
69
+
70
+ export const collection = (def: CollectionDef): CollectionDef => def;
71
+
72
+ /** defineApp returns the app description unchanged; compileConfig checks it. */
73
+ export const defineApp = (def: AppDef): AppDef => def;
package/src/index.ts ADDED
@@ -0,0 +1,26 @@
1
+ #!/usr/bin/env node
2
+ import { spawn } from "node:child_process";
3
+ import { readFileSync } from "node:fs";
4
+ import { homedir } from "node:os";
5
+ import { run } from "./cli.js";
6
+
7
+ const pkg = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8")) as { version: string };
8
+
9
+ // A closed pipe (for example `phibac --help | head`) is not an error.
10
+ process.stdout.on("error", () => {});
11
+
12
+ const code = await run(process.argv.slice(2), {
13
+ args: [],
14
+ env: process.env,
15
+ cwd: process.cwd(),
16
+ out: (line) => void process.stdout.write(line + "\n"),
17
+ err: (line) => void process.stderr.write(line + "\n"),
18
+ fetch,
19
+ stdin: process.stdin,
20
+ spawn,
21
+ version: pkg.version,
22
+ platform: process.platform,
23
+ arch: process.arch,
24
+ homedir: homedir(),
25
+ });
26
+ process.exitCode = code;