@octabyte-io/paperstack-api-client 0.0.0-stage → 1.0.0-rc.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/LICENSE +203 -0
- package/README.md +48 -2
- package/dist/answer.d.ts +15 -0
- package/dist/answer.js +86 -0
- package/dist/errors.d.ts +38 -0
- package/dist/errors.js +37 -0
- package/dist/events.d.ts +31 -0
- package/dist/events.gen.d.ts +260 -0
- package/dist/events.gen.js +1 -0
- package/dist/events.js +1 -0
- package/dist/experimental/index.d.ts +1 -0
- package/dist/experimental/index.js +1 -0
- package/dist/file-answer.d.ts +13 -0
- package/dist/file-answer.js +55 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +4 -0
- package/dist/node/file-from-path.d.ts +6 -0
- package/dist/node/file-from-path.js +12 -0
- package/dist/node/index.d.ts +3 -0
- package/dist/node/index.js +4 -0
- package/dist/node/save-to-file.d.ts +7 -0
- package/dist/node/save-to-file.js +18 -0
- package/dist/operations.gen.d.ts +9406 -0
- package/dist/operations.gen.js +5 -0
- package/dist/paginate.d.ts +25 -0
- package/dist/paginate.js +17 -0
- package/dist/paper-stack.d.ts +45 -0
- package/dist/paper-stack.js +86 -0
- package/dist/resources.d.ts +15 -0
- package/dist/resources.js +9 -0
- package/dist/route-types.d.ts +73 -0
- package/dist/route-types.js +1 -0
- package/dist/routes.gen.d.ts +165 -0
- package/dist/routes.gen.js +177 -0
- package/dist/upload-body.d.ts +9 -0
- package/dist/upload-body.js +141 -0
- package/examples/file-invoice.ts +80 -0
- package/package.json +49 -3
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
/** The parts of a `RequestInit` a body sets. */
|
|
2
|
+
export interface SentBody {
|
|
3
|
+
body: string | FormData | ReadableStream<Uint8Array> | null;
|
|
4
|
+
headers: Record<string, string>;
|
|
5
|
+
duplex?: 'half';
|
|
6
|
+
redirect?: 'error';
|
|
7
|
+
}
|
|
8
|
+
/** What a call sends for `body`: nothing, JSON, or an upload's multipart body. */
|
|
9
|
+
export declare function sentBodyOf(body: unknown, signal: AbortSignal | null): SentBody;
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// What a call sends as its body: JSON, or for an upload (a body holding a `File`) a multipart body.
|
|
2
|
+
// Outside browsers it is streamed from the file with its size up front, so a big file never sits
|
|
3
|
+
// whole in memory and the api can refuse one too big before reading it (413). Browsers get plain
|
|
4
|
+
// `FormData`, which every one of them can send.
|
|
5
|
+
const encoder = new TextEncoder();
|
|
6
|
+
function isUpload(body) {
|
|
7
|
+
if (typeof body !== 'object' || body === null)
|
|
8
|
+
return false;
|
|
9
|
+
return Object.values(body).some((value) => value instanceof Blob);
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Whether the client runs in Node, Bun or Deno, which can stream a request body. Read from
|
|
13
|
+
* `navigator.userAgent`, which each of them sets to its own name (`Node.js/24`, `Bun/1.2`,
|
|
14
|
+
* `Deno/2.4`), or jsdom's (`... jsdom/30.1.2`): jsdom is a page made inside Node for tests, whose
|
|
15
|
+
* own `FormData` Node's `fetch` can't send. Anything else, browsers first, is sent `FormData`.
|
|
16
|
+
*/
|
|
17
|
+
function streamsUploads() {
|
|
18
|
+
const agent = globalThis.navigator?.userAgent;
|
|
19
|
+
return typeof agent === 'string' && /^(Node\.js|Bun|Deno)\/|\bjsdom\//.test(agent);
|
|
20
|
+
}
|
|
21
|
+
/** A file's bytes as a stream; jsdom's files have no `stream()`, so theirs are read whole. */
|
|
22
|
+
function streamOfFile(file) {
|
|
23
|
+
if (typeof file.stream === 'function')
|
|
24
|
+
return file.stream();
|
|
25
|
+
return new ReadableStream({
|
|
26
|
+
async start(controller) {
|
|
27
|
+
controller.enqueue(new Uint8Array(await file.arrayBuffer()));
|
|
28
|
+
controller.close();
|
|
29
|
+
},
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
/** The body's text fields first (the api reads them before the file), then its files. */
|
|
33
|
+
function partsOf(fields) {
|
|
34
|
+
const parts = Object.entries(fields).flatMap(([name, value]) => {
|
|
35
|
+
if (value === undefined)
|
|
36
|
+
return [];
|
|
37
|
+
if (value instanceof File)
|
|
38
|
+
return [[name, value]];
|
|
39
|
+
if (typeof value === 'string')
|
|
40
|
+
return [[name, value]];
|
|
41
|
+
throw new TypeError(`PaperStack: body.${name} must be text or a File`);
|
|
42
|
+
});
|
|
43
|
+
return parts.toSorted(([, a], [, b]) => Number(a instanceof File) - Number(b instanceof File));
|
|
44
|
+
}
|
|
45
|
+
function formDataOf(fields) {
|
|
46
|
+
const form = new FormData();
|
|
47
|
+
for (const [name, value] of partsOf(fields))
|
|
48
|
+
form.append(name, value);
|
|
49
|
+
return { body: form, headers: {} };
|
|
50
|
+
}
|
|
51
|
+
/** A name or file name inside a part's header, escaped as browsers do. */
|
|
52
|
+
const quoted = (text) => `"${text.replaceAll('"', '%22').replaceAll('\r', '%0D').replaceAll('\n', '%0A')}"`;
|
|
53
|
+
/** One multipart body read piece by piece: bytes as they are, files from their own streams. */
|
|
54
|
+
function streamOf(pieces, signal) {
|
|
55
|
+
let reading;
|
|
56
|
+
let next = 0;
|
|
57
|
+
const closeFile = (reason) => {
|
|
58
|
+
reading?.cancel(reason).catch(() => undefined);
|
|
59
|
+
reading = undefined;
|
|
60
|
+
};
|
|
61
|
+
/** The next bytes to send, or nothing once the body is done. */
|
|
62
|
+
const nextBytes = async () => {
|
|
63
|
+
for (;;) {
|
|
64
|
+
if (reading !== undefined) {
|
|
65
|
+
const { done, value } = await reading.read();
|
|
66
|
+
if (!done)
|
|
67
|
+
return value;
|
|
68
|
+
reading = undefined;
|
|
69
|
+
}
|
|
70
|
+
const piece = pieces[next++];
|
|
71
|
+
// Text is told from files by `Blob`: jsdom's `TextEncoder` gives another realm's Uint8Array.
|
|
72
|
+
if (piece === undefined || !(piece instanceof Blob))
|
|
73
|
+
return piece;
|
|
74
|
+
reading = streamOfFile(piece).getReader();
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
let stopReading = () => {
|
|
78
|
+
// Set once the stream starts.
|
|
79
|
+
};
|
|
80
|
+
return new ReadableStream({
|
|
81
|
+
start(controller) {
|
|
82
|
+
// Cancelling the call closes the file being read, whatever `fetch` does with the body.
|
|
83
|
+
stopReading = () => {
|
|
84
|
+
closeFile(signal?.reason);
|
|
85
|
+
controller.error(signal?.reason);
|
|
86
|
+
};
|
|
87
|
+
signal?.addEventListener('abort', stopReading, { once: true });
|
|
88
|
+
},
|
|
89
|
+
async pull(controller) {
|
|
90
|
+
const bytes = await nextBytes();
|
|
91
|
+
if (signal?.aborted)
|
|
92
|
+
return;
|
|
93
|
+
if (bytes !== undefined) {
|
|
94
|
+
controller.enqueue(bytes);
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
signal?.removeEventListener('abort', stopReading);
|
|
98
|
+
controller.close();
|
|
99
|
+
},
|
|
100
|
+
cancel(reason) {
|
|
101
|
+
signal?.removeEventListener('abort', stopReading);
|
|
102
|
+
closeFile(reason);
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
function streamedOf(fields, signal) {
|
|
107
|
+
const boundary = `PaperStack-${crypto.randomUUID()}`;
|
|
108
|
+
const pieces = [];
|
|
109
|
+
for (const [name, value] of partsOf(fields)) {
|
|
110
|
+
if (typeof value === 'string') {
|
|
111
|
+
const header = `Content-Disposition: form-data; name=${quoted(name)}\r\n\r\n`;
|
|
112
|
+
pieces.push(encoder.encode(`--${boundary}\r\n${header}${value}\r\n`));
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
const type = value.type === '' ? 'application/octet-stream' : value.type;
|
|
116
|
+
const header = `Content-Disposition: form-data; name=${quoted(name)}; filename=${quoted(value.name)}\r\n` +
|
|
117
|
+
`Content-Type: ${type}\r\n\r\n`;
|
|
118
|
+
pieces.push(encoder.encode(`--${boundary}\r\n${header}`), value, encoder.encode('\r\n'));
|
|
119
|
+
}
|
|
120
|
+
pieces.push(encoder.encode(`--${boundary}--\r\n`));
|
|
121
|
+
const size = pieces.reduce((sum, piece) => sum + (piece instanceof Blob ? piece.size : piece.length), 0);
|
|
122
|
+
return {
|
|
123
|
+
body: streamOf(pieces, signal),
|
|
124
|
+
headers: {
|
|
125
|
+
'content-type': `multipart/form-data; boundary=${boundary}`,
|
|
126
|
+
'content-length': String(size),
|
|
127
|
+
},
|
|
128
|
+
duplex: 'half',
|
|
129
|
+
// A redirect would need the body sent again, which a stream can't be.
|
|
130
|
+
redirect: 'error',
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
/** What a call sends for `body`: nothing, JSON, or an upload's multipart body. */
|
|
134
|
+
export function sentBodyOf(body, signal) {
|
|
135
|
+
if (body === undefined)
|
|
136
|
+
return { body: null, headers: {} };
|
|
137
|
+
if (!isUpload(body)) {
|
|
138
|
+
return { body: JSON.stringify(body), headers: { 'content-type': 'application/json' } };
|
|
139
|
+
}
|
|
140
|
+
return streamsUploads() ? streamedOf(body, signal) : formDataOf(body);
|
|
141
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
// Files an invoice into PaperStack, the whole demo in one script: finds or makes the folder "Finance"
|
|
2
|
+
// and the tag "Paid", uploads "Invoice March.pdf" (from the folder you run it in) into Finance, tags
|
|
3
|
+
// it Paid, lists Finance page by page, downloads the file back next to it, and shows how a refusal
|
|
4
|
+
// (here `document_not_found`) is handled.
|
|
5
|
+
//
|
|
6
|
+
// Run it with an access token holding documents:write, folders:write and tags:write:
|
|
7
|
+
//
|
|
8
|
+
// PAPERSTACK_URL=https://dms.example.com PAPERSTACK_TOKEN=pst_... node file-invoice.ts
|
|
9
|
+
//
|
|
10
|
+
// (or `bun file-invoice.ts`, or `deno run --allow-env --allow-net --allow-read --allow-write file-invoice.ts`).
|
|
11
|
+
// The client itself never reads environment variables: this script does, and hands them over.
|
|
12
|
+
import { env } from 'node:process';
|
|
13
|
+
|
|
14
|
+
import { PaperStack, PaperStackError } from '@octabyte-io/paperstack-api-client';
|
|
15
|
+
import { fileFromPath, saveToFile } from '@octabyte-io/paperstack-api-client/node';
|
|
16
|
+
|
|
17
|
+
const url = env['PAPERSTACK_URL'];
|
|
18
|
+
const token = env['PAPERSTACK_TOKEN'];
|
|
19
|
+
if (url === undefined || token === undefined) {
|
|
20
|
+
throw new Error('Set PAPERSTACK_URL and PAPERSTACK_TOKEN first');
|
|
21
|
+
}
|
|
22
|
+
const invoice = 'Invoice March.pdf';
|
|
23
|
+
const downloadedCopy = 'Invoice March (downloaded).pdf';
|
|
24
|
+
|
|
25
|
+
const ps = new PaperStack({ url, token });
|
|
26
|
+
|
|
27
|
+
// Find "Finance" at the top, or make it on a fresh install.
|
|
28
|
+
let finance;
|
|
29
|
+
for await (const folder of ps.paginate(ps.folders.list)) {
|
|
30
|
+
if (folder.parentId === null && folder.name === 'Finance') {
|
|
31
|
+
finance = folder;
|
|
32
|
+
break;
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
finance ??= await ps.folders.create({ body: { name: 'Finance', parentId: null } });
|
|
36
|
+
|
|
37
|
+
// Make the tag "Paid"; when it already exists, the refusal carries the existing tag to use instead.
|
|
38
|
+
let paid;
|
|
39
|
+
try {
|
|
40
|
+
paid = await ps.tags.create({ body: { name: 'Paid', color: 'green' } });
|
|
41
|
+
} catch (error) {
|
|
42
|
+
if (!(error instanceof PaperStackError && error.code === 'tag_name_taken')) throw error;
|
|
43
|
+
paid = error.problem.tag;
|
|
44
|
+
if (paid === undefined) throw error;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// The file is read from disk bit by bit as it is sent, never loaded whole into memory.
|
|
48
|
+
const uploaded = await ps.documents.upload({
|
|
49
|
+
query: { folder: finance.id },
|
|
50
|
+
body: { file: await fileFromPath(invoice) },
|
|
51
|
+
});
|
|
52
|
+
console.log(`Uploaded "${uploaded.fileName}" as document ${uploaded.id}`);
|
|
53
|
+
|
|
54
|
+
await ps.documents.addTag({ path: { id: uploaded.id, tagId: paid.id } });
|
|
55
|
+
console.log(`Tagged it "${paid.name}"`);
|
|
56
|
+
|
|
57
|
+
// Two documents per page, so a folder holding a few already takes more than one call.
|
|
58
|
+
let page = 0;
|
|
59
|
+
for await (const documents of ps.paginate.pages(ps.documents.list, {
|
|
60
|
+
query: { folder: finance.id, limit: 2 },
|
|
61
|
+
})) {
|
|
62
|
+
page += 1;
|
|
63
|
+
for (const document of documents) {
|
|
64
|
+
const tags = document.tags.map(({ name }) => name).join(', ');
|
|
65
|
+
console.log(`Finance, page ${String(page)}: ${document.title} [${tags}]`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// The download streams straight to disk.
|
|
70
|
+
const download = await ps.documents.download({ path: { id: uploaded.id } });
|
|
71
|
+
await saveToFile(download, downloadedCopy);
|
|
72
|
+
console.log(`Downloaded "${download.fileName ?? invoice}" to "${downloadedCopy}"`);
|
|
73
|
+
|
|
74
|
+
// A document that doesn't exist: a typed refusal to handle, not a crash.
|
|
75
|
+
try {
|
|
76
|
+
await ps.documents.get({ path: { id: crypto.randomUUID() } });
|
|
77
|
+
} catch (error) {
|
|
78
|
+
if (!(error instanceof PaperStackError && error.code === 'document_not_found')) throw error;
|
|
79
|
+
console.log(`Asking for a missing document answers ${String(error.status)} ${error.code}`);
|
|
80
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,52 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@octabyte-io/paperstack-api-client",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "1.0.0-rc.1",
|
|
4
|
+
"license": "Apache-2.0",
|
|
5
|
+
"description": "Typed client for the PaperStack API, generated from its public OpenAPI document",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/octabyte-io/paperstack.git",
|
|
9
|
+
"directory": "packages/api-client"
|
|
10
|
+
},
|
|
11
|
+
"type": "module",
|
|
12
|
+
"engines": {
|
|
13
|
+
"node": ">=24"
|
|
14
|
+
},
|
|
15
|
+
"files": [
|
|
16
|
+
"dist",
|
|
17
|
+
"examples/*.ts"
|
|
18
|
+
],
|
|
19
|
+
"exports": {
|
|
20
|
+
".": {
|
|
21
|
+
"types": "./dist/index.d.ts",
|
|
22
|
+
"default": "./dist/index.js"
|
|
23
|
+
},
|
|
24
|
+
"./node": {
|
|
25
|
+
"types": "./dist/node/index.d.ts",
|
|
26
|
+
"default": "./dist/node/index.js"
|
|
27
|
+
},
|
|
28
|
+
"./experimental": {
|
|
29
|
+
"types": "./dist/experimental/index.d.ts",
|
|
30
|
+
"default": "./dist/experimental/index.js"
|
|
31
|
+
}
|
|
32
|
+
},
|
|
33
|
+
"publishConfig": {
|
|
34
|
+
"access": "public"
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@arethetypeswrong/cli": "0.18.5",
|
|
38
|
+
"@paperstack/config": "1.0.0-rc.1",
|
|
39
|
+
"@types/node": "^24.19.1",
|
|
40
|
+
"eslint": "10.12.0",
|
|
41
|
+
"publint": "0.3.25",
|
|
42
|
+
"typescript": "6.0.3",
|
|
43
|
+
"vitest": "5.0.3"
|
|
44
|
+
},
|
|
45
|
+
"scripts": {
|
|
46
|
+
"build": "tsc -p tsconfig.build.json",
|
|
47
|
+
"lint": "eslint . --max-warnings 0",
|
|
48
|
+
"package:check": "publint --strict && attw --pack . --profile esm-only",
|
|
49
|
+
"typecheck": "tsc --noEmit && tsc --noEmit -p src/node && tsc --noEmit -p examples",
|
|
50
|
+
"test": "vitest run"
|
|
51
|
+
}
|
|
6
52
|
}
|