invoice-builder-sdk 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/README.md ADDED
@@ -0,0 +1,358 @@
1
+ # Invoice Builder SDK 🚀
2
+
3
+ [![NPM Version](https://img.shields.io/npm/v/invoice-builder-sdk.svg?style=flat-back)](https://www.npmjs.com/package/invoice-builder-sdk)
4
+ [![License](https://img.shields.io/npm/l/invoice-builder-sdk.svg?style=flat-back)](https://github.com/invoice-builder/invoice-builder-open-api/blob/main/LICENSE)
5
+ [![Bundle Size](https://img.shields.io/bundlephobia/min/invoice-builder-sdk?style=flat-back)](https://bundlephobia.com/package/invoice-builder-sdk)
6
+ [![TypeScript Support](https://img.shields.io/badge/TypeScript-Ready-blue.svg?style=flat-back)](https://www.typescriptlang.org/)
7
+ [![PRs Welcome](https://img.shields.io/badge/PRs-welcome-brightgreen.svg?style=flat-back)](https://github.com/invoice-builder/invoice-builder-open-api/pulls)
8
+
9
+ A modern, ultra-lightweight, and zero-dependency TypeScript/JavaScript client library for the **Invoice Builder Open API**. Seamlessly integrate dynamic PDF/PNG invoice generation, historical auditing, and custom template schemas into any JS runtime (Node.js, Browsers, Cloudflare Workers, Vercel Edge, Bun, Deno).
10
+
11
+ ---
12
+
13
+ ## Table of Contents
14
+
15
+ - [Features](#features)
16
+ - [Installation](#installation)
17
+ - [Authentication & Configuration](#authentication--configuration)
18
+ - [Getting Started](#getting-started)
19
+ - [ESM / TypeScript](#esm--typescript)
20
+ - [CommonJS / JavaScript](#commonjs--javascript)
21
+ - [API Reference](#api-reference)
22
+ - [`listTemplates`](#listtemplatesoptions)
23
+ - [`getTemplateFields`](#gettemplatefieldsoptions)
24
+ - [`listHistory`](#listhistoryoptions)
25
+ - [`generatePdf`](#generatepdfpayload)
26
+ - [Error Handling](#error-handling)
27
+ - [Advanced Usage](#advanced-usage)
28
+ - [Vercel Edge & Cloudflare Workers](#vercel-edge--cloudflare-workers)
29
+ - [Express / Fastify PDF Streaming](#express--fastify-pdf-streaming)
30
+ - [License](#license)
31
+
32
+ ---
33
+
34
+ ## Features
35
+
36
+ - 📦 **Dual-Package Architecture**: Out-of-the-box support for both ES Modules (`import`) and CommonJS (`require`).
37
+ - ⚡ **Zero External Dependencies**: Built entirely on top of the native `fetch` API for maximum speed, security, and low memory footprints.
38
+ - 🔒 **Type-Safe Out of the Box**: Ships with comprehensive, strict TypeScript typings mirroring backend schemas (`Invoice`, `InvoiceTemplate`, `ComponentConfig`).
39
+ - 🛠️ **Environment-Agnostic**: Compatible with Node.js 18+, Edge/Serverless functions, and modern browsers.
40
+ - 📦 **Multiple File Packaging**: Built-in support to compile up to two templates and return a unified ZIP archive.
41
+
42
+ ---
43
+
44
+ ## Installation
45
+
46
+ Install via npm:
47
+
48
+ ```bash
49
+ npm install invoice-builder-sdk
50
+ ```
51
+
52
+ Or via yarn:
53
+
54
+ ```bash
55
+ yarn add invoice-builder-sdk
56
+ ```
57
+
58
+ Or via pnpm:
59
+
60
+ ```bash
61
+ pnpm add invoice-builder-sdk
62
+ ```
63
+
64
+ ---
65
+
66
+ ## Authentication & Configuration
67
+
68
+ The `InvoiceBuilder` class is initialized with a configuration object:
69
+
70
+ ```typescript
71
+ import { InvoiceBuilder } from "invoice-builder-sdk";
72
+
73
+ const client = new InvoiceBuilder({
74
+ apiKey: "ib_your_api_key_here",
75
+ baseUrl: "https://api.invoicingbuilder.com",
76
+ });
77
+ ```
78
+
79
+ ### Configuration Options
80
+
81
+ | Option | Type | Required | Environment Variable Fallback | Description |
82
+ | --------- | -------- | -------- | ----------------------------- | ----------------------------------------------------------------------- |
83
+ | `apiKey` | `string` | Yes | `INVOICE_BUILDER_API_KEY` | Your project secret API key starting with `ib_`. |
84
+ | `baseUrl` | `string` | No | `INVOICE_BUILDER_BASE_URL` | Override target server. Defaults to `https://api.invoicingbuilder.com`. |
85
+
86
+ ---
87
+
88
+ ## Getting Started
89
+
90
+ ### ESM / TypeScript
91
+
92
+ ```typescript
93
+ import { InvoiceBuilder, InvoiceTemplate } from "invoice-builder-sdk";
94
+
95
+ const client = new InvoiceBuilder(); // Implicitly pulls INVOICE_BUILDER_API_KEY from environment
96
+
97
+ async function listAllTemplates() {
98
+ const response = await client.listTemplates();
99
+ response.items.forEach((item) => {
100
+ console.log(`Template ID: ${item.id} | Name: ${item.template.name}`);
101
+ });
102
+ }
103
+ ```
104
+
105
+ ### CommonJS / JavaScript
106
+
107
+ ```javascript
108
+ const { InvoiceBuilder } = require("invoice-builder-sdk");
109
+
110
+ const client = new InvoiceBuilder({ apiKey: "ib_your_api_key" });
111
+
112
+ client.listHistory({ page: 1, limit: 10 }).then((history) => {
113
+ console.log(`Retrieved ${history.items.length} historic invoices.`);
114
+ });
115
+ ```
116
+
117
+ ---
118
+
119
+ ## API Reference
120
+
121
+ ### `listTemplates(options?: ListOptions)`
122
+
123
+ Retrieves a paginated list of invoice templates associated with your account.
124
+
125
+ - **Request Options (`ListOptions`)**:
126
+ - `page` (optional): `number` - The page index (starts at 1).
127
+ - `limit` (optional): `number` - Number of templates per page.
128
+ - **Returns**: `Promise<PaginatedResponse<InvoiceTemplateItem>>`
129
+
130
+ ```typescript
131
+ const templates = await client.listTemplates({ page: 1, limit: 5 });
132
+ ```
133
+
134
+ ### `getTemplateFields(options)`
135
+
136
+ Fetches all editable placeholder fields and dynamic components inside a specific template or history item. Great for building dynamic user forms.
137
+
138
+ - **Request Options**:
139
+ - `templateId` (optional): `string` - The template ID to retrieve fields from.
140
+ - `historyId` (optional): `string` - Retrieve fields as they were filled in a past generation.
141
+ - **Returns**: `Promise<TemplateFieldsResponse>`
142
+
143
+ ```typescript
144
+ const fieldMeta = await client.getTemplateFields({ templateId: "freelance" });
145
+ console.log(fieldMeta.fields); // Array of fields with label, type, and identifier
146
+ ```
147
+
148
+ ### `listHistory(options?: ListOptions)`
149
+
150
+ Retrieves a paginated log of all previously generated invoices and transaction logs.
151
+
152
+ - **Request Options (`ListOptions`)**:
153
+ - `page` (optional): `number`
154
+ - `limit` (optional): `number`
155
+ - **Returns**: `Promise<PaginatedResponse<HistoryItem>>`
156
+
157
+ ```typescript
158
+ const auditTrail = await client.listHistory({ page: 1, limit: 20 });
159
+ ```
160
+
161
+ ### `generatePdf(payload)`
162
+
163
+ Generates high-fidelity PDF/PNG files. Supports single generation or multi-document ZIP archival.
164
+
165
+ - **Request Payload**:
166
+ - `GeneratePdfOptions` (Object): Generates a single PDF or PNG. Returns `Buffer` (Node.js) or `ArrayBuffer` (Browser).
167
+ - `GeneratePdfOptions[]` (Array): Generates up to 2 invoices concurrently. Returns a `ZIP` buffer.
168
+ - **Returns**: `Promise<Buffer | ArrayBuffer>`
169
+
170
+ ```typescript
171
+ // Single Generation
172
+ const pdfBuffer = await client.generatePdf({
173
+ templateId: "freelance",
174
+ format: "pdf",
175
+ fields: {
176
+ invoiceNumber: "INV-0092",
177
+ billTo: "Client Co.",
178
+ table: [{ description: "Development Services", quantity: 10, rate: 100 }],
179
+ },
180
+ });
181
+ ```
182
+
183
+ ---
184
+
185
+ ## Dynamic PDF Mapping Guide
186
+
187
+ When generating documents via `generatePdf`, you pass a custom `fields` payload object mapping content to the template's placeholders. The tables below show how the API processes mapping keys and translates component types.
188
+
189
+ ### Field Mapping Rules
190
+
191
+ When matching a key inside the `fields` object, the API searches and resolves template components in this priority order:
192
+
193
+ | Priority | Match Target | Example Key | Resolution Rule |
194
+ | :------: | :----------------- | :-------------- | :-------------------------------------------------------------------------- |
195
+ | **1** | **Component ID** | `billTo-171829` | Always unique and targetable. |
196
+ | **2** | **Component Type** | `notes` | Matches the component if it is the only component of that type on the page. |
197
+ | **3** | **Custom Label** | `PO Number` | Matches the custom label text defined inside the template builder. |
198
+
199
+ ---
200
+
201
+ ### Handling Component Types
202
+
203
+ Each component type expects values to be formatted according to these rules:
204
+
205
+ | Component Type | Payload / Value Rules | Example Payload Value |
206
+ | :------------------------------- | :------------------------------------------------------------------------------------------------------------------------------------------------------ | :----------------------------------------------------- |
207
+ | **Text / Textareas** | Provide a direct string value. Use `\n` for line breaks. | `"billTo": "Client Corp\n123 Innovation Drive"` |
208
+ | **Dates** | Provide a string date value. | `"dueDate": "2026-06-30"` |
209
+ | **Logo & Signature** | Provide a direct, public URL pointing to the image. | `"logo": "https://example.com/logo.png"` |
210
+ | **Amount Paid** | Provide a string value of paid amount. | `"amountPaid": "150.00"` |
211
+ | **Taxes / Discounts / Shipping** | Overwrite values using their id, type, or label inside the fields object. | `"discount": "10"` |
212
+ | **Table** | Pass an array of objects representing the rows. The table subtotal, taxes/discounts, and final balance will be automatically calculated on the backend. | See table structure in the full payload example below. |
213
+
214
+ ---
215
+
216
+ ### Complete Multi-Template Payload Example
217
+
218
+ The following example shows a batch of two templates (which generates a ZIP archive) showing custom headers, dates, discounts, amount paid, and table rows:
219
+
220
+ ```typescript
221
+ const zipBuffer = await client.generatePdf([
222
+ {
223
+ templateId: "e7184fdc-838a-4766-b484-d7f6fcb44ebb",
224
+ format: "pdf",
225
+ fields: {
226
+ invoiceNumber: "INV-2026-001",
227
+ billTo: "Client Corp\n123 Innovation Drive\nNew York, NY",
228
+ shipTo: "Buyyer Corp\n789 Team Invoice Drive\nSan Francisco, California",
229
+ dueDate: "2026-06-30",
230
+ amountPaid: "50.00",
231
+ discount: "10",
232
+ table: [
233
+ {
234
+ description: "Software Engineering Services",
235
+ quantity: 40,
236
+ rate: 85.0,
237
+ amountPaid: 3400,
238
+ },
239
+ {
240
+ description: "Cloud Deployment Setup",
241
+ quantity: 1,
242
+ rate: 500.0,
243
+ amountPaid: 500,
244
+ },
245
+ ],
246
+ },
247
+ },
248
+ {
249
+ templateId: "e7184fdc-838a-4766-b484-d7f6fcb44ebb",
250
+ format: "pdf",
251
+ fields: {
252
+ invoiceNumber: "INV-2026-001",
253
+ billTo: "Client Corp\n123 Innovation Drive\nNew York, NY",
254
+ shipTo: "Buyyer Corp\n789 Team Invoice Drive\nSan Francisco, California",
255
+ dueDate: "2026-06-30",
256
+ amountPaid: "50.00",
257
+ discount: "10",
258
+ table: [
259
+ {
260
+ description: "Software Engineering Services1",
261
+ quantity: 40,
262
+ rate: 85.0,
263
+ amountPaid: 3400,
264
+ },
265
+ {
266
+ description: "Cloud Deployment Setup1",
267
+ quantity: 1,
268
+ rate: 500.0,
269
+ amountPaid: 500,
270
+ },
271
+ ],
272
+ },
273
+ },
274
+ ]);
275
+ ```
276
+
277
+ ---
278
+
279
+ ## Error Handling
280
+
281
+ Errors returned by the Invoice Builder API are parsed and thrown as standard JavaScript `Error` objects containing descriptive server-side messages (such as validation warnings).
282
+
283
+ ```typescript
284
+ try {
285
+ await client.generatePdf({
286
+ templateId: "non-existent",
287
+ format: "pdf",
288
+ });
289
+ } catch (error) {
290
+ if (error instanceof Error) {
291
+ console.error("API Error:", error.message);
292
+ // e.g. "Template not found" or validation array logs
293
+ }
294
+ }
295
+ ```
296
+
297
+ ---
298
+
299
+ ## Advanced Usage
300
+
301
+ ### Vercel Edge & Cloudflare Workers
302
+
303
+ Since the SDK uses native `fetch` and does not bind node-specific network or filesystem APIs, it runs natively on edge compute runtimes:
304
+
305
+ ```typescript
306
+ export const config = { runtime: "edge" };
307
+
308
+ export default async function handler(req: Request) {
309
+ const client = new InvoiceBuilder({
310
+ apiKey: process.env.INVOICE_BUILDER_API_KEY,
311
+ });
312
+ const pdfBytes = await client.generatePdf({
313
+ templateId: "freelance",
314
+ format: "pdf",
315
+ fields: { invoiceNumber: "INV-EDGE" },
316
+ });
317
+
318
+ return new Response(pdfBytes, {
319
+ headers: { "Content-Type": "application/pdf" },
320
+ });
321
+ }
322
+ ```
323
+
324
+ ### Express / Fastify PDF Streaming
325
+
326
+ Deliver generated invoice binaries directly to users as inline downloads in web frameworks:
327
+
328
+ ```javascript
329
+ const express = require("express");
330
+ const { InvoiceBuilder } = require("invoice-builder-sdk");
331
+ const app = express();
332
+
333
+ const client = new InvoiceBuilder();
334
+
335
+ app.get("/download-invoice", async (req, res) => {
336
+ try {
337
+ const pdfBuffer = await client.generatePdf({
338
+ templateId: "freelance",
339
+ format: "pdf",
340
+ fields: { invoiceNumber: "INV-123" },
341
+ });
342
+
343
+ res.setHeader("Content-Type", "application/pdf");
344
+ res.setHeader("Content-Disposition", 'attachment; filename="invoice.pdf"');
345
+ res.send(pdfBuffer);
346
+ } catch (error) {
347
+ res.status(500).send({ error: error.message });
348
+ }
349
+ });
350
+
351
+ app.listen(3000);
352
+ ```
353
+
354
+ ---
355
+
356
+ ## License
357
+
358
+ This project is licensed under the MIT License. See [LICENSE](https://github.com/invoice-builder/invoice-builder-open-api/blob/main/LICENSE) for details.
@@ -0,0 +1,142 @@
1
+ type DocFormat = 'pdf' | 'png' | 'zip';
2
+ interface ListOptions {
3
+ /**
4
+ * The page number to retrieve (starts at 1).
5
+ */
6
+ page?: number;
7
+ /**
8
+ * The number of items to return per page.
9
+ */
10
+ limit?: number;
11
+ }
12
+ interface PaginatedResponse<T> {
13
+ items: T[];
14
+ total: number;
15
+ page: number;
16
+ limit: number;
17
+ totalPages: number;
18
+ }
19
+ interface ComponentConfig {
20
+ id: string;
21
+ type: string;
22
+ properties?: Record<string, any>;
23
+ children?: ComponentConfig[];
24
+ }
25
+ interface InvoiceTemplate {
26
+ id: string;
27
+ name: string;
28
+ components: ComponentConfig[];
29
+ createdAt: string;
30
+ updatedAt: string;
31
+ isDefault?: boolean;
32
+ isDefaultCopy?: boolean;
33
+ currency?: string;
34
+ numberFormat?: string;
35
+ isWatermark?: boolean;
36
+ watermarkProperties?: Record<string, any>;
37
+ }
38
+ interface Invoice {
39
+ id: string;
40
+ date: string;
41
+ dueDate: string;
42
+ templateId: string;
43
+ templateName: string;
44
+ components: ComponentConfig[];
45
+ balanceDue: string;
46
+ currency?: string;
47
+ createdAt: string;
48
+ updatedAt: string;
49
+ numberFormat?: string;
50
+ isPaid?: boolean;
51
+ isWatermark?: boolean;
52
+ watermarkProperties?: Record<string, any>;
53
+ }
54
+ interface InvoiceTemplateItem {
55
+ id: string;
56
+ template: InvoiceTemplate;
57
+ updatedAt: string;
58
+ }
59
+ interface HistoryItem {
60
+ id: string;
61
+ invoice: Invoice;
62
+ updatedAt: string;
63
+ }
64
+ interface TemplateField {
65
+ id: string;
66
+ type: string;
67
+ label: string;
68
+ value: any;
69
+ }
70
+ interface TemplateFieldsResponse {
71
+ id: string;
72
+ source: 'history' | 'template';
73
+ updatedAt: string;
74
+ fields: TemplateField[];
75
+ }
76
+ interface GeneratePdfOptions {
77
+ /**
78
+ * Target invoice template ID.
79
+ */
80
+ templateId: string;
81
+ /**
82
+ * Format of the generated binary output.
83
+ */
84
+ format: 'pdf' | 'png';
85
+ /**
86
+ * Key-value mapping of field values to insert into the template.
87
+ * Keys can be component IDs, types, or label names.
88
+ */
89
+ fields?: Record<string, any>;
90
+ }
91
+ interface InvoiceBuilderConfig {
92
+ /**
93
+ * Your API key starting with 'ib_'.
94
+ * If not provided, falls back to the `INVOICE_BUILDER_API_KEY` environment variable.
95
+ */
96
+ apiKey?: string;
97
+ /**
98
+ * The base URL of the API.
99
+ * If not provided, falls back to the `INVOICE_BUILDER_BASE_URL` environment variable,
100
+ * or defaults to 'https://api.invoicingbuilder.com'.
101
+ */
102
+ baseUrl?: string;
103
+ }
104
+
105
+ declare class InvoiceBuilder {
106
+ private apiKey;
107
+ private baseUrl;
108
+ constructor(config?: InvoiceBuilderConfig);
109
+ /**
110
+ * Internal request helper
111
+ */
112
+ private request;
113
+ /**
114
+ * Retrieve all available templates from your account.
115
+ * Use this endpoint to browse templates and get the `templateId` required for generating invoices.
116
+ */
117
+ listTemplates(options?: ListOptions): Promise<PaginatedResponse<InvoiceTemplateItem>>;
118
+ /**
119
+ * Retrieve all editable fields and components inside a specific template or history record.
120
+ * Either templateId or historyId must be provided.
121
+ */
122
+ getTemplateFields(options: {
123
+ templateId?: string;
124
+ historyId?: string;
125
+ }): Promise<TemplateFieldsResponse>;
126
+ /**
127
+ * Retrieve the history of generated invoices and API transactions.
128
+ */
129
+ listHistory(options?: ListOptions): Promise<PaginatedResponse<HistoryItem>>;
130
+ /**
131
+ * Generates high-quality PDF/PNG documents dynamically.
132
+ *
133
+ * Accepts either a single mapping object or an array of up to 2 mapping objects.
134
+ * If a single object is provided, returns the generated document binary (PDF or PNG).
135
+ * If an array is provided, returns a ZIP file containing the generated documents.
136
+ *
137
+ * @returns Node.js Buffer (if running in Node.js) or ArrayBuffer (in browsers/non-Node environments).
138
+ */
139
+ generatePdf(payload: GeneratePdfOptions | GeneratePdfOptions[]): Promise<Buffer | ArrayBuffer>;
140
+ }
141
+
142
+ export { type ComponentConfig, type DocFormat, type GeneratePdfOptions, type HistoryItem, type Invoice, InvoiceBuilder, type InvoiceBuilderConfig, type InvoiceTemplate, type InvoiceTemplateItem, type ListOptions, type PaginatedResponse, type TemplateField, type TemplateFieldsResponse };
@@ -0,0 +1,142 @@
1
+ type DocFormat = 'pdf' | 'png' | 'zip';
2
+ interface ListOptions {
3
+ /**
4
+ * The page number to retrieve (starts at 1).
5
+ */
6
+ page?: number;
7
+ /**
8
+ * The number of items to return per page.
9
+ */
10
+ limit?: number;
11
+ }
12
+ interface PaginatedResponse<T> {
13
+ items: T[];
14
+ total: number;
15
+ page: number;
16
+ limit: number;
17
+ totalPages: number;
18
+ }
19
+ interface ComponentConfig {
20
+ id: string;
21
+ type: string;
22
+ properties?: Record<string, any>;
23
+ children?: ComponentConfig[];
24
+ }
25
+ interface InvoiceTemplate {
26
+ id: string;
27
+ name: string;
28
+ components: ComponentConfig[];
29
+ createdAt: string;
30
+ updatedAt: string;
31
+ isDefault?: boolean;
32
+ isDefaultCopy?: boolean;
33
+ currency?: string;
34
+ numberFormat?: string;
35
+ isWatermark?: boolean;
36
+ watermarkProperties?: Record<string, any>;
37
+ }
38
+ interface Invoice {
39
+ id: string;
40
+ date: string;
41
+ dueDate: string;
42
+ templateId: string;
43
+ templateName: string;
44
+ components: ComponentConfig[];
45
+ balanceDue: string;
46
+ currency?: string;
47
+ createdAt: string;
48
+ updatedAt: string;
49
+ numberFormat?: string;
50
+ isPaid?: boolean;
51
+ isWatermark?: boolean;
52
+ watermarkProperties?: Record<string, any>;
53
+ }
54
+ interface InvoiceTemplateItem {
55
+ id: string;
56
+ template: InvoiceTemplate;
57
+ updatedAt: string;
58
+ }
59
+ interface HistoryItem {
60
+ id: string;
61
+ invoice: Invoice;
62
+ updatedAt: string;
63
+ }
64
+ interface TemplateField {
65
+ id: string;
66
+ type: string;
67
+ label: string;
68
+ value: any;
69
+ }
70
+ interface TemplateFieldsResponse {
71
+ id: string;
72
+ source: 'history' | 'template';
73
+ updatedAt: string;
74
+ fields: TemplateField[];
75
+ }
76
+ interface GeneratePdfOptions {
77
+ /**
78
+ * Target invoice template ID.
79
+ */
80
+ templateId: string;
81
+ /**
82
+ * Format of the generated binary output.
83
+ */
84
+ format: 'pdf' | 'png';
85
+ /**
86
+ * Key-value mapping of field values to insert into the template.
87
+ * Keys can be component IDs, types, or label names.
88
+ */
89
+ fields?: Record<string, any>;
90
+ }
91
+ interface InvoiceBuilderConfig {
92
+ /**
93
+ * Your API key starting with 'ib_'.
94
+ * If not provided, falls back to the `INVOICE_BUILDER_API_KEY` environment variable.
95
+ */
96
+ apiKey?: string;
97
+ /**
98
+ * The base URL of the API.
99
+ * If not provided, falls back to the `INVOICE_BUILDER_BASE_URL` environment variable,
100
+ * or defaults to 'https://api.invoicingbuilder.com'.
101
+ */
102
+ baseUrl?: string;
103
+ }
104
+
105
+ declare class InvoiceBuilder {
106
+ private apiKey;
107
+ private baseUrl;
108
+ constructor(config?: InvoiceBuilderConfig);
109
+ /**
110
+ * Internal request helper
111
+ */
112
+ private request;
113
+ /**
114
+ * Retrieve all available templates from your account.
115
+ * Use this endpoint to browse templates and get the `templateId` required for generating invoices.
116
+ */
117
+ listTemplates(options?: ListOptions): Promise<PaginatedResponse<InvoiceTemplateItem>>;
118
+ /**
119
+ * Retrieve all editable fields and components inside a specific template or history record.
120
+ * Either templateId or historyId must be provided.
121
+ */
122
+ getTemplateFields(options: {
123
+ templateId?: string;
124
+ historyId?: string;
125
+ }): Promise<TemplateFieldsResponse>;
126
+ /**
127
+ * Retrieve the history of generated invoices and API transactions.
128
+ */
129
+ listHistory(options?: ListOptions): Promise<PaginatedResponse<HistoryItem>>;
130
+ /**
131
+ * Generates high-quality PDF/PNG documents dynamically.
132
+ *
133
+ * Accepts either a single mapping object or an array of up to 2 mapping objects.
134
+ * If a single object is provided, returns the generated document binary (PDF or PNG).
135
+ * If an array is provided, returns a ZIP file containing the generated documents.
136
+ *
137
+ * @returns Node.js Buffer (if running in Node.js) or ArrayBuffer (in browsers/non-Node environments).
138
+ */
139
+ generatePdf(payload: GeneratePdfOptions | GeneratePdfOptions[]): Promise<Buffer | ArrayBuffer>;
140
+ }
141
+
142
+ export { type ComponentConfig, type DocFormat, type GeneratePdfOptions, type HistoryItem, type Invoice, InvoiceBuilder, type InvoiceBuilderConfig, type InvoiceTemplate, type InvoiceTemplateItem, type ListOptions, type PaginatedResponse, type TemplateField, type TemplateFieldsResponse };
package/dist/index.js ADDED
@@ -0,0 +1,143 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+
20
+ // src/index.ts
21
+ var index_exports = {};
22
+ __export(index_exports, {
23
+ InvoiceBuilder: () => InvoiceBuilder
24
+ });
25
+ module.exports = __toCommonJS(index_exports);
26
+
27
+ // src/client/invoice-builder.ts
28
+ var InvoiceBuilder = class {
29
+ apiKey;
30
+ baseUrl;
31
+ constructor(config = {}) {
32
+ const apiKey = config.apiKey || (typeof process !== "undefined" ? process.env.INVOICE_BUILDER_API_KEY : void 0);
33
+ if (!apiKey) {
34
+ throw new Error(
35
+ "API Key is required. Provide it in the constructor or set the INVOICE_BUILDER_API_KEY environment variable."
36
+ );
37
+ }
38
+ this.apiKey = apiKey;
39
+ const baseUrl = config.baseUrl || (typeof process !== "undefined" ? process.env.INVOICE_BUILDER_BASE_URL : void 0) || "https://api.invoicingbuilder.com";
40
+ this.baseUrl = baseUrl.replace(/\/+$/, "");
41
+ }
42
+ /**
43
+ * Internal request helper
44
+ */
45
+ async request(path, options = {}) {
46
+ const url = `${this.baseUrl}${path}`;
47
+ const headers = {
48
+ "x-api-key": this.apiKey,
49
+ ...options.headers
50
+ };
51
+ const response = await fetch(url, {
52
+ ...options,
53
+ headers
54
+ });
55
+ if (!response.ok) {
56
+ let errorMessage = `Request failed with status ${response.status}`;
57
+ try {
58
+ const errorData = await response.json();
59
+ if (errorData && errorData.message) {
60
+ errorMessage = Array.isArray(errorData.message) ? errorData.message.join(", ") : errorData.message;
61
+ }
62
+ } catch (e) {
63
+ }
64
+ throw new Error(errorMessage);
65
+ }
66
+ return response;
67
+ }
68
+ /**
69
+ * Retrieve all available templates from your account.
70
+ * Use this endpoint to browse templates and get the `templateId` required for generating invoices.
71
+ */
72
+ async listTemplates(options = {}) {
73
+ const searchParams = new URLSearchParams();
74
+ if (options.page !== void 0) {
75
+ searchParams.append("page", options.page.toString());
76
+ }
77
+ if (options.limit !== void 0) {
78
+ searchParams.append("limit", options.limit.toString());
79
+ }
80
+ const queryString = searchParams.toString();
81
+ const path = `/api/v1/templates${queryString ? `?${queryString}` : ""}`;
82
+ const response = await this.request(path, { method: "GET" });
83
+ return response.json();
84
+ }
85
+ /**
86
+ * Retrieve all editable fields and components inside a specific template or history record.
87
+ * Either templateId or historyId must be provided.
88
+ */
89
+ async getTemplateFields(options) {
90
+ if (!options.templateId && !options.historyId) {
91
+ throw new Error("Either templateId or historyId must be provided.");
92
+ }
93
+ const searchParams = new URLSearchParams();
94
+ if (options.templateId) searchParams.append("templateId", options.templateId);
95
+ if (options.historyId) searchParams.append("historyId", options.historyId);
96
+ const path = `/api/v1/templates/fields?${searchParams.toString()}`;
97
+ const response = await this.request(path, { method: "GET" });
98
+ return response.json();
99
+ }
100
+ /**
101
+ * Retrieve the history of generated invoices and API transactions.
102
+ */
103
+ async listHistory(options = {}) {
104
+ const searchParams = new URLSearchParams();
105
+ if (options.page !== void 0) {
106
+ searchParams.append("page", options.page.toString());
107
+ }
108
+ if (options.limit !== void 0) {
109
+ searchParams.append("limit", options.limit.toString());
110
+ }
111
+ const queryString = searchParams.toString();
112
+ const path = `/api/v1/history${queryString ? `?${queryString}` : ""}`;
113
+ const response = await this.request(path, { method: "GET" });
114
+ return response.json();
115
+ }
116
+ /**
117
+ * Generates high-quality PDF/PNG documents dynamically.
118
+ *
119
+ * Accepts either a single mapping object or an array of up to 2 mapping objects.
120
+ * If a single object is provided, returns the generated document binary (PDF or PNG).
121
+ * If an array is provided, returns a ZIP file containing the generated documents.
122
+ *
123
+ * @returns Node.js Buffer (if running in Node.js) or ArrayBuffer (in browsers/non-Node environments).
124
+ */
125
+ async generatePdf(payload) {
126
+ if (Array.isArray(payload) && payload.length > 2) {
127
+ throw new Error("You can generate a maximum of 2 templates at a time.");
128
+ }
129
+ const response = await this.request("/api/v1/pdf/generate", {
130
+ method: "POST",
131
+ headers: {
132
+ "Content-Type": "application/json"
133
+ },
134
+ body: JSON.stringify(payload)
135
+ });
136
+ const arrayBuffer = await response.arrayBuffer();
137
+ return typeof Buffer !== "undefined" ? Buffer.from(arrayBuffer) : arrayBuffer;
138
+ }
139
+ };
140
+ // Annotate the CommonJS export names for ESM import in node:
141
+ 0 && (module.exports = {
142
+ InvoiceBuilder
143
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,116 @@
1
+ // src/client/invoice-builder.ts
2
+ var InvoiceBuilder = class {
3
+ apiKey;
4
+ baseUrl;
5
+ constructor(config = {}) {
6
+ const apiKey = config.apiKey || (typeof process !== "undefined" ? process.env.INVOICE_BUILDER_API_KEY : void 0);
7
+ if (!apiKey) {
8
+ throw new Error(
9
+ "API Key is required. Provide it in the constructor or set the INVOICE_BUILDER_API_KEY environment variable."
10
+ );
11
+ }
12
+ this.apiKey = apiKey;
13
+ const baseUrl = config.baseUrl || (typeof process !== "undefined" ? process.env.INVOICE_BUILDER_BASE_URL : void 0) || "https://api.invoicingbuilder.com";
14
+ this.baseUrl = baseUrl.replace(/\/+$/, "");
15
+ }
16
+ /**
17
+ * Internal request helper
18
+ */
19
+ async request(path, options = {}) {
20
+ const url = `${this.baseUrl}${path}`;
21
+ const headers = {
22
+ "x-api-key": this.apiKey,
23
+ ...options.headers
24
+ };
25
+ const response = await fetch(url, {
26
+ ...options,
27
+ headers
28
+ });
29
+ if (!response.ok) {
30
+ let errorMessage = `Request failed with status ${response.status}`;
31
+ try {
32
+ const errorData = await response.json();
33
+ if (errorData && errorData.message) {
34
+ errorMessage = Array.isArray(errorData.message) ? errorData.message.join(", ") : errorData.message;
35
+ }
36
+ } catch (e) {
37
+ }
38
+ throw new Error(errorMessage);
39
+ }
40
+ return response;
41
+ }
42
+ /**
43
+ * Retrieve all available templates from your account.
44
+ * Use this endpoint to browse templates and get the `templateId` required for generating invoices.
45
+ */
46
+ async listTemplates(options = {}) {
47
+ const searchParams = new URLSearchParams();
48
+ if (options.page !== void 0) {
49
+ searchParams.append("page", options.page.toString());
50
+ }
51
+ if (options.limit !== void 0) {
52
+ searchParams.append("limit", options.limit.toString());
53
+ }
54
+ const queryString = searchParams.toString();
55
+ const path = `/api/v1/templates${queryString ? `?${queryString}` : ""}`;
56
+ const response = await this.request(path, { method: "GET" });
57
+ return response.json();
58
+ }
59
+ /**
60
+ * Retrieve all editable fields and components inside a specific template or history record.
61
+ * Either templateId or historyId must be provided.
62
+ */
63
+ async getTemplateFields(options) {
64
+ if (!options.templateId && !options.historyId) {
65
+ throw new Error("Either templateId or historyId must be provided.");
66
+ }
67
+ const searchParams = new URLSearchParams();
68
+ if (options.templateId) searchParams.append("templateId", options.templateId);
69
+ if (options.historyId) searchParams.append("historyId", options.historyId);
70
+ const path = `/api/v1/templates/fields?${searchParams.toString()}`;
71
+ const response = await this.request(path, { method: "GET" });
72
+ return response.json();
73
+ }
74
+ /**
75
+ * Retrieve the history of generated invoices and API transactions.
76
+ */
77
+ async listHistory(options = {}) {
78
+ const searchParams = new URLSearchParams();
79
+ if (options.page !== void 0) {
80
+ searchParams.append("page", options.page.toString());
81
+ }
82
+ if (options.limit !== void 0) {
83
+ searchParams.append("limit", options.limit.toString());
84
+ }
85
+ const queryString = searchParams.toString();
86
+ const path = `/api/v1/history${queryString ? `?${queryString}` : ""}`;
87
+ const response = await this.request(path, { method: "GET" });
88
+ return response.json();
89
+ }
90
+ /**
91
+ * Generates high-quality PDF/PNG documents dynamically.
92
+ *
93
+ * Accepts either a single mapping object or an array of up to 2 mapping objects.
94
+ * If a single object is provided, returns the generated document binary (PDF or PNG).
95
+ * If an array is provided, returns a ZIP file containing the generated documents.
96
+ *
97
+ * @returns Node.js Buffer (if running in Node.js) or ArrayBuffer (in browsers/non-Node environments).
98
+ */
99
+ async generatePdf(payload) {
100
+ if (Array.isArray(payload) && payload.length > 2) {
101
+ throw new Error("You can generate a maximum of 2 templates at a time.");
102
+ }
103
+ const response = await this.request("/api/v1/pdf/generate", {
104
+ method: "POST",
105
+ headers: {
106
+ "Content-Type": "application/json"
107
+ },
108
+ body: JSON.stringify(payload)
109
+ });
110
+ const arrayBuffer = await response.arrayBuffer();
111
+ return typeof Buffer !== "undefined" ? Buffer.from(arrayBuffer) : arrayBuffer;
112
+ }
113
+ };
114
+ export {
115
+ InvoiceBuilder
116
+ };
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "invoice-builder-sdk",
3
+ "version": "1.0.0",
4
+ "description": "SDK for the Invoice Builder API supporting both TypeScript and JavaScript.",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./dist/index.d.ts",
11
+ "import": "./dist/index.mjs",
12
+ "require": "./dist/index.js",
13
+ "default": "./dist/index.mjs"
14
+ }
15
+ },
16
+ "files": [
17
+ "dist"
18
+ ],
19
+ "scripts": {
20
+ "build": "tsup src/index.ts --format cjs,esm --dts --clean --tsconfig tsconfig.build.json"
21
+ },
22
+ "author": "",
23
+ "license": "MIT",
24
+ "devDependencies": {
25
+ "@types/node": "^25.9.3",
26
+ "tsup": "^8.5.1",
27
+ "typescript": "^6.0.3"
28
+ }
29
+ }