@rowbind/sdk 0.0.0-stage → 0.1.0-alpha.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.
Files changed (47) hide show
  1. package/README.md +537 -2
  2. package/dist/generated/catalog.d.ts +22 -0
  3. package/dist/generated/catalog.js +7 -0
  4. package/dist/generated/http.d.ts +1740 -0
  5. package/dist/generated/http.js +843 -0
  6. package/dist/generated/raw.d.ts +39 -0
  7. package/dist/generated/raw.js +14 -0
  8. package/dist/generated/validators.d.ts +1411 -0
  9. package/dist/generated/validators.js +993 -0
  10. package/dist/http-error.d.ts +5 -0
  11. package/dist/http-error.js +2 -0
  12. package/dist/http-request.d.ts +17 -0
  13. package/dist/http-request.js +73 -0
  14. package/dist/index.d.ts +622 -0
  15. package/dist/index.js +256 -0
  16. package/dist/inputs.d.ts +145 -0
  17. package/dist/inputs.js +46 -0
  18. package/dist/ledger.d.ts +98 -0
  19. package/dist/ledger.js +218 -0
  20. package/dist/raw-invoice-query.d.ts +2 -0
  21. package/dist/raw-invoice-query.js +10 -0
  22. package/dist/transport.d.ts +344 -0
  23. package/dist/transport.js +276 -0
  24. package/dist/wire.d.ts +16 -0
  25. package/dist/wire.js +8 -0
  26. package/examples/catalog-invoice.mts +30 -0
  27. package/examples/connection-health.mts +21 -0
  28. package/examples/department-quickbooks/example.mts +12 -0
  29. package/examples/department-quickbooks/tsconfig.json +4 -0
  30. package/examples/facturar.mts +34 -0
  31. package/examples/first-customer.mts +72 -0
  32. package/examples/invoice-balances.mts +60 -0
  33. package/examples/invoice-settlement.mts +86 -0
  34. package/examples/invoice-sync.mts +46 -0
  35. package/examples/invoice-traces.mts +65 -0
  36. package/examples/invoice.mts +27 -0
  37. package/examples/mixed-providers/example.mts +12 -0
  38. package/examples/mixed-providers/tsconfig.json +4 -0
  39. package/examples/native-query.mts +28 -0
  40. package/examples/native-quickstart.mts +46 -0
  41. package/examples/observed-payments.mts +29 -0
  42. package/examples/quickstart.mts +11 -0
  43. package/examples/reimbursement-batch.mts +36 -0
  44. package/examples/resume-invoice.mts +52 -0
  45. package/examples/tsconfig.editor.json +11 -0
  46. package/examples/webhook-receiver.mts +142 -0
  47. package/package.json +78 -4
@@ -0,0 +1,46 @@
1
+ import { Rowbind } from "@rowbind/sdk"
2
+ import { openBalanceDatabase, saveInvoiceBalance } from "./invoice-balances.mts"
3
+
4
+ const usage = "Usage: bun invoice-sync.mts enable|status <connectionId> | list|pages <connectionId> [after|-] [limit]"
5
+
6
+ async function main() {
7
+ const [action, connectionId, after, limit, ...extra] = process.argv.slice(2)
8
+ if (!connectionId || extra.length || (action !== "list" && action !== "pages" && after !== undefined)) throw new Error(usage)
9
+ const rowbind = new Rowbind()
10
+ try {
11
+ if (action === "enable") return await rowbind.sync.invoices.enable(connectionId)
12
+ if (action === "status") return await rowbind.sync.invoices.status(connectionId)
13
+ const options = {
14
+ ...(after && after !== "-" && { after }), ...(limit !== undefined && { limit: Number(limit) }),
15
+ }
16
+ if (action === "pages") {
17
+ for await (const page of rowbind.invoices.iterPages(connectionId, options)) {
18
+ console.log(JSON.stringify(page))
19
+ }
20
+ return
21
+ }
22
+ if (action !== "list") throw new Error(usage)
23
+ const page = await rowbind.invoices.list(connectionId, options)
24
+ if (process.env.ROWBIND_WEBHOOK_DB) {
25
+ const db = openBalanceDatabase(process.env.ROWBIND_WEBHOOK_DB)
26
+ try {
27
+ db.transaction(() => {
28
+ for (const row of page.invoices) saveInvoiceBalance(db, connectionId, row)
29
+ })()
30
+ } finally {
31
+ db.close()
32
+ }
33
+ }
34
+ return page
35
+ } finally {
36
+ rowbind.close()
37
+ }
38
+ }
39
+
40
+ try {
41
+ const result = await main()
42
+ if (result !== undefined) console.log(JSON.stringify(result, null, 2))
43
+ } catch (error) {
44
+ console.error(error instanceof Error ? error.message : "Could not query invoice sync.")
45
+ process.exitCode = 1
46
+ }
@@ -0,0 +1,65 @@
1
+ import { Rowbind, type InvoiceRequestTrace, type InvoiceTraceLookup } from "@rowbind/sdk"
2
+
3
+ function lookupFromArgs([selector, value, connectionId, ...extra]: string[]): InvoiceTraceLookup {
4
+ const book = connectionId === undefined ? {} : { connectionId }
5
+ if (value && !extra.length) {
6
+ if (selector === "requestId") return { requestId: value, ...book }
7
+ if (selector === "reference") return { reference: value, ...book }
8
+ if (selector === "operationId") return { operationId: value, ...book }
9
+ }
10
+ throw new Error("Uso: bun invoice-traces.mts reference|requestId|operationId <valor> [connectionId]")
11
+ }
12
+
13
+ async function readRequests(rowbind: Rowbind, query: InvoiceTraceLookup) {
14
+ const requests: InvoiceRequestTrace[] = []
15
+ let after: string | null = null
16
+ do {
17
+ const page = await rowbind.invoiceTraces.list(after === null ? query : { ...query, after })
18
+ requests.push(...page.requests)
19
+ after = page.nextCursor
20
+ } while (after !== null)
21
+ return requests
22
+ }
23
+
24
+ async function readTrace(rowbind: Rowbind, query: InvoiceTraceLookup) {
25
+ let requests = await readRequests(rowbind, query)
26
+ const operationId = requests[0]?.operationId
27
+ if (query.requestId && operationId) {
28
+ const book = query.connectionId === undefined ? {} : { connectionId: query.connectionId }
29
+ requests = await readRequests(rowbind, { operationId, ...book })
30
+ }
31
+ const groups = new Map<string, InvoiceRequestTrace[]>()
32
+ const unassociatedRequests: InvoiceRequestTrace[] = []
33
+ for (const request of requests) {
34
+ if (request.operationId === null) {
35
+ unassociatedRequests.push(request)
36
+ continue
37
+ }
38
+ const group = groups.get(request.operationId)
39
+ if (group) group.push(request)
40
+ else groups.set(request.operationId, [request])
41
+ }
42
+
43
+ const operations = []
44
+ for (const [operationId, requests] of groups) {
45
+ const [operation, recovery] = await Promise.all([
46
+ rowbind.operations.retrieve(operationId),
47
+ rowbind.operations.recovery(operationId),
48
+ ])
49
+ operations.push({ operationId, requests, operation, recovery })
50
+ }
51
+ return { operations, unassociatedRequests }
52
+ }
53
+
54
+ try {
55
+ const query = lookupFromArgs(process.argv.slice(2))
56
+ const rowbind = new Rowbind()
57
+ try {
58
+ console.log(JSON.stringify(await readTrace(rowbind, query), null, 2))
59
+ } finally {
60
+ rowbind.close()
61
+ }
62
+ } catch (error) {
63
+ console.error(error instanceof Error ? error.message : "Falló la consulta de solicitudes de factura.")
64
+ process.exitCode = 1
65
+ }
@@ -0,0 +1,27 @@
1
+ import { Rowbind } from "@rowbind/sdk"
2
+ import { facturar, facturarConDepartamento } from "./facturar.mts"
3
+
4
+ const databasePath = process.env.ROWBIND_SANDBOX_DB
5
+ const rowbind = databasePath === undefined ? new Rowbind() : new Rowbind({ databasePath })
6
+ try {
7
+ console.log(databasePath === undefined ? "Destino: API HTTP de Rowbind." : "Destino: simulación SQLite.")
8
+ const [id, ...extra] = process.argv.slice(2)
9
+ if (extra.length && (extra.length !== 2 || extra[0] !== "--department" || !extra[1])) {
10
+ throw new Error("Indica un connectionId y, para NetSuite, opcionalmente --department <internalId>.")
11
+ }
12
+ if (!id) {
13
+ const connections = await rowbind.connections.list()
14
+ console.table(connections.map(({ id, provider }) => ({ id, provider })))
15
+ console.log("Vuelve a ejecutar el ejemplo pasando el ID del libro elegido.")
16
+ } else {
17
+ const connection = await rowbind.connections.retrieve(id)
18
+ if (extra.length) {
19
+ if (connection.provider !== "netsuite") throw new Error("--department requires a NetSuite connection.")
20
+ await facturarConDepartamento(rowbind, connection, extra[1]!)
21
+ } else {
22
+ await facturar(rowbind, connection.invoiceTarget)
23
+ }
24
+ }
25
+ } finally {
26
+ rowbind.close()
27
+ }
@@ -0,0 +1,12 @@
1
+ import type { Rowbind } from "@rowbind/sdk"
2
+
3
+ // Abre este archivo en el editor. Para corregir el error cambia únicamente
4
+ // demo.quickbooksDesktop.connectionId por demo.netsuite.connectionId.
5
+ export async function comprobarDestino(rowbind: Rowbind) {
6
+ const demo = await rowbind.sandbox.fixtures.retrieve("quickstart-v1")
7
+ return rowbind.netsuite.salesOrders.retrieve({
8
+ connectionId: demo.quickbooksDesktop.connectionId,
9
+ id: demo.netsuite.partialShipment.orderId,
10
+ source: "live",
11
+ })
12
+ }
@@ -0,0 +1,4 @@
1
+ {
2
+ "extends": "../tsconfig.editor.json",
3
+ "include": ["example.mts"]
4
+ }
@@ -0,0 +1,28 @@
1
+ import { Rowbind } from "@rowbind/sdk"
2
+
3
+ const [connectionId, vendorName, ...extra] = process.argv.slice(2)
4
+ if (!connectionId || extra.length || vendorName === "") {
5
+ throw new Error("Usage: bun native-query.mts <connectionId> [QuickBooks vendor name]")
6
+ }
7
+
8
+ const rb = new Rowbind()
9
+ const book = await rb.platform.connections.retrieve(connectionId)
10
+ if (book.provider === "netsuite") {
11
+ if (vendorName !== undefined) throw new Error("The vendor lookup needs a QuickBooks Desktop connection.")
12
+ // The custom field must exist in the Records Catalog visible to this role.
13
+ const result = await rb.netsuite.raw.suiteql({
14
+ connectionId: book.id,
15
+ q: "SELECT id, entityid, custentity_delivery_route FROM customer ORDER BY id",
16
+ limit: 10,
17
+ })
18
+ console.log(JSON.stringify(result))
19
+ } else {
20
+ const qbxml = vendorName === undefined
21
+ ? "<DataExtDefQueryRq><OwnerID>0</OwnerID></DataExtDefQueryRq>"
22
+ : `<VendorQueryRq><FullName>${vendorName.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;")}</FullName></VendorQueryRq>`
23
+ const result = await rb.quickbooksDesktop.raw.query({
24
+ connectionId: book.id,
25
+ qbxml,
26
+ })
27
+ console.log(JSON.stringify(result))
28
+ }
@@ -0,0 +1,46 @@
1
+ import { Rowbind } from "@rowbind/sdk"
2
+ import { facturar } from "./facturar.mts"
3
+
4
+ const rowbind = new Rowbind({ databasePath: process.env.ROWBIND_SANDBOX_DB ?? ".rowbind/sandbox.sqlite" })
5
+
6
+ try {
7
+ const demo = await rowbind.sandbox.fixtures.retrieve("quickstart-v1")
8
+ const qbd = demo.quickbooksDesktop
9
+ const ns = demo.netsuite
10
+
11
+ console.log("Rowbind · sandbox local")
12
+ await facturar(rowbind, qbd.invoiceTarget)
13
+ await facturar(rowbind, ns.invoiceTarget)
14
+
15
+ const fabricacion = await rowbind.quickbooksDesktop.buildAssemblies.create({
16
+ connectionId: qbd.connectionId,
17
+ ...qbd.kitBuild,
18
+ quantityToBuild: 3,
19
+ markPendingIfRequired: false,
20
+ idempotencyKey: "quickstart-build-001",
21
+ })
22
+ const build = await rowbind.operations.waitForVerifiedRecord(fabricacion.id)
23
+ const stock = await rowbind.quickbooksDesktop.itemSites.list({
24
+ connectionId: qbd.connectionId, inventorySiteId: build.inventorySiteId, source: "live",
25
+ })
26
+ console.log("Build en QuickBooks Enterprise:", build.id, "· Pendiente:", build.isPending)
27
+ console.table(stock.data)
28
+
29
+ const { orderId, orderLine, locationId } = ns.partialShipment
30
+ const envio = await rowbind.netsuite.salesOrders.fulfill({
31
+ connectionId: ns.connectionId,
32
+ salesOrderId: orderId,
33
+ lines: [{ orderLine, locationId, quantity: 3 }],
34
+ idempotencyKey: "quickstart-shipment-001",
35
+ })
36
+ const expedicion = await rowbind.operations.waitForVerifiedRecord(envio.id)
37
+ const pedido = await rowbind.netsuite.salesOrders.retrieve({
38
+ connectionId: ns.connectionId, id: orderId, source: "live",
39
+ })
40
+ console.log("Expedición en NetSuite:", expedicion.id, "· Pedido:", pedido.id)
41
+ console.table(pedido.lines.map(line => ({
42
+ línea: line.orderLine, expedidas: line.quantityFulfilled, pendientes: line.quantity - line.quantityFulfilled,
43
+ })))
44
+ } finally {
45
+ rowbind.close()
46
+ }
@@ -0,0 +1,29 @@
1
+ import { Rowbind } from "@rowbind/sdk"
2
+
3
+ const usage = "Usage: bun observed-payments.mts enable|status <connectionId> | list <connectionId> [after] | match <observationId> <externalInvoiceId>"
4
+
5
+ async function main() {
6
+ const [action, id, value, ...extra] = process.argv.slice(2)
7
+ if (!id || value === "" || extra.length) throw new Error(usage)
8
+ const rowbind = new Rowbind()
9
+ try {
10
+ if (action === "enable" && value === undefined) return await rowbind.sync.receivedPayments.enable(id)
11
+ if (action === "status" && value === undefined) return await rowbind.sync.receivedPayments.status(id)
12
+ if (action === "list") {
13
+ return await rowbind.observedPayments.list(id, { status: "pending_match", ...(value && { after: value }) })
14
+ }
15
+ if (action === "match" && value) {
16
+ return await rowbind.observedPayments.match(id, { externalInvoiceId: value })
17
+ }
18
+ throw new Error(usage)
19
+ } finally {
20
+ rowbind.close()
21
+ }
22
+ }
23
+
24
+ try {
25
+ console.log(JSON.stringify(await main(), null, 2))
26
+ } catch (error) {
27
+ console.error(error instanceof Error ? error.message : "Could not query or match the observed payment.")
28
+ process.exitCode = 1
29
+ }
@@ -0,0 +1,11 @@
1
+ import { Rowbind, RowbindError } from "@rowbind/sdk"
2
+
3
+ try {
4
+ const client = new Rowbind()
5
+ const connections = await client.platform.connections.list()
6
+ console.log(JSON.stringify(connections.map(({ id, provider }) => ({ id, provider })), null, 2))
7
+ } catch (error) {
8
+ if (!(error instanceof RowbindError)) throw error
9
+ console.error(error.code + ": " + error.message)
10
+ process.exitCode = 1
11
+ }
@@ -0,0 +1,36 @@
1
+ import { Rowbind } from "@rowbind/sdk"
2
+
3
+ async function main() {
4
+ const [action, id, key, ...extra] = process.argv.slice(2)
5
+ const rowbind = new Rowbind()
6
+ try {
7
+ if (action === "retrieve" && id && !key && !extra.length) return await rowbind.batches.retrieve(id)
8
+ if (action === "row" && id && key && !extra.length) {
9
+ const batch = await rowbind.batches.retrieve(id)
10
+ const row = batch.rows.find(entry => entry.key === key)
11
+ if (!row) throw new Error("La fila no existe en este lote.")
12
+ return row
13
+ }
14
+ if (action === "submit" && id && key && !extra.length) {
15
+ return await rowbind.batches.create({
16
+ connectionId: id, idempotencyKey: key, vendorRef: "employee-clearing", currency: "USD",
17
+ rows: [
18
+ { key: "expense-1", kind: "vendor_bill", amount: "40.00" },
19
+ { key: "expense-2", kind: "vendor_bill", amount: "40.00" },
20
+ { key: "expense-3", kind: "vendor_bill", amount: "40.00" },
21
+ { key: "payment", kind: "bill_payment", dependsOn: ["expense-1", "expense-2", "expense-3"] },
22
+ ],
23
+ })
24
+ }
25
+ throw new Error("Uso: bun reimbursement-batch.mts submit <connectionId> <idempotencyKey> | retrieve <batchId> | row <batchId> <rowKey>")
26
+ } finally {
27
+ rowbind.close()
28
+ }
29
+ }
30
+
31
+ try {
32
+ console.log(JSON.stringify(await main(), null, 2))
33
+ } catch (error) {
34
+ console.error(error instanceof Error ? error.message : "No se pudo consultar o enviar el lote.")
35
+ process.exitCode = 1
36
+ }
@@ -0,0 +1,52 @@
1
+ import { open, readFile } from "node:fs/promises"
2
+ import { Rowbind } from "@rowbind/sdk"
3
+ import { venta } from "./facturar.mts"
4
+
5
+ async function submit(rowbind: Rowbind, connectionId: string, path: string) {
6
+ const book = await rowbind.connections.retrieve(connectionId)
7
+ // Reserve a new file before submitting; an existing checkpoint belongs to its original sale.
8
+ const file = await open(path, "wx", 0o600)
9
+ try {
10
+ const operation = await rowbind.invoices.create({
11
+ ...venta, ...book.invoiceTarget, externalReference: "RB-1002", idempotencyKey: "resume-invoice-1002",
12
+ })
13
+ try {
14
+ await file.writeFile(operation.id + "\n")
15
+ await file.sync()
16
+ } catch (cause) {
17
+ throw new Error(`No se pudo guardar el operationId. Conserva este ID: ${operation.id}`, { cause })
18
+ }
19
+ return { operationId: operation.id }
20
+ } finally {
21
+ await file.close()
22
+ }
23
+ }
24
+
25
+ async function readOperationId(path: string) {
26
+ const id = (await readFile(path, "utf8")).trim()
27
+ if (!id) throw new Error("El fichero todavía no contiene un operationId.")
28
+ return id
29
+ }
30
+
31
+ async function main() {
32
+ const [command, target, file, ...extra] = process.argv.slice(2)
33
+ const rowbind = new Rowbind()
34
+ try {
35
+ if (command === "submit" && target && file && !extra.length) return await submit(rowbind, target, file)
36
+ if (command === "resume" && target && file === undefined) return await rowbind.operations.retrieve(await readOperationId(target))
37
+ if (command === "history" && target && !extra.length) {
38
+ if (file !== undefined && !/^[1-9]\d*$/.test(file)) throw new Error("Usa el cursor numérico devuelto por Rowbind.")
39
+ return await rowbind.operations.recovery(await readOperationId(target), file === undefined ? {} : { after: Number(file) })
40
+ }
41
+ throw new Error("Uso: bun resume-invoice.mts submit <connectionId> <fichero> | resume <fichero> | history <fichero> [cursor]")
42
+ } finally {
43
+ rowbind.close()
44
+ }
45
+ }
46
+
47
+ try {
48
+ console.log(JSON.stringify(await main(), null, 2))
49
+ } catch (error) {
50
+ console.error(error instanceof Error ? error.message : "Falló el ejemplo de facturación.")
51
+ process.exitCode = 1
52
+ }
@@ -0,0 +1,11 @@
1
+ {
2
+ "compilerOptions": {
3
+ "module": "NodeNext",
4
+ "target": "ES2022",
5
+ "strict": true,
6
+ "exactOptionalPropertyTypes": true,
7
+ "allowImportingTsExtensions": true,
8
+ "skipLibCheck": true,
9
+ "noEmit": true
10
+ }
11
+ }
@@ -0,0 +1,142 @@
1
+ import { createHmac, timingSafeEqual } from "node:crypto"
2
+ import { createServer, type IncomingMessage } from "node:http"
3
+ import type { SyncedInvoice } from "@rowbind/sdk"
4
+ import { ListSyncedInvoicesResponse } from "@rowbind/sdk/wire"
5
+ import { deleteInvoiceBalance, openBalanceDatabase, saveInvoiceBalance } from "./invoice-balances.mts"
6
+
7
+ // Run `bun webhook-receiver.mts` with ROWBIND_WEBHOOK_SECRET set to the destination's signingSecret.
8
+ // Use ROWBIND_WEBHOOK_PORT=0 for a free port and give the Worker the URL printed on startup.
9
+ const secret = process.env.ROWBIND_WEBHOOK_SECRET
10
+ if (!secret) throw new Error("Set ROWBIND_WEBHOOK_SECRET to the signing secret of the sandbox destination.")
11
+ const port = Number(process.env.ROWBIND_WEBHOOK_PORT ?? 8788)
12
+ if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error("ROWBIND_WEBHOOK_PORT must be a port between 0 and 65535.")
13
+
14
+ const dbPath = process.env.ROWBIND_WEBHOOK_DB || ".rowbind/webhook-receiver.sqlite"
15
+ const db = openBalanceDatabase(dbPath)
16
+ db.run("CREATE TABLE IF NOT EXISTS received_events (id TEXT PRIMARY KEY NOT NULL, body TEXT NOT NULL)")
17
+ db.run(`CREATE TABLE IF NOT EXISTS payment_allocations (
18
+ event_id TEXT NOT NULL UNIQUE, connection_id TEXT NOT NULL, observation_id TEXT NOT NULL,
19
+ provider TEXT NOT NULL, payment_id TEXT NOT NULL, invoice_id TEXT NOT NULL, external_invoice_id TEXT NOT NULL,
20
+ amount TEXT NOT NULL, currency TEXT NOT NULL, balance_due TEXT NOT NULL,
21
+ PRIMARY KEY (connection_id, observation_id), UNIQUE (connection_id, payment_id, invoice_id)
22
+ )`)
23
+ // The SaaS records the ERP's allocation and reported balance in the same commit as the inbox entry.
24
+ db.run(`CREATE TRIGGER IF NOT EXISTS record_payment_match AFTER INSERT ON received_events
25
+ WHEN NEW.body ->> '$.type' = 'payment.matched'
26
+ BEGIN
27
+ INSERT INTO payment_allocations (event_id, connection_id, observation_id, provider, payment_id,
28
+ invoice_id, external_invoice_id, amount, currency, balance_due)
29
+ VALUES (NEW.id, NEW.body ->> '$.data.connectionId', NEW.body ->> '$.data.observationId',
30
+ NEW.body ->> '$.data.provider', NEW.body ->> '$.data.paymentId', NEW.body ->> '$.data.invoiceId',
31
+ NEW.body ->> '$.data.externalInvoiceId', NEW.body ->> '$.data.amount', NEW.body ->> '$.data.currency',
32
+ NEW.body ->> '$.data.balanceDue')
33
+ ON CONFLICT DO NOTHING;
34
+ END`)
35
+
36
+ const route = "/webhooks/rowbind"
37
+ // Raise this explicitly for destinations importing invoices with large line arrays.
38
+ const maxBodyBytes = Number(process.env.ROWBIND_WEBHOOK_MAX_BODY_BYTES ?? 64 * 1024)
39
+ if (!Number.isSafeInteger(maxBodyBytes) || maxBodyBytes < 1) throw new Error("ROWBIND_WEBHOOK_MAX_BODY_BYTES must be a positive integer.")
40
+
41
+ function timestampInWindow(timestamp: string) {
42
+ return Math.abs(Math.floor(Date.now() / 1000) - Number(timestamp)) <= 300
43
+ }
44
+
45
+ function isObject(value: unknown): value is Record<string, unknown> {
46
+ return value !== null && typeof value === "object" && !Array.isArray(value)
47
+ }
48
+
49
+ function isPaymentMatch(event: Record<string, unknown>) {
50
+ const data = event.data
51
+ if (event.version !== 1 || typeof event.occurredAt !== "string" || !Number.isFinite(Date.parse(event.occurredAt)) ||
52
+ !isObject(data) || (data.provider !== "quickbooksDesktop" && data.provider !== "netsuite")) return false
53
+ const ids = [data.observationId, data.connectionId, data.paymentId, data.invoiceId, data.externalInvoiceId]
54
+ const decimal = /^(0|[1-9]\d*)\.\d{2}$/
55
+ return ids.every(id => typeof id === "string" && id.length > 0) && data.currency === "USD" &&
56
+ typeof data.amount === "string" && data.amount.length <= 13 && decimal.test(data.amount) && data.amount !== "0.00" &&
57
+ typeof data.balanceDue === "string" && decimal.test(data.balanceDue)
58
+ }
59
+
60
+ const invoiceRow = ListSyncedInvoicesResponse.shape.invoices.element
61
+ const deletedRow = invoiceRow.pick({ invoiceId: true, revision: true }).strict()
62
+ type InvoiceChange = (SyncedInvoice | Pick<SyncedInvoice, "invoiceId" | "revision">) & { connectionId: string }
63
+
64
+ const recordEvent = db.transaction((id: string, body: string, invoice?: InvoiceChange) => {
65
+ const { changes } = db.run("INSERT INTO received_events (id, body) VALUES (?, ?) ON CONFLICT(id) DO NOTHING", id, body)
66
+ if (!changes || !invoice) return
67
+ if ("currency" in invoice) saveInvoiceBalance(db, invoice.connectionId, invoice)
68
+ else deleteInvoiceBalance(db, invoice.connectionId, invoice.invoiceId, invoice.revision)
69
+ })
70
+
71
+ async function readBody(req: IncomingMessage): Promise<Buffer | null> {
72
+ if (Number(req.headers["content-length"]) > maxBodyBytes) return null
73
+ const chunks: Buffer[] = []
74
+ let size = 0
75
+ // Keep the socket open on early return so the sender can receive HTTP 413.
76
+ for await (const chunk of req.iterator({ destroyOnReturn: false })) {
77
+ size += chunk.length
78
+ if (size > maxBodyBytes) return null
79
+ chunks.push(chunk)
80
+ }
81
+ return Buffer.concat(chunks, size)
82
+ }
83
+
84
+ async function receive(req: IncomingMessage, signingSecret: string) {
85
+ if (req.url?.split("?")[0] !== route) return 404
86
+ if (req.method !== "POST") return 405
87
+ const id = req.headers["rowbind-event-id"]
88
+ const timestamp = req.headers["rowbind-timestamp"]
89
+ const signature = req.headers["rowbind-signature"]
90
+ if (typeof id !== "string" || !id || typeof timestamp !== "string" || !/^\d+$/.test(timestamp) ||
91
+ typeof signature !== "string" || !/^v1=[0-9a-fA-F]{64}$/.test(signature)) return 401
92
+
93
+ if (!timestampInWindow(timestamp)) return 401
94
+ const rawBody = await readBody(req)
95
+ if (rawBody === null) return 413
96
+ if (!timestampInWindow(timestamp)) return 401
97
+ const expected = createHmac("sha256", signingSecret).update(timestamp + ".").update(rawBody).digest()
98
+ if (!timingSafeEqual(expected, Buffer.from(signature.slice(3), "hex"))) return 401
99
+
100
+ let body: string
101
+ let event: unknown
102
+ try {
103
+ body = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(rawBody)
104
+ event = JSON.parse(body)
105
+ } catch {
106
+ return 400
107
+ }
108
+ if (!isObject(event) || event.id !== id) return 400
109
+ if (event.type === "invoice.created" || event.type === "invoice.updated" || event.type === "invoice.voided" || event.type === "invoice.deleted") {
110
+ if (event.version !== 1 || !isObject(event.data)) return 400
111
+ const { connectionId, provider, ...row } = event.data
112
+ if (typeof connectionId !== "string" || !connectionId || (provider !== "quickbooksDesktop" && provider !== "netsuite")) return 400
113
+ if (event.type === "invoice.voided" && row.status !== "voided") return 400
114
+ const invoice = (event.type === "invoice.deleted" ? deletedRow : invoiceRow).safeParse(row)
115
+ if (!invoice.success) return 400
116
+ recordEvent(id, body, { ...invoice.data, connectionId })
117
+ } else if (event.type === "payment.matched") {
118
+ if (!isPaymentMatch(event)) return 400
119
+ recordEvent(id, body)
120
+ } else if (event.type === "operation.verified") {
121
+ recordEvent(id, body)
122
+ } else {
123
+ return 400
124
+ }
125
+ return 204
126
+ }
127
+
128
+ const server = createServer(async (req, res) => {
129
+ try {
130
+ const status = await receive(req, secret)
131
+ if (status === 413) res.setHeader("Connection", "close")
132
+ res.writeHead(status).end()
133
+ } catch {
134
+ // Leave a failed write unacknowledged so the Worker can retry.
135
+ res.writeHead(500).end()
136
+ }
137
+ })
138
+ server.listen(port, "127.0.0.1", () => {
139
+ const address = server.address()
140
+ if (!address || typeof address === "string") throw new Error("Expected a loopback TCP listener.")
141
+ console.log(JSON.stringify({ url: `http://127.0.0.1:${address.port}${route}` }))
142
+ })
package/package.json CHANGED
@@ -1,6 +1,80 @@
1
1
  {
2
2
  "name": "@rowbind/sdk",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-alpha.1",
4
+ "type": "module",
5
+ "description": "Rowbind SDK for the local sandbox and the QuickBooks Desktop and NetSuite invoice pilot",
6
+ "engines": {
7
+ "node": ">=24"
8
+ },
9
+ "publishConfig": {
10
+ "access": "public"
11
+ },
12
+ "exports": {
13
+ ".": {
14
+ "types": "./dist/index.d.ts",
15
+ "import": "./dist/index.js"
16
+ },
17
+ "./wire": {
18
+ "types": "./dist/wire.d.ts",
19
+ "import": "./dist/wire.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist",
24
+ "README.md",
25
+ "examples/first-customer.mts",
26
+ "examples/connection-health.mts",
27
+ "examples/facturar.mts",
28
+ "examples/catalog-invoice.mts",
29
+ "examples/invoice.mts",
30
+ "examples/quickstart.mts",
31
+ "examples/native-quickstart.mts",
32
+ "examples/native-query.mts",
33
+ "examples/tsconfig.editor.json",
34
+ "examples/mixed-providers",
35
+ "examples/department-quickbooks",
36
+ "examples/resume-invoice.mts",
37
+ "examples/invoice-traces.mts",
38
+ "examples/reimbursement-batch.mts",
39
+ "examples/invoice-sync.mts",
40
+ "examples/invoice-balances.mts",
41
+ "examples/observed-payments.mts",
42
+ "examples/invoice-settlement.mts",
43
+ "examples/webhook-receiver.mts"
44
+ ],
45
+ "scripts": {
46
+ "build": "tsc -p tsconfig.build.json",
47
+ "prepack": "bun run build",
48
+ "prequickstart": "bun run build",
49
+ "quickstart": "node examples/quickstart.mts",
50
+ "preinvoice": "bun run build",
51
+ "invoice": "node --env-file-if-exists=.env.client examples/invoice.mts",
52
+ "prepilot": "bun run build",
53
+ "pilot": "node --env-file-if-exists=.env.pilot pilot/start.mts",
54
+ "preeditor:error": "bun run build",
55
+ "editor:error": "tsc -p examples/mixed-providers --pretty false",
56
+ "typecheck": "tsc -p tsconfig.json",
57
+ "test": "node --test test/*.test.mts",
58
+ "test:bun-tarball": "node scripts/test-bun-tarball.mjs",
59
+ "generate:http": "node scripts/generate-http.mjs",
60
+ "check:generated": "node scripts/generate-http.mjs --check",
61
+ "pree2e:preflight": "bun run build",
62
+ "e2e:preflight": "node --env-file-if-exists=.env.pilot pilot/preflight.mts",
63
+ "pree2e:live": "bun run build",
64
+ "e2e:payables:fixture": "node --test test/payables-acceptance.test.mts test/quickbooks-payables.test.mts test/netsuite-payables-acceptance.test.mts test/netsuite-payables.test.mts",
65
+ "e2e:payables": "node --env-file-if-exists=.env.pilot pilot/payables.mts",
66
+ "e2e:live": "node --env-file-if-exists=.env.client pilot/acceptance.mts",
67
+ "e2e:mock": "bun run build && node --test test/pilot-transport.test.mts test/pilot-service.test.mts test/netsuite-pilot.test.mts test/quickbooks-pilot.test.mts test/pilot-acceptance.test.mts",
68
+ "preeditor:department": "bun run build",
69
+ "editor:department": "tsc -p examples/department-quickbooks --pretty false"
70
+ },
71
+ "dependencies": {
72
+ "zod": "4.6.7"
73
+ },
74
+ "devDependencies": {
75
+ "@rowbind/api-contract": "0.0.0",
76
+ "@types/node": "24.19.4",
77
+ "orval": "8.50.0",
78
+ "typescript": "5.9.3"
79
+ }
80
+ }