@zpdf/sdk 0.0.0-stage → 0.3.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +69 -0
- package/LICENSE +201 -0
- package/README.md +276 -2
- package/dist/cli/commands.d.ts +53 -0
- package/dist/cli/commands.js +1280 -0
- package/dist/cli/config.d.ts +8 -0
- package/dist/cli/config.js +21 -0
- package/dist/cli/errors.d.ts +30 -0
- package/dist/cli/errors.js +67 -0
- package/dist/cli/overrides.d.ts +4 -0
- package/dist/cli/overrides.js +107 -0
- package/dist/cli/parse.d.ts +18 -0
- package/dist/cli/parse.js +72 -0
- package/dist/cli/program.d.ts +15 -0
- package/dist/cli/program.js +323 -0
- package/dist/client.d.ts +263 -0
- package/dist/client.js +474 -0
- package/dist/config.d.ts +4 -0
- package/dist/config.js +5 -0
- package/dist/errors.d.ts +57 -0
- package/dist/errors.js +51 -0
- package/dist/http.d.ts +39 -0
- package/dist/http.js +156 -0
- package/dist/index.d.ts +13 -0
- package/dist/index.js +6 -0
- package/dist/overrides.d.ts +122 -0
- package/dist/overrides.js +72 -0
- package/dist/pagination.d.ts +20 -0
- package/dist/pagination.js +32 -0
- package/dist/runtime.d.ts +5 -0
- package/dist/runtime.js +31 -0
- package/dist/types.d.ts +574 -0
- package/dist/types.js +9 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +2 -0
- package/dist/webhooks.d.ts +31 -0
- package/dist/webhooks.js +76 -0
- package/package.json +68 -5
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export interface CliConfig {
|
|
2
|
+
apiKey?: string;
|
|
3
|
+
apiUrl?: string;
|
|
4
|
+
}
|
|
5
|
+
/** `ZPDF_CONFIG_PATH`, or `~/.zpdf/config.json`. */
|
|
6
|
+
export declare function configPath(env: Record<string, string | undefined>): string;
|
|
7
|
+
export declare function readConfig(env: Record<string, string | undefined>): CliConfig;
|
|
8
|
+
export declare function writeConfig(env: Record<string, string | undefined>, config: CliConfig): string;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
/** `ZPDF_CONFIG_PATH`, or `~/.zpdf/config.json`. */
|
|
5
|
+
export function configPath(env) {
|
|
6
|
+
return env.ZPDF_CONFIG_PATH ?? join(homedir(), ".zpdf", "config.json");
|
|
7
|
+
}
|
|
8
|
+
export function readConfig(env) {
|
|
9
|
+
try {
|
|
10
|
+
return JSON.parse(readFileSync(configPath(env), "utf8"));
|
|
11
|
+
}
|
|
12
|
+
catch {
|
|
13
|
+
return {};
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
export function writeConfig(env, config) {
|
|
17
|
+
const path = configPath(env);
|
|
18
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
19
|
+
writeFileSync(path, `${JSON.stringify(config, null, 2)}\n`, { mode: 0o600 });
|
|
20
|
+
return path;
|
|
21
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/** Exit codes are part of the contract: scripts and agents branch on them. */
|
|
2
|
+
export declare const EXIT: {
|
|
3
|
+
readonly OK: 0;
|
|
4
|
+
readonly FAILURE: 1;
|
|
5
|
+
readonly USAGE: 2;
|
|
6
|
+
readonly AUTH: 3;
|
|
7
|
+
readonly PERMISSION: 4;
|
|
8
|
+
};
|
|
9
|
+
export interface ErrorPayload {
|
|
10
|
+
type: string;
|
|
11
|
+
code: string | null;
|
|
12
|
+
message: string;
|
|
13
|
+
param: string | null;
|
|
14
|
+
request_id: string | null;
|
|
15
|
+
details?: Record<string, unknown>;
|
|
16
|
+
doc_url?: string;
|
|
17
|
+
}
|
|
18
|
+
export declare class CliError extends Error {
|
|
19
|
+
readonly exitCode: number;
|
|
20
|
+
readonly type: string;
|
|
21
|
+
readonly code: string | null;
|
|
22
|
+
readonly param: string | null;
|
|
23
|
+
constructor(message: string, exitCode?: number, type?: string, code?: string | null, param?: string | null);
|
|
24
|
+
}
|
|
25
|
+
/** A command line that cannot be run as written. Exit 2. */
|
|
26
|
+
export declare function usageError(message: string, param?: string | null): CliError;
|
|
27
|
+
export declare function toExit(error: unknown): {
|
|
28
|
+
exitCode: number;
|
|
29
|
+
payload: ErrorPayload;
|
|
30
|
+
};
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { ZPDFConnectionError, ZPDFError } from "../index.js";
|
|
2
|
+
/** Exit codes are part of the contract: scripts and agents branch on them. */
|
|
3
|
+
export const EXIT = { OK: 0, FAILURE: 1, USAGE: 2, AUTH: 3, PERMISSION: 4 };
|
|
4
|
+
export class CliError extends Error {
|
|
5
|
+
constructor(message, exitCode = EXIT.FAILURE, type = "cli_error", code = null, param = null) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.exitCode = exitCode;
|
|
8
|
+
this.type = type;
|
|
9
|
+
this.code = code;
|
|
10
|
+
this.param = param;
|
|
11
|
+
this.name = "CliError";
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
/** A command line that cannot be run as written. Exit 2. */
|
|
15
|
+
export function usageError(message, param = null) {
|
|
16
|
+
return new CliError(message, EXIT.USAGE, "usage_error", "usage", param);
|
|
17
|
+
}
|
|
18
|
+
export function toExit(error) {
|
|
19
|
+
if (error instanceof CliError) {
|
|
20
|
+
return {
|
|
21
|
+
exitCode: error.exitCode,
|
|
22
|
+
payload: {
|
|
23
|
+
type: error.type,
|
|
24
|
+
code: error.code,
|
|
25
|
+
message: error.message,
|
|
26
|
+
param: error.param,
|
|
27
|
+
request_id: null,
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
}
|
|
31
|
+
if (error instanceof ZPDFError) {
|
|
32
|
+
return {
|
|
33
|
+
exitCode: error.status === 401 ? EXIT.AUTH : error.status === 403 ? EXIT.PERMISSION : EXIT.FAILURE,
|
|
34
|
+
payload: {
|
|
35
|
+
type: error.type,
|
|
36
|
+
code: error.code,
|
|
37
|
+
message: error.message,
|
|
38
|
+
param: error.param ?? null,
|
|
39
|
+
request_id: error.requestId ?? null,
|
|
40
|
+
...(error.details !== undefined ? { details: error.details } : {}),
|
|
41
|
+
...(error.docUrl !== undefined ? { doc_url: error.docUrl } : {}),
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
}
|
|
45
|
+
if (error instanceof ZPDFConnectionError) {
|
|
46
|
+
return {
|
|
47
|
+
exitCode: EXIT.FAILURE,
|
|
48
|
+
payload: {
|
|
49
|
+
type: "connection_error",
|
|
50
|
+
code: "connection_failed",
|
|
51
|
+
message: error.message,
|
|
52
|
+
param: null,
|
|
53
|
+
request_id: null,
|
|
54
|
+
},
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
return {
|
|
58
|
+
exitCode: EXIT.FAILURE,
|
|
59
|
+
payload: {
|
|
60
|
+
type: "cli_error",
|
|
61
|
+
code: null,
|
|
62
|
+
message: error instanceof Error ? error.message : String(error),
|
|
63
|
+
param: null,
|
|
64
|
+
request_id: null,
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
import { type Override } from "../index.js";
|
|
2
|
+
export declare const OVERRIDE_HELP = "Override forms, applied in the order given:\n remove:REGION remove every element with that data-region\n replace:REGION=HTML replace the region's element\n insert_before:REGION=HTML add a fragment before the region\n insert_after:REGION=HTML add a fragment after the region\n append:REGION=HTML add a fragment inside the region, at the end\n prepend:REGION=HTML add a fragment inside the region, at the start\n css=CSS append CSS after the template's own\n set_asset:NAME=ASSET point a named asset at another stored asset\n set_page:size=Letter,margin=12mm change size, orientation, margin, header, footer\n add_field:NAME=TYPE declare one more input; TYPE! makes it required (string!)\n replace_file:html=HTML replace the whole HTML or CSS file\nA value that starts with @ is read from that file (append:notes=@clause.html).\nAn argument that starts with { is one operation as JSON.";
|
|
3
|
+
/** Turns one `--override` argument into the operation the API takes. */
|
|
4
|
+
export declare function parseOverride(text: string, readFile: (path: string) => string): Override;
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { overrideOps } from "../index.js";
|
|
2
|
+
import { usageError } from "./errors.js";
|
|
3
|
+
const fragmentOps = new Set(["replace", "insert_before", "insert_after", "append", "prepend"]);
|
|
4
|
+
export const OVERRIDE_HELP = `Override forms, applied in the order given:
|
|
5
|
+
remove:REGION remove every element with that data-region
|
|
6
|
+
replace:REGION=HTML replace the region's element
|
|
7
|
+
insert_before:REGION=HTML add a fragment before the region
|
|
8
|
+
insert_after:REGION=HTML add a fragment after the region
|
|
9
|
+
append:REGION=HTML add a fragment inside the region, at the end
|
|
10
|
+
prepend:REGION=HTML add a fragment inside the region, at the start
|
|
11
|
+
css=CSS append CSS after the template's own
|
|
12
|
+
set_asset:NAME=ASSET point a named asset at another stored asset
|
|
13
|
+
set_page:size=Letter,margin=12mm change size, orientation, margin, header, footer
|
|
14
|
+
add_field:NAME=TYPE declare one more input; TYPE! makes it required (string!)
|
|
15
|
+
replace_file:html=HTML replace the whole HTML or CSS file
|
|
16
|
+
A value that starts with @ is read from that file (append:notes=@clause.html).
|
|
17
|
+
An argument that starts with { is one operation as JSON.`;
|
|
18
|
+
function fail(text, why) {
|
|
19
|
+
throw usageError(`--override ${JSON.stringify(text)}: ${why}`, "--override");
|
|
20
|
+
}
|
|
21
|
+
/** Turns one `--override` argument into the operation the API takes. */
|
|
22
|
+
export function parseOverride(text, readFile) {
|
|
23
|
+
const trimmed = text.trim();
|
|
24
|
+
if (trimmed.startsWith("{")) {
|
|
25
|
+
try {
|
|
26
|
+
return JSON.parse(trimmed);
|
|
27
|
+
}
|
|
28
|
+
catch {
|
|
29
|
+
fail(text, "not valid JSON.");
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
const match = /^([a-z_]+)(?::([^=]*))?(?:=([\s\S]*))?$/.exec(trimmed);
|
|
33
|
+
const op = match?.[1];
|
|
34
|
+
if (match === null || op === undefined || !overrideOps.includes(op)) {
|
|
35
|
+
fail(text, `the operation is one of ${overrideOps.join(", ")}.`);
|
|
36
|
+
}
|
|
37
|
+
const target = match[2];
|
|
38
|
+
const raw = match[3];
|
|
39
|
+
const value = raw !== undefined && raw.startsWith("@") ? readFile(raw.slice(1)) : raw;
|
|
40
|
+
const need = (what, name, form) => {
|
|
41
|
+
if (what === undefined || what === "")
|
|
42
|
+
fail(text, `needs ${name}: ${form}.`);
|
|
43
|
+
return what;
|
|
44
|
+
};
|
|
45
|
+
if (op === "remove") {
|
|
46
|
+
if (value !== undefined)
|
|
47
|
+
fail(text, "remove takes only a region: remove:REGION.");
|
|
48
|
+
return { op, region: need(target, "a region", "remove:REGION") };
|
|
49
|
+
}
|
|
50
|
+
if (fragmentOps.has(op)) {
|
|
51
|
+
return {
|
|
52
|
+
op: op,
|
|
53
|
+
region: need(target, "a region", `${op}:REGION=HTML`),
|
|
54
|
+
html: need(value, "HTML", `${op}:REGION=HTML`),
|
|
55
|
+
};
|
|
56
|
+
}
|
|
57
|
+
if (op === "css") {
|
|
58
|
+
return { op, css: need(value, "CSS", "css=CSS") };
|
|
59
|
+
}
|
|
60
|
+
if (op === "set_asset") {
|
|
61
|
+
return {
|
|
62
|
+
op,
|
|
63
|
+
name: need(target, "an asset name", "set_asset:NAME=ASSET"),
|
|
64
|
+
asset: need(value, "an asset", "set_asset:NAME=ASSET"),
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
if (op === "set_page") {
|
|
68
|
+
if (target === undefined && value !== undefined && value.trim().startsWith("{")) {
|
|
69
|
+
try {
|
|
70
|
+
return { op, page: JSON.parse(value) };
|
|
71
|
+
}
|
|
72
|
+
catch {
|
|
73
|
+
fail(text, "the page is not valid JSON.");
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
const page = {};
|
|
77
|
+
const settings = trimmed.slice("set_page:".length);
|
|
78
|
+
for (const pair of settings.split(",")) {
|
|
79
|
+
const equals = pair.indexOf("=");
|
|
80
|
+
if (target === undefined || equals < 1)
|
|
81
|
+
fail(text, "needs settings: set_page:size=Letter,orientation=landscape.");
|
|
82
|
+
page[pair.slice(0, equals).trim()] = pair.slice(equals + 1).trim();
|
|
83
|
+
}
|
|
84
|
+
return { op, page: page };
|
|
85
|
+
}
|
|
86
|
+
if (op === "add_field") {
|
|
87
|
+
const name = need(target, "a field name", "add_field:NAME=TYPE");
|
|
88
|
+
const declared = need(value, "a type", "add_field:NAME=TYPE");
|
|
89
|
+
if (declared.trim().startsWith("{")) {
|
|
90
|
+
try {
|
|
91
|
+
return { op, name, field: JSON.parse(declared) };
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
fail(text, "the field is not valid JSON.");
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
const required = declared.endsWith("!");
|
|
98
|
+
const type = (required ? declared.slice(0, -1) : declared);
|
|
99
|
+
return { op, name, field: required ? { type, required: true } : { type } };
|
|
100
|
+
}
|
|
101
|
+
const file = need(target, "a file", "replace_file:html=HTML");
|
|
102
|
+
if (file !== "html" && file !== "css")
|
|
103
|
+
fail(text, "the file is html or css.");
|
|
104
|
+
if (value === undefined)
|
|
105
|
+
fail(text, "needs content: replace_file:html=HTML.");
|
|
106
|
+
return { op: "replace_file", file, content: value };
|
|
107
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export interface FlagSpec {
|
|
2
|
+
/** Without dashes, for example `make-current`. */
|
|
3
|
+
name: string;
|
|
4
|
+
short?: string;
|
|
5
|
+
type: "string" | "number" | "boolean" | "list";
|
|
6
|
+
/** The placeholder shown in help, for example `<file>`. */
|
|
7
|
+
value?: string;
|
|
8
|
+
help: string;
|
|
9
|
+
}
|
|
10
|
+
export type FlagValues = Record<string, string | number | boolean | string[] | undefined>;
|
|
11
|
+
export interface Parsed {
|
|
12
|
+
positionals: string[];
|
|
13
|
+
flags: FlagValues;
|
|
14
|
+
}
|
|
15
|
+
/** Parses arguments against the flags a command declares. Unknown flags are usage errors. */
|
|
16
|
+
export declare function parseArgs(argv: string[], specs: FlagSpec[]): Parsed;
|
|
17
|
+
/** Parses repeated `name=value` flags (metadata) into a record. */
|
|
18
|
+
export declare function keyValues(pairs: string[] | undefined, flag: string): Record<string, string> | undefined;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { usageError } from "./errors.js";
|
|
2
|
+
/** Parses arguments against the flags a command declares. Unknown flags are usage errors. */
|
|
3
|
+
export function parseArgs(argv, specs) {
|
|
4
|
+
const positionals = [];
|
|
5
|
+
const flags = {};
|
|
6
|
+
const byName = new Map(specs.map((spec) => [spec.name, spec]));
|
|
7
|
+
const byShort = new Map(specs.filter((spec) => spec.short !== undefined).map((spec) => [spec.short, spec]));
|
|
8
|
+
for (let index = 0; index < argv.length; index++) {
|
|
9
|
+
const token = argv[index];
|
|
10
|
+
if (token === "--") {
|
|
11
|
+
positionals.push(...argv.slice(index + 1));
|
|
12
|
+
break;
|
|
13
|
+
}
|
|
14
|
+
if (!token.startsWith("-") || token === "-") {
|
|
15
|
+
positionals.push(token);
|
|
16
|
+
continue;
|
|
17
|
+
}
|
|
18
|
+
let spec;
|
|
19
|
+
let inline;
|
|
20
|
+
if (token.startsWith("--")) {
|
|
21
|
+
const equals = token.indexOf("=");
|
|
22
|
+
const name = equals === -1 ? token.slice(2) : token.slice(2, equals);
|
|
23
|
+
inline = equals === -1 ? undefined : token.slice(equals + 1);
|
|
24
|
+
spec = byName.get(name);
|
|
25
|
+
}
|
|
26
|
+
else {
|
|
27
|
+
spec = byShort.get(token.slice(1));
|
|
28
|
+
}
|
|
29
|
+
if (spec === undefined) {
|
|
30
|
+
throw usageError(`Unknown flag ${token.split("=")[0]}. Run with --help for the flags this command takes.`, token.split("=")[0]);
|
|
31
|
+
}
|
|
32
|
+
if (spec.type === "boolean") {
|
|
33
|
+
if (inline !== undefined && inline !== "true" && inline !== "false") {
|
|
34
|
+
throw usageError(`--${spec.name} takes no value.`, `--${spec.name}`);
|
|
35
|
+
}
|
|
36
|
+
flags[spec.name] = inline !== "false";
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
const value = inline ?? argv[++index];
|
|
40
|
+
if (value === undefined) {
|
|
41
|
+
throw usageError(`--${spec.name} needs a value: --${spec.name} ${spec.value ?? "<value>"}.`, `--${spec.name}`);
|
|
42
|
+
}
|
|
43
|
+
if (spec.type === "number") {
|
|
44
|
+
const number = Number(value);
|
|
45
|
+
if (value.trim() === "" || !Number.isFinite(number)) {
|
|
46
|
+
throw usageError(`--${spec.name} is a number.`, `--${spec.name}`);
|
|
47
|
+
}
|
|
48
|
+
flags[spec.name] = number;
|
|
49
|
+
}
|
|
50
|
+
else if (spec.type === "list") {
|
|
51
|
+
flags[spec.name] = [...(flags[spec.name] ?? []), value];
|
|
52
|
+
}
|
|
53
|
+
else {
|
|
54
|
+
flags[spec.name] = value;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
return { positionals, flags };
|
|
58
|
+
}
|
|
59
|
+
/** Parses repeated `name=value` flags (metadata) into a record. */
|
|
60
|
+
export function keyValues(pairs, flag) {
|
|
61
|
+
if (pairs === undefined || pairs.length === 0)
|
|
62
|
+
return undefined;
|
|
63
|
+
const record = {};
|
|
64
|
+
for (const pair of pairs) {
|
|
65
|
+
const equals = pair.indexOf("=");
|
|
66
|
+
if (equals < 1) {
|
|
67
|
+
throw usageError(`--${flag} takes name=value, for example --${flag} order=ORD-1042.`, `--${flag}`);
|
|
68
|
+
}
|
|
69
|
+
record[pair.slice(0, equals)] = pair.slice(equals + 1);
|
|
70
|
+
}
|
|
71
|
+
return record;
|
|
72
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type FetchLike } from "../index.js";
|
|
2
|
+
import { type Command, type Io } from "./commands.js";
|
|
3
|
+
import { configPath } from "./config.js";
|
|
4
|
+
export declare function rootHelp(): string;
|
|
5
|
+
export declare function commandHelp(command: Command): string;
|
|
6
|
+
/** Finds the command named by the first one or two words. */
|
|
7
|
+
export declare function resolveCommand(words: string[]): {
|
|
8
|
+
command: Command;
|
|
9
|
+
length: number;
|
|
10
|
+
} | undefined;
|
|
11
|
+
/** Runs the CLI and returns the exit code. `overrides` replaces the outside world in tests. */
|
|
12
|
+
export declare function runCli(argv: string[], overrides?: Partial<Io> & {
|
|
13
|
+
fetch?: FetchLike;
|
|
14
|
+
}): Promise<number>;
|
|
15
|
+
export { configPath };
|
|
@@ -0,0 +1,323 @@
|
|
|
1
|
+
import { spawn } from "node:child_process";
|
|
2
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
import { DEFAULT_BASE_URL, DOCS_URL, VERSION, ZPDF, ZPDFConnectionError, ZPDFError, } from "../index.js";
|
|
5
|
+
import { commands, environmentKey, registerFetch } from "./commands.js";
|
|
6
|
+
import { configPath, readConfig } from "./config.js";
|
|
7
|
+
import { CliError, EXIT, toExit, usageError } from "./errors.js";
|
|
8
|
+
import { parseArgs } from "./parse.js";
|
|
9
|
+
const GLOBAL_FLAGS = [
|
|
10
|
+
{ name: "json", type: "boolean", help: "Print exactly one JSON value on stdout: the API's own object" },
|
|
11
|
+
{
|
|
12
|
+
name: "api-url",
|
|
13
|
+
type: "string",
|
|
14
|
+
value: "<url>",
|
|
15
|
+
help: "The API base URL ending in /v1 (default: ZPDF_API, then the config file)",
|
|
16
|
+
},
|
|
17
|
+
{
|
|
18
|
+
name: "dry-run",
|
|
19
|
+
type: "boolean",
|
|
20
|
+
help: "Print the HTTP request the command would send, as JSON, and send nothing",
|
|
21
|
+
},
|
|
22
|
+
{ name: "help", short: "h", type: "boolean", help: "Show help" },
|
|
23
|
+
{ name: "version", short: "V", type: "boolean", help: "Print the version" },
|
|
24
|
+
];
|
|
25
|
+
function defaultIo() {
|
|
26
|
+
return {
|
|
27
|
+
env: process.env,
|
|
28
|
+
stdout: (data) => void process.stdout.write(data),
|
|
29
|
+
stderr: (text) => void process.stderr.write(text),
|
|
30
|
+
readFile(path) {
|
|
31
|
+
try {
|
|
32
|
+
return readFileSync(path);
|
|
33
|
+
}
|
|
34
|
+
catch {
|
|
35
|
+
throw usageError(`Cannot read ${path}.`, path);
|
|
36
|
+
}
|
|
37
|
+
},
|
|
38
|
+
writeFile(path, data) {
|
|
39
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
40
|
+
writeFileSync(path, data);
|
|
41
|
+
},
|
|
42
|
+
fileExists: (path) => existsSync(path),
|
|
43
|
+
async readStdin() {
|
|
44
|
+
const chunks = [];
|
|
45
|
+
for await (const chunk of process.stdin)
|
|
46
|
+
chunks.push(chunk);
|
|
47
|
+
return Buffer.concat(chunks).toString("utf8");
|
|
48
|
+
},
|
|
49
|
+
open(target) {
|
|
50
|
+
const [command, args] = process.platform === "darwin"
|
|
51
|
+
? ["open", [target]]
|
|
52
|
+
: process.platform === "win32"
|
|
53
|
+
? ["cmd", ["/c", "start", "", target]]
|
|
54
|
+
: ["xdg-open", [target]];
|
|
55
|
+
return new Promise((resolve, reject) => {
|
|
56
|
+
const child = spawn(command, args, { stdio: "ignore", detached: true });
|
|
57
|
+
child.on("error", () => reject(new CliError(`Could not open ${target}. Open it yourself.`)));
|
|
58
|
+
child.on("spawn", () => {
|
|
59
|
+
child.unref();
|
|
60
|
+
resolve();
|
|
61
|
+
});
|
|
62
|
+
});
|
|
63
|
+
},
|
|
64
|
+
};
|
|
65
|
+
}
|
|
66
|
+
/** A command's flags, then the global ones it does not redefine (documents generate has its own --version). */
|
|
67
|
+
function flagsOf(command) {
|
|
68
|
+
const own = command.flags ?? [];
|
|
69
|
+
return [...own, ...GLOBAL_FLAGS.filter((flag) => !own.some((candidate) => candidate.name === flag.name))];
|
|
70
|
+
}
|
|
71
|
+
function groups() {
|
|
72
|
+
const map = new Map();
|
|
73
|
+
for (const command of commands) {
|
|
74
|
+
const group = command.name.split(" ")[0];
|
|
75
|
+
map.set(group, [...(map.get(group) ?? []), command]);
|
|
76
|
+
}
|
|
77
|
+
return map;
|
|
78
|
+
}
|
|
79
|
+
function flagLine(flag) {
|
|
80
|
+
const short = flag.short !== undefined ? `-${flag.short}, ` : " ";
|
|
81
|
+
return [`${short}--${flag.name}${flag.value !== undefined ? ` ${flag.value}` : ""}`, flag.help];
|
|
82
|
+
}
|
|
83
|
+
function columns(rows) {
|
|
84
|
+
const width = Math.max(...rows.map(([left]) => left.length));
|
|
85
|
+
return rows.map(([left, right]) => ` ${left.padEnd(width)} ${right}`).join("\n");
|
|
86
|
+
}
|
|
87
|
+
export function rootHelp() {
|
|
88
|
+
const rows = commands.map((command) => [command.name, command.summary]);
|
|
89
|
+
return `zpdf ${VERSION}: the API for agents to generate documents.
|
|
90
|
+
|
|
91
|
+
Usage: zpdf <command> [arguments] [flags]
|
|
92
|
+
Without installing: npx @zpdf/cli <command>. Install: npm install -g @zpdf/cli
|
|
93
|
+
|
|
94
|
+
Commands:
|
|
95
|
+
${columns(rows)}
|
|
96
|
+
|
|
97
|
+
Aliases: render = documents generate, templates save = templates push, whoami = business
|
|
98
|
+
|
|
99
|
+
Global flags:
|
|
100
|
+
${columns(GLOBAL_FLAGS.map(flagLine))}
|
|
101
|
+
|
|
102
|
+
Key: ZPDF_API_KEY, or the key stored by "zpdf login" in ~/.zpdf/config.json (ZPDF_CONFIG_PATH moves it).
|
|
103
|
+
Lists: --limit <n> and --starting-after <cursor> read one page; --all reads every page.
|
|
104
|
+
Exit codes: 0 success, 1 failure, 2 usage, 3 authentication, 4 permission.
|
|
105
|
+
Docs: ${DOCS_URL}
|
|
106
|
+
|
|
107
|
+
Example:
|
|
108
|
+
zpdf documents generate invoice --data data.json --override remove:col-unit-price -o invoice.pdf
|
|
109
|
+
|
|
110
|
+
Run "zpdf <command> --help" for a command's arguments, flags and an example.
|
|
111
|
+
`;
|
|
112
|
+
}
|
|
113
|
+
export function commandHelp(command) {
|
|
114
|
+
const args = (command.args ?? [])
|
|
115
|
+
.map((arg) => (arg.optional === true ? `[${arg.name}]` : `<${arg.name}>`))
|
|
116
|
+
.join(" ");
|
|
117
|
+
const parts = [
|
|
118
|
+
`${command.summary}.`,
|
|
119
|
+
"",
|
|
120
|
+
`Usage: zpdf ${command.name}${args !== "" ? ` ${args}` : ""} [flags]`,
|
|
121
|
+
`API: ${command.operation}`,
|
|
122
|
+
];
|
|
123
|
+
if (command.aliases !== undefined)
|
|
124
|
+
parts.push(`Alias: ${command.aliases.map((alias) => `zpdf ${alias}`).join(", ")}`);
|
|
125
|
+
if ((command.args ?? []).length > 0) {
|
|
126
|
+
parts.push("", "Arguments:", columns(command.args.map((arg) => [arg.name, arg.help])));
|
|
127
|
+
}
|
|
128
|
+
parts.push("", "Flags:", columns(flagsOf(command).map(flagLine)));
|
|
129
|
+
if (command.notes !== undefined)
|
|
130
|
+
parts.push("", command.notes);
|
|
131
|
+
parts.push("", "Example:", ` ${command.example}`, "");
|
|
132
|
+
return parts.join("\n");
|
|
133
|
+
}
|
|
134
|
+
function groupHelp(group, members) {
|
|
135
|
+
return `Usage: zpdf ${group} <command> [arguments] [flags]
|
|
136
|
+
|
|
137
|
+
Commands:
|
|
138
|
+
${columns(members.map((command) => [command.name, command.summary]))}
|
|
139
|
+
|
|
140
|
+
Example:
|
|
141
|
+
${members[0].example}
|
|
142
|
+
|
|
143
|
+
Run "zpdf <command> --help" for a command's arguments, flags and an example.
|
|
144
|
+
`;
|
|
145
|
+
}
|
|
146
|
+
/** Finds the command named by the first one or two words. */
|
|
147
|
+
export function resolveCommand(words) {
|
|
148
|
+
for (const length of [2, 1]) {
|
|
149
|
+
const name = words.slice(0, length).join(" ");
|
|
150
|
+
const command = commands.find((candidate) => candidate.name === name || candidate.aliases?.includes(name) === true);
|
|
151
|
+
if (command !== undefined && words.length >= length) {
|
|
152
|
+
return { command, length };
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
return undefined;
|
|
156
|
+
}
|
|
157
|
+
function printError(io, json, error) {
|
|
158
|
+
const { exitCode, payload } = toExit(error);
|
|
159
|
+
if (payload.code === "key_missing") {
|
|
160
|
+
payload.message = 'No API key. Set ZPDF_API_KEY or run "zpdf login --key zp_sk_…".';
|
|
161
|
+
}
|
|
162
|
+
if (json) {
|
|
163
|
+
io.stdout(`${JSON.stringify({ error: payload }, null, 2)}\n`);
|
|
164
|
+
return exitCode;
|
|
165
|
+
}
|
|
166
|
+
io.stderr(`error: ${payload.message}\n`);
|
|
167
|
+
const facts = [
|
|
168
|
+
payload.code !== null ? `code: ${payload.code}` : "",
|
|
169
|
+
payload.param !== null ? `param: ${payload.param}` : "",
|
|
170
|
+
payload.request_id !== null ? `request: ${payload.request_id}` : "",
|
|
171
|
+
].filter((fact) => fact !== "");
|
|
172
|
+
if (facts.length > 0)
|
|
173
|
+
io.stderr(` ${facts.join(" ")}\n`);
|
|
174
|
+
if (error instanceof ZPDFError) {
|
|
175
|
+
for (const problem of error.problems) {
|
|
176
|
+
io.stderr(` - ${problem.code}${problem.param !== undefined ? ` ${problem.param}` : ""}${problem.line !== undefined ? ` (line ${problem.line})` : ""}: ${problem.message}\n`);
|
|
177
|
+
}
|
|
178
|
+
if (typeof error.details?.did_you_mean === "string")
|
|
179
|
+
io.stderr(` did you mean: ${error.details.did_you_mean}\n`);
|
|
180
|
+
if (Array.isArray(error.details?.regions))
|
|
181
|
+
io.stderr(` regions: ${error.details.regions.join(", ")}\n`);
|
|
182
|
+
if (error.code === "key_missing" || error.code === "key_invalid") {
|
|
183
|
+
io.stderr(' Set ZPDF_API_KEY or run "zpdf login --key zp_sk_…". No key yet? zpdf signup start <email>\n');
|
|
184
|
+
}
|
|
185
|
+
if (error.code === "signup_code_invalid") {
|
|
186
|
+
io.stderr(" Ask for a new code: zpdf signup start <email>\n");
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return exitCode;
|
|
190
|
+
}
|
|
191
|
+
/** Thrown by the --dry-run fetch once the request is printed, to stop the command. */
|
|
192
|
+
class DryRunStop extends Error {
|
|
193
|
+
}
|
|
194
|
+
/**
|
|
195
|
+
* The fetch behind --dry-run: prints the request as one JSON object and
|
|
196
|
+
* sends nothing. The key is never printed.
|
|
197
|
+
*/
|
|
198
|
+
function dryRunFetch(io) {
|
|
199
|
+
return async (input, init) => {
|
|
200
|
+
const headers = {};
|
|
201
|
+
for (const [name, value] of Object.entries((init?.headers ?? {}))) {
|
|
202
|
+
headers[name] = name === "authorization" ? "Bearer <key>" : value;
|
|
203
|
+
}
|
|
204
|
+
let body;
|
|
205
|
+
if (typeof init?.body === "string") {
|
|
206
|
+
body = JSON.parse(init.body);
|
|
207
|
+
}
|
|
208
|
+
else if (init?.body instanceof FormData) {
|
|
209
|
+
const form = {};
|
|
210
|
+
init.body.forEach((value, name) => {
|
|
211
|
+
form[name] = typeof value === "string" ? value : { file: value.name, bytes: value.size };
|
|
212
|
+
});
|
|
213
|
+
headers["content-type"] = "multipart/form-data";
|
|
214
|
+
body = form;
|
|
215
|
+
}
|
|
216
|
+
const request = { dry_run: true, method: init?.method ?? "GET", url: input, headers };
|
|
217
|
+
io.stdout(`${JSON.stringify(body !== undefined ? { ...request, body } : request, null, 2)}\n`);
|
|
218
|
+
throw new DryRunStop();
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
/** Runs the CLI and returns the exit code. `overrides` replaces the outside world in tests. */
|
|
222
|
+
export async function runCli(argv, overrides = {}) {
|
|
223
|
+
const { fetch: givenFetch, ...ioOverrides } = overrides;
|
|
224
|
+
const io = { ...defaultIo(), ...ioOverrides };
|
|
225
|
+
const dryRun = argv.includes("--dry-run");
|
|
226
|
+
const fetch = dryRun ? dryRunFetch(io) : givenFetch;
|
|
227
|
+
registerFetch(io, fetch);
|
|
228
|
+
const json = argv.includes("--json");
|
|
229
|
+
try {
|
|
230
|
+
const wantsHelp = argv.includes("--help") || argv.includes("-h");
|
|
231
|
+
const words = argv.filter((token) => !token.startsWith("-"));
|
|
232
|
+
if (argv.length === 0 || (wantsHelp && words.length === 0) || words[0] === "help") {
|
|
233
|
+
const target = words[0] === "help" ? resolveCommand(words.slice(1)) : undefined;
|
|
234
|
+
io.stdout(target !== undefined ? commandHelp(target.command) : rootHelp());
|
|
235
|
+
return EXIT.OK;
|
|
236
|
+
}
|
|
237
|
+
if (argv[0] === "--version" || argv[0] === "-V") {
|
|
238
|
+
io.stdout(`${VERSION}\n`);
|
|
239
|
+
return EXIT.OK;
|
|
240
|
+
}
|
|
241
|
+
const start = argv.findIndex((token) => !token.startsWith("-"));
|
|
242
|
+
const leading = [];
|
|
243
|
+
for (const token of start === -1 ? [] : argv.slice(start)) {
|
|
244
|
+
if (token.startsWith("-"))
|
|
245
|
+
break;
|
|
246
|
+
leading.push(token);
|
|
247
|
+
}
|
|
248
|
+
const resolved = resolveCommand(leading);
|
|
249
|
+
if (resolved === undefined) {
|
|
250
|
+
const members = groups().get(leading[0] ?? "");
|
|
251
|
+
if (members !== undefined && (leading.length === 1 || wantsHelp)) {
|
|
252
|
+
io.stdout(groupHelp(leading[0], members));
|
|
253
|
+
return wantsHelp ? EXIT.OK : EXIT.USAGE;
|
|
254
|
+
}
|
|
255
|
+
throw usageError(members !== undefined
|
|
256
|
+
? `Unknown command "zpdf ${leading.slice(0, 2).join(" ")}". ${leading[0]} has: ${members.map((member) => member.name.split(" ")[1]).join(", ")}.`
|
|
257
|
+
: `Unknown command "${leading[0] ?? argv[0]}". Run "zpdf --help" for the list.`);
|
|
258
|
+
}
|
|
259
|
+
const { command } = resolved;
|
|
260
|
+
if (wantsHelp) {
|
|
261
|
+
io.stdout(commandHelp(command));
|
|
262
|
+
return EXIT.OK;
|
|
263
|
+
}
|
|
264
|
+
const parsed = parseArgs([...argv.slice(0, start), ...argv.slice(start + resolved.length)], flagsOf(command));
|
|
265
|
+
const declared = command.args ?? [];
|
|
266
|
+
if (parsed.positionals.length > declared.length) {
|
|
267
|
+
throw usageError(`zpdf ${command.name} takes ${declared.length} argument${declared.length === 1 ? "" : "s"}; got an extra "${parsed.positionals[declared.length]}".`);
|
|
268
|
+
}
|
|
269
|
+
const args = {};
|
|
270
|
+
declared.forEach((arg, index) => {
|
|
271
|
+
const value = parsed.positionals[index];
|
|
272
|
+
if (value === undefined && arg.optional !== true) {
|
|
273
|
+
throw usageError(`zpdf ${command.name} needs <${arg.name}>: ${arg.help}. Example: ${command.example}`, arg.name);
|
|
274
|
+
}
|
|
275
|
+
if (value !== undefined)
|
|
276
|
+
args[arg.name] = value;
|
|
277
|
+
});
|
|
278
|
+
const config = readConfig(io.env);
|
|
279
|
+
if (dryRun && command.operation === "local") {
|
|
280
|
+
io.stdout(`${JSON.stringify({ dry_run: true, method: null, url: null }, null, 2)}\n`);
|
|
281
|
+
return EXIT.OK;
|
|
282
|
+
}
|
|
283
|
+
const zpdf = new ZPDF({
|
|
284
|
+
apiKey: environmentKey(io.env) ?? config.apiKey ?? (dryRun ? "zp_sk_dry_run" : ""),
|
|
285
|
+
baseUrl: parsed.flags["api-url"] ??
|
|
286
|
+
io.env.ZPDF_API ??
|
|
287
|
+
config.apiUrl ??
|
|
288
|
+
DEFAULT_BASE_URL,
|
|
289
|
+
...(fetch !== undefined ? { fetch } : {}),
|
|
290
|
+
...(dryRun ? { maxRetries: 0 } : {}),
|
|
291
|
+
});
|
|
292
|
+
const context = {
|
|
293
|
+
args,
|
|
294
|
+
flags: parsed.flags,
|
|
295
|
+
io,
|
|
296
|
+
zpdf,
|
|
297
|
+
line: (text) => io.stdout(`${text}\n`),
|
|
298
|
+
note: (text) => io.stderr(`${text}\n`),
|
|
299
|
+
};
|
|
300
|
+
const value = await command.run(context);
|
|
301
|
+
if (value === undefined)
|
|
302
|
+
return EXIT.OK;
|
|
303
|
+
if (json) {
|
|
304
|
+
io.stdout(`${JSON.stringify(value, null, 2)}\n`);
|
|
305
|
+
}
|
|
306
|
+
else if (command.human !== undefined) {
|
|
307
|
+
command.human(value, context);
|
|
308
|
+
}
|
|
309
|
+
else {
|
|
310
|
+
io.stdout(`${JSON.stringify(value, null, 2)}\n`);
|
|
311
|
+
}
|
|
312
|
+
return EXIT.OK;
|
|
313
|
+
}
|
|
314
|
+
catch (error) {
|
|
315
|
+
if (dryRun &&
|
|
316
|
+
error instanceof ZPDFConnectionError &&
|
|
317
|
+
error.cause instanceof DryRunStop) {
|
|
318
|
+
return EXIT.OK;
|
|
319
|
+
}
|
|
320
|
+
return printError(io, json, error);
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
export { configPath };
|