@aivax/cli 0.0.0-stage → 1.0.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 +21 -0
- package/README.md +114 -2
- package/package.json +31 -5
- package/src/args.js +84 -0
- package/src/cli.js +116 -0
- package/src/commands/account.js +132 -0
- package/src/commands/analytics.js +30 -0
- package/src/commands/api.js +37 -0
- package/src/commands/auth.js +124 -0
- package/src/commands/batch.js +191 -0
- package/src/commands/chat-clients.js +157 -0
- package/src/commands/conversations.js +92 -0
- package/src/commands/crud.js +68 -0
- package/src/commands/docs.js +91 -0
- package/src/commands/gateways.js +85 -0
- package/src/commands/generate.js +195 -0
- package/src/commands/logs.js +41 -0
- package/src/commands/models.js +38 -0
- package/src/commands/ocr.js +366 -0
- package/src/commands/rag.js +451 -0
- package/src/commands/shell.js +46 -0
- package/src/commands/skills.js +48 -0
- package/src/commands/tests.js +83 -0
- package/src/commands/web.js +68 -0
- package/src/errors.js +19 -0
- package/src/http.js +161 -0
- package/src/input.js +116 -0
- package/src/pdf.js +208 -0
- package/src/profiles.js +64 -0
- package/src/prompt.js +67 -0
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { UsageError } from "../errors.js";
|
|
2
|
+
import { call } from "../http.js";
|
|
3
|
+
import { dataUrl, isUrl, payload, readJson } from "../input.js";
|
|
4
|
+
|
|
5
|
+
export const schemaOption = { value: "<json>", description: "JSON Schema used to convert each result into JSON (JSON, @file or -)." };
|
|
6
|
+
|
|
7
|
+
export const fetchSources = async sources => Promise.all(sources.map(source => isUrl(source) || source.startsWith("data:") ? source : dataUrl(source)));
|
|
8
|
+
|
|
9
|
+
const search = {
|
|
10
|
+
description: "Search the web.",
|
|
11
|
+
options: {
|
|
12
|
+
query: { alias: "q", value: "<text>", description: "Search query. Also accepted as positional text." },
|
|
13
|
+
top: { alias: "k", value: "<n>", number: true, description: "Result count from 1 to 25." },
|
|
14
|
+
country: { value: "<code>", description: "Two-letter ISO 3166-1 country code." },
|
|
15
|
+
language: { value: "<code>", description: "Language code." },
|
|
16
|
+
domain: { value: "<domain>", list: true, description: "Restrict results to a domain. Repeatable." }
|
|
17
|
+
},
|
|
18
|
+
args: "[query]",
|
|
19
|
+
async run(ctx) {
|
|
20
|
+
const query = ctx.options.query ?? ctx.args.join(" ");
|
|
21
|
+
|
|
22
|
+
if (!query) {
|
|
23
|
+
throw new UsageError("Provide a search query with -q or positional text.");
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const body = await payload(ctx, {
|
|
27
|
+
query,
|
|
28
|
+
topn: ctx.options.top,
|
|
29
|
+
country: ctx.options.country,
|
|
30
|
+
language: ctx.options.language,
|
|
31
|
+
includeDomains: ctx.options.domain
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
await call(ctx, "POST", "/api/v1/web/search", { body });
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
|
|
38
|
+
const fetchCommand = {
|
|
39
|
+
aliases: ["read"],
|
|
40
|
+
description: "Extract readable text from URLs or local files.",
|
|
41
|
+
options: {
|
|
42
|
+
url: { alias: "u", value: "<url>", list: true, description: "URL to read. Repeatable. Also accepted as positional arguments." },
|
|
43
|
+
file: { alias: "f", value: "<file>", list: true, description: "Local file sent inline. Repeatable." },
|
|
44
|
+
schema: schemaOption,
|
|
45
|
+
noErrors: { description: "Omit failed items from the response." }
|
|
46
|
+
},
|
|
47
|
+
args: "[url...]",
|
|
48
|
+
async run(ctx) {
|
|
49
|
+
const sources = [...ctx.args, ...(ctx.options.url ?? []), ...(ctx.options.file ?? [])];
|
|
50
|
+
|
|
51
|
+
if (!sources.length) {
|
|
52
|
+
throw new UsageError("Provide at least one URL or file.");
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const body = {
|
|
56
|
+
contents: await fetchSources(sources),
|
|
57
|
+
returnErrors: ctx.options.noErrors ? false : undefined,
|
|
58
|
+
responseSchema: ctx.options.schema && await readJson(ctx.options.schema, "--schema")
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
await call(ctx, "POST", "/api/v1/web/fetch", { body });
|
|
62
|
+
}
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
export default {
|
|
66
|
+
description: "Web search and access commands.",
|
|
67
|
+
commands: { search, fetch: fetchCommand }
|
|
68
|
+
};
|
package/src/errors.js
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
export class UsageError extends Error { }
|
|
2
|
+
|
|
3
|
+
export class ApiError extends Error {
|
|
4
|
+
constructor(status, body, headers) {
|
|
5
|
+
let message = body.trim();
|
|
6
|
+
|
|
7
|
+
try {
|
|
8
|
+
const parsed = JSON.parse(body);
|
|
9
|
+
message = [parsed.error?.message ?? parsed.error ?? parsed.message, parsed.details && JSON.stringify(parsed.details)]
|
|
10
|
+
.filter(Boolean)
|
|
11
|
+
.join(" ") || message;
|
|
12
|
+
}
|
|
13
|
+
catch { }
|
|
14
|
+
|
|
15
|
+
super(message || `HTTP ${status}`);
|
|
16
|
+
this.status = status;
|
|
17
|
+
this.retryAfter = Number.parseFloat(headers?.get("retry-after") ?? "") * 1000 || 0;
|
|
18
|
+
}
|
|
19
|
+
}
|
package/src/http.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
import { ApiError, UsageError } from "./errors.js";
|
|
2
|
+
import { defaultEndpoint, resolveSession } from "./profiles.js";
|
|
3
|
+
|
|
4
|
+
export const VERSION = "1.0";
|
|
5
|
+
|
|
6
|
+
export const seg = encodeURIComponent;
|
|
7
|
+
|
|
8
|
+
const LONG_REQUEST_TIMEOUT_MS = 20 * 60_000;
|
|
9
|
+
|
|
10
|
+
// Long OCR and import calls go to the direct host, which is not behind the Cloudflare request timeout.
|
|
11
|
+
export const directEndpoint = endpoint => endpoint.replace(/^(https?:\/\/)inference\.aivax\.net/i, "$1direct.inference.aivax.net");
|
|
12
|
+
|
|
13
|
+
const isRawBody = body => body instanceof FormData
|
|
14
|
+
|| body instanceof Blob
|
|
15
|
+
|| body instanceof Uint8Array
|
|
16
|
+
|| body instanceof ArrayBuffer;
|
|
17
|
+
|
|
18
|
+
function buildUrl(endpoint, path, query = {}) {
|
|
19
|
+
const url = new URL(path, endpoint);
|
|
20
|
+
|
|
21
|
+
for (const [key, value] of Object.entries(query)) {
|
|
22
|
+
if (value !== undefined && value !== null && value !== "") {
|
|
23
|
+
url.searchParams.set(key, String(value));
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
return url;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export async function request(ctx, method, path, options = {}) {
|
|
31
|
+
const {
|
|
32
|
+
query,
|
|
33
|
+
body,
|
|
34
|
+
headers = {},
|
|
35
|
+
auth = true,
|
|
36
|
+
longRunning = false,
|
|
37
|
+
agentOutput = !ctx.options.verbose
|
|
38
|
+
} = options;
|
|
39
|
+
|
|
40
|
+
const session = auth
|
|
41
|
+
? await resolveSession(ctx)
|
|
42
|
+
: { endpoint: options.endpoint ?? defaultEndpoint() };
|
|
43
|
+
|
|
44
|
+
const init = {
|
|
45
|
+
method,
|
|
46
|
+
headers: { "User-Agent": `aivax-cli/${VERSION}`, ...headers }
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
if (session.token) {
|
|
50
|
+
init.headers.Authorization = `Bearer ${session.token}`;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
if (agentOutput) {
|
|
54
|
+
init.headers["X-Response-Truncating"] = "agent-optimized";
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
if (body !== undefined) {
|
|
58
|
+
init.body = isRawBody(body) ? body : JSON.stringify(body);
|
|
59
|
+
|
|
60
|
+
if (!isRawBody(body)) {
|
|
61
|
+
init.headers["Content-Type"] = "application/json";
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
if (longRunning) {
|
|
66
|
+
init.timeout = false;
|
|
67
|
+
init.signal = AbortSignal.timeout(LONG_REQUEST_TIMEOUT_MS);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
const endpoint = longRunning ? directEndpoint(session.endpoint) : session.endpoint;
|
|
71
|
+
const response = await fetch(buildUrl(endpoint, path, query), init);
|
|
72
|
+
|
|
73
|
+
if (!response.ok) {
|
|
74
|
+
throw new ApiError(response.status, await response.text(), response.headers);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
return response;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function unwrap(value) {
|
|
81
|
+
while (value && typeof value === "object" && !Array.isArray(value) && "data" in value && "message" in value) {
|
|
82
|
+
value = value.data;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
return value;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export async function fetchData(ctx, method, path, options = {}) {
|
|
89
|
+
const response = await request(ctx, method, path, { ...options, agentOutput: false });
|
|
90
|
+
const text = await response.text();
|
|
91
|
+
|
|
92
|
+
return text ? unwrap(JSON.parse(text)) : null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
export function print(value) {
|
|
96
|
+
const text = typeof value === "string" ? value : JSON.stringify(value, null, 2);
|
|
97
|
+
process.stdout.write(text.endsWith("\n") ? text : `${text}\n`);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function output(ctx, response) {
|
|
101
|
+
const type = response.headers.get("content-type") ?? "";
|
|
102
|
+
|
|
103
|
+
if (ctx.options.output) {
|
|
104
|
+
const bytes = await Bun.write(ctx.options.output, response);
|
|
105
|
+
process.stderr.write(`Saved ${bytes.toLocaleString("en-US")} bytes to ${ctx.options.output}\n`);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const isText = /json|toon|text|xml|jsonl|ndjson|event-stream/.test(type) || type === "";
|
|
110
|
+
|
|
111
|
+
if (!isText) {
|
|
112
|
+
if (process.stdout.isTTY) {
|
|
113
|
+
throw new UsageError(`The response is binary (${type}). Use -o <file> to save it.`);
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
await Bun.write(Bun.stdout, response);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const text = await response.text();
|
|
121
|
+
if (!text) {
|
|
122
|
+
return;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
if (ctx.options.verbose && type.includes("application/json")) {
|
|
126
|
+
try {
|
|
127
|
+
print(JSON.parse(text));
|
|
128
|
+
return;
|
|
129
|
+
}
|
|
130
|
+
catch { }
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
print(text);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export async function call(ctx, method, path, options) {
|
|
137
|
+
await output(ctx, await request(ctx, method, path, options));
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
export async function* events(response) {
|
|
141
|
+
const decoder = new TextDecoder();
|
|
142
|
+
let buffer = "";
|
|
143
|
+
|
|
144
|
+
for await (const chunk of response.body) {
|
|
145
|
+
buffer += decoder.decode(chunk, { stream: true });
|
|
146
|
+
|
|
147
|
+
let newline;
|
|
148
|
+
while ((newline = buffer.indexOf("\n")) >= 0) {
|
|
149
|
+
const line = buffer.slice(0, newline).replace(/\r$/, "");
|
|
150
|
+
buffer = buffer.slice(newline + 1);
|
|
151
|
+
|
|
152
|
+
if (line.startsWith("data:")) {
|
|
153
|
+
yield line.slice(5).trim();
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (buffer.startsWith("data:")) {
|
|
159
|
+
yield buffer.slice(5).trim();
|
|
160
|
+
}
|
|
161
|
+
}
|
package/src/input.js
ADDED
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { basename, extname } from "node:path";
|
|
2
|
+
import { UsageError } from "./errors.js";
|
|
3
|
+
|
|
4
|
+
export const isUrl = value => /^https?:\/\//i.test(value);
|
|
5
|
+
|
|
6
|
+
export async function openFile(path) {
|
|
7
|
+
const file = Bun.file(path);
|
|
8
|
+
|
|
9
|
+
if (!await file.exists()) {
|
|
10
|
+
throw new UsageError(`File not found: ${path}`);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
return file;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export async function readSource(value) {
|
|
17
|
+
if (value === "-" || value === "@-") {
|
|
18
|
+
return await Bun.stdin.text();
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
if (value.startsWith("@")) {
|
|
22
|
+
return await (await openFile(value.slice(1))).text();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
return value;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
export async function readJson(value, flag = "--data") {
|
|
29
|
+
const text = await readSource(value);
|
|
30
|
+
|
|
31
|
+
try {
|
|
32
|
+
return JSON.parse(text);
|
|
33
|
+
}
|
|
34
|
+
catch (error) {
|
|
35
|
+
throw new UsageError(`${flag} is not valid JSON: ${error.message}`);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export async function payload(ctx, fields = {}) {
|
|
40
|
+
const data = ctx.options.data === undefined ? {} : await readJson(ctx.options.data);
|
|
41
|
+
const defined = Object.fromEntries(Object.entries(fields).filter(([, value]) => value !== undefined));
|
|
42
|
+
|
|
43
|
+
return Object.keys(defined).length ? { ...data, ...defined } : data;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function base64(path) {
|
|
47
|
+
const file = await openFile(path);
|
|
48
|
+
return Buffer.from(await file.arrayBuffer()).toString("base64");
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export async function dataUrl(path) {
|
|
52
|
+
const file = await openFile(path);
|
|
53
|
+
return `data:${file.type};base64,${await base64(path)}`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
export async function contentPart(source) {
|
|
57
|
+
const remote = isUrl(source);
|
|
58
|
+
const type = Bun.file(remote ? new URL(source).pathname : source).type;
|
|
59
|
+
const kind = type.split("/")[0];
|
|
60
|
+
const url = remote ? source : await dataUrl(source);
|
|
61
|
+
|
|
62
|
+
if (kind === "image") {
|
|
63
|
+
return { type: "image_url", image_url: { url } };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
if (kind === "video") {
|
|
67
|
+
return { type: "video_url", video_url: { url } };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
if (kind === "audio" && !remote) {
|
|
71
|
+
return { type: "input_audio", input_audio: { data: await base64(source), format: extname(source).slice(1).toLowerCase() } };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
if (kind === "text" && !remote) {
|
|
75
|
+
return { type: "text", text: await Bun.file(source).text() };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
return { type: "file", file: { filename: basename(remote ? new URL(source).pathname : source), file_data: url } };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export async function documentParts(ctx) {
|
|
82
|
+
const parts = [
|
|
83
|
+
...await Promise.all((ctx.options.file ?? []).map(contentPart)),
|
|
84
|
+
...(ctx.options.text ?? []).map(text => ({ type: "text", text }))
|
|
85
|
+
];
|
|
86
|
+
|
|
87
|
+
if (!parts.length) {
|
|
88
|
+
throw new UsageError("Provide at least one document with -f <file|url> or --text <text>.");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
return parts;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function textDocuments(ctx) {
|
|
95
|
+
const documents = [
|
|
96
|
+
...await Promise.all((ctx.options.file ?? []).map(async path => (await openFile(path)).text())),
|
|
97
|
+
...(ctx.options.document ?? [])
|
|
98
|
+
];
|
|
99
|
+
|
|
100
|
+
if (!documents.length) {
|
|
101
|
+
throw new UsageError("Provide at least one document with -f <file> or --document <text>.");
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
return documents;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export const fileOption = description => ({ alias: "f", value: "<file>", list: true, description });
|
|
108
|
+
|
|
109
|
+
export const textOption = { value: "<text>", list: true, description: "Inline text document. Repeatable." };
|
|
110
|
+
|
|
111
|
+
export const dataOption = (required = false) => ({
|
|
112
|
+
alias: "d",
|
|
113
|
+
value: "<json>",
|
|
114
|
+
required,
|
|
115
|
+
description: "JSON request body, @file to read it from a file, or - for stdin."
|
|
116
|
+
});
|
package/src/pdf.js
ADDED
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { deflateSync, inflateSync } from "node:zlib";
|
|
2
|
+
import { PDFArray, PDFBool, PDFDict, PDFDocument, PDFName, PDFNumber, PDFRawStream, decodePDFRawStream } from "@cantoo/pdf-lib";
|
|
3
|
+
|
|
4
|
+
const MIN_IMAGE_BYTES = 64 * 1024;
|
|
5
|
+
const MAX_IMAGE_SIDE = 2400;
|
|
6
|
+
const JPEG_QUALITY = 75;
|
|
7
|
+
const PNG_SIGNATURE = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
|
|
8
|
+
|
|
9
|
+
const name = PDFName.of;
|
|
10
|
+
const latin1 = new TextDecoder("latin1");
|
|
11
|
+
const prunedGroups = new Set(["XObject", "Font", "ExtGState", "Pattern", "Shading", "ColorSpace", "Properties"].map(name));
|
|
12
|
+
|
|
13
|
+
const numberOf = (dict, key, fallback) => {
|
|
14
|
+
const value = dict?.lookup(name(key));
|
|
15
|
+
return value instanceof PDFNumber ? value.asNumber() : fallback;
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
function pngChunk(type, data) {
|
|
19
|
+
const chunk = Buffer.alloc(data.length + 12);
|
|
20
|
+
chunk.writeUInt32BE(data.length);
|
|
21
|
+
chunk.write(type, 4, "latin1");
|
|
22
|
+
chunk.set(data, 8);
|
|
23
|
+
chunk.writeUInt32BE(Bun.hash.crc32(chunk.subarray(4, data.length + 8)), data.length + 8);
|
|
24
|
+
|
|
25
|
+
return chunk;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function colorComponents(dict) {
|
|
29
|
+
const space = dict.lookup(name("ColorSpace"));
|
|
30
|
+
|
|
31
|
+
if (space === name("DeviceRGB")) return 3;
|
|
32
|
+
if (space === name("DeviceGray")) return 1;
|
|
33
|
+
|
|
34
|
+
if (space instanceof PDFArray && space.lookup(0) === name("ICCBased")) {
|
|
35
|
+
const components = numberOf(space.lookup(1)?.dict, "N", 0);
|
|
36
|
+
return components === 1 || components === 3 ? components : null;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
return null;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Returns the image as JPEG or PNG bytes that Bun.Image can decode, or null when it is not supported.
|
|
43
|
+
function encodedImage(dict, contents) {
|
|
44
|
+
const filters = dict.lookup(name("Filter"));
|
|
45
|
+
const filter = filters instanceof PDFArray ? (filters.size() === 1 ? filters.lookup(0) : null) : filters;
|
|
46
|
+
const components = colorComponents(dict);
|
|
47
|
+
|
|
48
|
+
if (!components || dict.has(name("Decode")) || filter === null) {
|
|
49
|
+
return null;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
if (filter === name("DCTDecode")) {
|
|
53
|
+
return contents;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
if ((filter && filter !== name("FlateDecode")) || numberOf(dict, "BitsPerComponent", 0) !== 8) {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const width = numberOf(dict, "Width", 0);
|
|
61
|
+
const height = numberOf(dict, "Height", 0);
|
|
62
|
+
const rowBytes = width * components;
|
|
63
|
+
const parms = dict.lookup(name("DecodeParms"));
|
|
64
|
+
const params = parms instanceof PDFArray ? parms.lookup(0) : parms;
|
|
65
|
+
const predictor = numberOf(params, "Predictor", 1);
|
|
66
|
+
let idat;
|
|
67
|
+
|
|
68
|
+
if (filter && predictor >= 10) {
|
|
69
|
+
// PNG predictors: the Flate data already is a PNG IDAT stream.
|
|
70
|
+
const matches = numberOf(params, "Colors", 1) === components
|
|
71
|
+
&& numberOf(params, "BitsPerComponent", 8) === 8
|
|
72
|
+
&& numberOf(params, "Columns", 1) === width;
|
|
73
|
+
|
|
74
|
+
if (!matches) return null;
|
|
75
|
+
idat = contents;
|
|
76
|
+
}
|
|
77
|
+
else if (predictor === 1) {
|
|
78
|
+
const pixels = filter ? inflateSync(contents) : contents;
|
|
79
|
+
if (pixels.length < rowBytes * height) return null;
|
|
80
|
+
|
|
81
|
+
const rows = Buffer.alloc((rowBytes + 1) * height);
|
|
82
|
+
for (let row = 0; row < height; row++) {
|
|
83
|
+
rows.set(pixels.subarray(row * rowBytes, (row + 1) * rowBytes), row * (rowBytes + 1) + 1);
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
idat = deflateSync(rows, { level: 1 });
|
|
87
|
+
}
|
|
88
|
+
else {
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
const header = Buffer.alloc(13);
|
|
93
|
+
header.writeUInt32BE(width);
|
|
94
|
+
header.writeUInt32BE(height, 4);
|
|
95
|
+
header[8] = 8;
|
|
96
|
+
header[9] = components === 3 ? 2 : 0;
|
|
97
|
+
|
|
98
|
+
return Buffer.concat([PNG_SIGNATURE, pngChunk("IHDR", header), pngChunk("IDAT", idat), pngChunk("IEND", new Uint8Array())]);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export async function openPdf(data) {
|
|
102
|
+
try {
|
|
103
|
+
return await PDFDocument.load(data, { password: "", updateMetadata: false });
|
|
104
|
+
}
|
|
105
|
+
catch (error) {
|
|
106
|
+
throw new Error(/password/i.test(error.message)
|
|
107
|
+
? "Password-protected PDFs are not supported."
|
|
108
|
+
: `The file is not a valid PDF document (${error.message}).`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export async function compressImages(doc) {
|
|
113
|
+
let images = 0;
|
|
114
|
+
let saved = 0;
|
|
115
|
+
|
|
116
|
+
for (const [, object] of doc.context.enumerateIndirectObjects()) {
|
|
117
|
+
if (!(object instanceof PDFRawStream) || object.dict.lookup(name("Subtype")) !== name("Image")) {
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
const { dict, contents } = object;
|
|
122
|
+
|
|
123
|
+
if (contents.length < MIN_IMAGE_BYTES || dict.lookup(name("ImageMask")) === PDFBool.True) {
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
try {
|
|
128
|
+
const source = encodedImage(dict, contents);
|
|
129
|
+
if (!source) continue;
|
|
130
|
+
|
|
131
|
+
const image = new Bun.Image(source)
|
|
132
|
+
.resize(MAX_IMAGE_SIDE, MAX_IMAGE_SIDE, { fit: "inside", withoutEnlargement: true })
|
|
133
|
+
.jpeg({ quality: JPEG_QUALITY });
|
|
134
|
+
|
|
135
|
+
const jpeg = await image.bytes();
|
|
136
|
+
if (jpeg.length >= contents.length * 0.8) continue;
|
|
137
|
+
|
|
138
|
+
saved += contents.length - jpeg.length;
|
|
139
|
+
object.updateContents(jpeg);
|
|
140
|
+
dict.set(name("Filter"), name("DCTDecode"));
|
|
141
|
+
dict.set(name("ColorSpace"), name("DeviceRGB"));
|
|
142
|
+
dict.set(name("Width"), PDFNumber.of(image.width));
|
|
143
|
+
dict.set(name("Height"), PDFNumber.of(image.height));
|
|
144
|
+
dict.set(name("BitsPerComponent"), PDFNumber.of(8));
|
|
145
|
+
dict.delete(name("DecodeParms"));
|
|
146
|
+
images++;
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
return { images, saved };
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export async function splitPages(doc, onProgress) {
|
|
157
|
+
const total = doc.getPageCount();
|
|
158
|
+
const pages = [];
|
|
159
|
+
|
|
160
|
+
for (let index = 0; index < total; index++) {
|
|
161
|
+
const leaf = doc.getPage(index).node;
|
|
162
|
+
const ownResources = leaf.get(name("Resources"));
|
|
163
|
+
|
|
164
|
+
try {
|
|
165
|
+
// Keep only the resources the page content uses, so pages of documents that share one
|
|
166
|
+
// resource dictionary across all pages do not carry every image and font of the file.
|
|
167
|
+
try {
|
|
168
|
+
const contents = leaf.Contents();
|
|
169
|
+
const streams = contents instanceof PDFArray ? contents.asArray().map(ref => doc.context.lookup(ref)) : [contents];
|
|
170
|
+
const used = new Set(streams.map(stream => latin1.decode(decodePDFRawStream(stream).decode())).join("\n").match(/\/[^\s/[\]()<>{}%]+/g));
|
|
171
|
+
const resources = leaf.Resources();
|
|
172
|
+
const pruned = doc.context.obj({});
|
|
173
|
+
|
|
174
|
+
for (const [key, value] of resources?.entries() ?? []) {
|
|
175
|
+
const group = prunedGroups.has(key) ? resources.lookup(key) : null;
|
|
176
|
+
|
|
177
|
+
if (!(group instanceof PDFDict)) {
|
|
178
|
+
pruned.set(key, value);
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
const kept = doc.context.obj({});
|
|
183
|
+
group.entries().filter(([entry]) => used.has(entry.asString())).forEach(([entry, ref]) => kept.set(entry, ref));
|
|
184
|
+
pruned.set(key, kept);
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (resources) leaf.set(name("Resources"), pruned);
|
|
188
|
+
}
|
|
189
|
+
catch { }
|
|
190
|
+
|
|
191
|
+
const single = await PDFDocument.create({ updateMetadata: false });
|
|
192
|
+
const [page] = await single.copyPages(doc, [index]);
|
|
193
|
+
single.addPage(page);
|
|
194
|
+
pages.push({ page: index + 1, bytes: await single.save({ useObjectStreams: true }), error: null });
|
|
195
|
+
}
|
|
196
|
+
catch (error) {
|
|
197
|
+
pages.push({ page: index + 1, bytes: null, error: `Split failed: ${error.message}` });
|
|
198
|
+
}
|
|
199
|
+
finally {
|
|
200
|
+
if (ownResources) leaf.set(name("Resources"), ownResources);
|
|
201
|
+
else leaf.delete(name("Resources"));
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
onProgress(index + 1, total);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
return pages;
|
|
208
|
+
}
|
package/src/profiles.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { mkdir } from "node:fs/promises";
|
|
2
|
+
import { homedir } from "node:os";
|
|
3
|
+
import { dirname, join } from "node:path";
|
|
4
|
+
import { UsageError } from "./errors.js";
|
|
5
|
+
|
|
6
|
+
const SERVICE = "aivax-cli";
|
|
7
|
+
|
|
8
|
+
const configHome = process.platform === "win32"
|
|
9
|
+
? process.env.APPDATA ?? join(homedir(), "AppData", "Roaming")
|
|
10
|
+
: process.env.XDG_CONFIG_HOME ?? join(homedir(), ".config");
|
|
11
|
+
|
|
12
|
+
const profilesFile = join(process.env.AIVAX_CLI_HOME ?? join(configHome, "aivax-cli"), "profiles.json");
|
|
13
|
+
|
|
14
|
+
export const defaultEndpoint = () => process.env.AIVAX_ENDPOINT ?? "https://inference.aivax.net";
|
|
15
|
+
|
|
16
|
+
export async function loadProfiles() {
|
|
17
|
+
const file = Bun.file(profilesFile);
|
|
18
|
+
|
|
19
|
+
return await file.exists()
|
|
20
|
+
? await file.json()
|
|
21
|
+
: { default: null, profiles: {} };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export async function saveProfiles(data) {
|
|
25
|
+
await mkdir(dirname(profilesFile), { recursive: true });
|
|
26
|
+
await Bun.write(profilesFile, JSON.stringify(data, null, 4));
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export const slugify = text => text
|
|
30
|
+
.normalize("NFD")
|
|
31
|
+
.replace(/[\u0300-\u036f]/g, "")
|
|
32
|
+
.toLowerCase()
|
|
33
|
+
.replace(/[^a-z0-9]+/g, "-")
|
|
34
|
+
.replace(/^-+|-+$/g, "");
|
|
35
|
+
|
|
36
|
+
export function findProfile(data, name) {
|
|
37
|
+
if (!name || !data.profiles[name]) {
|
|
38
|
+
throw new UsageError(name
|
|
39
|
+
? `Profile "${name}" not found. Run "aivax auth profiles" to list the saved profiles.`
|
|
40
|
+
: "No account profile found. Run \"aivax auth login\" first.");
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
return name;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export const storeToken = (name, value) => Bun.secrets.set({ service: SERVICE, name, value });
|
|
47
|
+
|
|
48
|
+
export const deleteToken = name => Bun.secrets.delete({ service: SERVICE, name });
|
|
49
|
+
|
|
50
|
+
export async function resolveSession(ctx) {
|
|
51
|
+
if (process.env.AIVAX_API_KEY && !ctx.options.profile) {
|
|
52
|
+
return { token: process.env.AIVAX_API_KEY, endpoint: defaultEndpoint() };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
const data = await loadProfiles();
|
|
56
|
+
const name = findProfile(data, ctx.options.profile ?? data.default);
|
|
57
|
+
const profile = data.profiles[name];
|
|
58
|
+
const token = await Bun.secrets.get({ service: SERVICE, name });
|
|
59
|
+
if (!token) {
|
|
60
|
+
throw new UsageError(`The access key of profile "${name}" is missing from the system credential store. Run "aivax auth login" again.`);
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
return { name, token, endpoint: process.env.AIVAX_ENDPOINT ?? profile.endpoint };
|
|
64
|
+
}
|