Files
binect-js/README.md
tegwick 6b2b26f3ea Update README with installation options and AI agent prompts
- Add three installation methods (local path, npm link, copy dist)
- Fix Quick Start example to use correct API property names
- Add "Using AI Coding Agents" section with example prompts
- Reference AGENTS.md for detailed integration instructions

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-14 23:19:49 +01:00

278 lines
7.7 KiB
Markdown

# Binect-JS
A JavaScript/TypeScript wrapper for the [Binect API](https://app.binect.de/index.jsp?id=api) to send PDF documents as physical mail via Deutsche Post.
## Features
- **SDK (`@binect/js`)**: Type-safe API wrapper with domain-aligned sub-clients
- **Explorer**: Browser-based interactive tool for learning and testing the API
- **Zero Dependencies**: Uses native `fetch` API, works in browsers and Node.js >= 18
## Installation
### Option 1: Local Path Reference (Recommended)
Since this library is not yet published to npm, reference it via local path in your `package.json`:
```json
{
"dependencies": {
"@binect/js": "file:../binect-js"
}
}
```
Then run `npm install`. Adjust the path to where you cloned/placed the binect-js folder.
### Option 2: npm link
```bash
# In the binect-js directory
cd /path/to/binect-js
npm install
npm run build
npm link
# In your project directory
cd /path/to/your-project
npm link @binect/js
```
### Option 3: Copy the dist folder
1. Build the library: `cd binect-js && npm install && npm run build`
2. Copy the `dist/` folder to your project
3. Import directly: `import { BinectClient } from './dist/index.js'`
### Future: npm (not yet available)
```bash
npm install @binect/js
```
## Quick Start
```typescript
import { BinectClient, DocumentStatus, isShippable } from '@binect/js';
import { readFileSync } from 'fs';
// Create client with your Binect credentials
const client = new BinectClient({
username: 'your@email.com',
password: 'your-password',
});
// Upload a PDF document
const pdfContent = readFileSync('letter.pdf').toString('base64');
const document = await client.documents.upload({
content: pdfContent,
filename: 'letter.pdf',
color: false,
simplex: false, // false = duplex (double-sided)
envelope: 'DINLANG',
franking: 'STANDARD_FRANKING',
});
console.log('Document ID:', document.id);
console.log('Status:', document.status.code, document.status.text);
// Check if ready to send
if (isShippable(document)) {
// Send the document as physical mail
await client.sendings.send(String(document.id));
console.log('Mail dispatched!');
}
```
## SDK API Reference
The SDK provides domain-aligned sub-clients:
### Documents (`client.documents`)
- `upload(options)` - Upload a PDF document
- `list(pagination?)` - List shippable documents
- `listErrors(pagination?)` - List documents with errors
- `get(documentId)` - Get document details
- `delete(documentId)` - Delete a document
- `getPdf(documentId)` - Get PDF preview
- `getPng(documentId)` - Get PNG preview
- `getAttributes(documentId)` - Get document attributes
- `setAttributes(documentId, attributes)` - Set attributes
- `applyTransformation(documentId, transformation)` - Apply scaling/offset
- `addCoverPage(documentId, options)` - Add cover page
### Sendings (`client.sendings`)
- `announce(documentIds)` - Announce documents for delivery
- `list(pagination?)` - List all sendings
- `send(documentId)` - Trigger single document send
- `cancel(documentId)` - Cancel a sending
- `getStatus(documentIds)` - Batch status check
### Attachments (`client.attachments`)
- `upload(options)` - Upload an attachment
- `list(pagination?)` - List all attachments
- `get(attachmentId)` - Get attachment details
- `delete(attachmentId)` - Delete an attachment
- `attachToDocuments(attachmentId, documentIds)` - Attach to documents
### Accounts (`client.accounts`)
- `get()` - Get account balance/credit info
- `getPersonalData()` - Get personal data
- `updatePersonalData(data)` - Update personal data
- `getOptions()` - Get default print options
- `updateOptions(options)` - Update print options
- `getJournal(month)` - Get transaction journal
### Invoices (`client.invoices`)
- `list(pagination?)` - List all invoices
- `get(invoiceNumber)` - Get invoice details
- `getPdf(invoiceNumber)` - Download invoice PDF
## Convenience Helpers
```typescript
import {
isShippable,
isErroneous,
isSent,
isTerminal,
isCancelable,
hasErrors,
hasWarnings,
getErrors,
getStatusDescription,
waitForShippable,
fileToBase64,
} from '@binect/js';
// Status predicates
if (isShippable(document)) { /* ... */ }
if (isErroneous(document)) { /* ... */ }
// Validation helpers
const errors = getErrors(document);
if (hasWarnings(document)) {
console.log('Document has warnings');
}
// Polling (opt-in)
const readyDoc = await waitForShippable(
() => client.documents.get(docId),
{ intervalMs: 2000, maxAttempts: 30 }
);
// Base64 encoding (browser)
const file = document.querySelector('input[type="file"]').files[0];
const base64 = await fileToBase64(file);
```
## Explorer
The Binect Explorer is a browser-based interactive tool for:
- Learning the Binect API
- Testing document uploads and mail dispatch
- Managing use case profiles
Open `explorer/index.html` in a browser to use it.
## Document Status Codes
| Code | Status | Description |
|------|--------|-------------|
| 1 | IN_PREPARATION | Document is being validated |
| 2 | SHIPPABLE | Ready to send |
| 3 | PRODUCTION_QUEUE | In production queue |
| 4 | PRINTING | Currently printing |
| 5 | SENT | Mail has been sent |
| 6 | CANCELED | Sending was canceled |
| 7 | ERRONEOUS | Document has validation errors |
## Development
```bash
# Install dependencies
npm install
# Build
npm run build
# Run tests
npm test
# Run e2e tests (requires Binect credentials)
BINECT_USERNAME=your@email.com BINECT_PASSWORD=yourpass npm run test:e2e
# Type check
npm run typecheck
```
## Project Structure
```
binect-js/
├── src/ # SDK source code
│ ├── client.ts # Main BinectClient
│ ├── clients/ # Domain sub-clients
│ ├── types.ts # Type definitions
│ ├── errors.ts # Error classes
│ ├── http.ts # HTTP layer
│ └── helpers.ts # Convenience helpers
├── explorer/ # Browser-based Explorer UI
├── tests/ # Test suite
├── architecture/ # Architecture Decision Records
└── research/ # API documentation research
```
## Architecture
See [architecture/](./architecture/) for Architecture Decision Records (ADRs):
- ADR-001: SDK Architecture
- ADR-002: No External Dependencies
- ADR-003: Explorer Architecture
## API Documentation
Official Binect API documentation: https://app.binect.de/index.jsp?id=api
## Using AI Coding Agents
This library includes an `AGENTS.md` file with comprehensive instructions for AI coding assistants (Claude, Cursor, Copilot, etc.).
### Setup for AI Integration
1. Ensure the binect-js folder is accessible to your project
2. Copy `AGENTS.md` to your project root, or ensure the agent can read from binect-js
### Example Prompts
**To integrate the library into your project:**
> I want to add physical mail sending capability using the Binect API. The @binect/js library is located at `../binect-js`. Please:
> 1. Add it as a dependency to my package.json
> 2. Create a mail service that can upload PDFs and send them as letters
> 3. Include proper error handling and status checking
>
> Read AGENTS.md in the binect-js folder for API documentation.
**To send a letter:**
> Using the @binect/js library, create a function that:
> 1. Takes a PDF file path and sends it as physical mail via Binect
> 2. Polls until the document is ready, then triggers sending
> 3. Returns the document ID and final status
>
> Credentials are in environment variables BINECT_USERNAME and BINECT_PASSWORD.
**To add mail functionality to an existing service:**
> Add a `sendPhysicalMail(pdfBuffer: Buffer, options?: { color?: boolean })` method to my NotificationService class. Use the @binect/js library from `../binect-js`. Handle errors appropriately and log the document status.
## License
MIT