diff --git a/jest.config.mjs b/jest.config.mjs index e5adc4389..eaf4295b5 100644 --- a/jest.config.mjs +++ b/jest.config.mjs @@ -2,8 +2,49 @@ export default { preset: "ts-jest", testEnvironment: "node", - moduleNameMapper: { - "(.+)\.js$": "$1", - }, - workerThreads: true, -}; + projects: [ + { + displayName: "unit", + preset: "ts-jest", + testEnvironment: "node", + moduleNameMapper: { + "^(\.{1,2}/.*)\.js$": "$1", + }, + roots: ["/tests"], + testPathIgnorePatterns: ["\.browser\.(spec|test)\.[jt]sx?$", "/tests/wire/", "/tests/integration/"], + setupFilesAfterEnv: [], + }, + { + displayName: "browser", + preset: "ts-jest", + testEnvironment: "/tests/BrowserTestEnvironment.ts", + moduleNameMapper: { + "^(\.{1,2}/.*)\.js$": "$1", + }, + roots: ["/tests"], + testMatch: ["/tests/unit/**/?(*.)+(browser).(spec|test).[jt]s?(x)"], + setupFilesAfterEnv: [], + }, + { + displayName: "wire", + preset: "ts-jest", + testEnvironment: "node", + moduleNameMapper: { + "^(\.{1,2}/.*)\.js$": "$1", + }, + roots: ["/tests/wire"], + setupFilesAfterEnv: ["/tests/mock-server/setup.ts"], + }, + { + displayName: "integration", + preset: "ts-jest", + testEnvironment: "node", + moduleNameMapper: { + "^(\.{1,2}/.*)\.js$": "$1", + }, + roots: ["/tests/integration"], + }, + ], + workerThreads: false, + passWithNoTests: true, +}; \ No newline at end of file diff --git a/package.json b/package.json index e4a923579..24a919e91 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "square", "version": "43.0.1", "private": false, - "repository": "https://github.com/square/square-nodejs-sdk", + "repository": "github:square/square-nodejs-sdk", "license": "MIT", "main": "./index.js", "types": "./index.d.ts", @@ -10,32 +10,31 @@ "format": "prettier . --write --ignore-unknown", "build": "tsc", "prepack": "cp -rv dist/. .", - "test": "yarn test:unit", - "test:unit": "jest --testPathPattern=tests/unit", - "test:integration": "jest --testPathPattern=tests/integration" + "test": "jest --selectProjects unit browser wire", + "test:unit": "jest --selectProjects unit", + "test:browser": "jest --selectProjects browser", + "test:wire": "jest --selectProjects wire", + "test:integration": "jest --selectProjects integration" }, "dependencies": { - "url-join": "4.0.1", "form-data": "^4.0.0", "formdata-node": "^6.0.3", "node-fetch": "^2.7.0", - "qs": "^6.13.1", "readable-stream": "^4.5.2", - "js-base64": "3.7.7", "form-data-encoder": "^4.0.2", "square-legacy": "npm:square@^39.1.1" }, "devDependencies": { - "@types/url-join": "4.0.1", - "@types/qs": "^6.9.17", "@types/node-fetch": "^2.6.12", "@types/readable-stream": "^4.0.18", "webpack": "^5.97.1", "ts-loader": "^9.5.1", "jest": "^29.7.0", + "@jest/globals": "^29.7.0", "@types/jest": "^29.5.14", - "ts-jest": "^29.1.1", + "ts-jest": "^29.3.4", "jest-environment-jsdom": "^29.7.0", + "msw": "^2.8.4", "@types/node": "^18.19.70", "prettier": "^3.4.2", "typescript": "~5.7.2" @@ -43,8 +42,14 @@ "browser": { "fs": false, "os": false, - "path": false + "path": false, + "stream": false }, + "packageManager": "yarn@1.22.22", + "engines": { + "node": ">=18.0.0" + }, + "sideEffects": false, "description": "Use Square APIs to manage and run business including payment, customer, product, inventory, and employee management.", "author": { "name": "Square Developer Platform", diff --git a/reference.md b/reference.md index d03ead60a..cf36416ad 100644 --- a/reference.md +++ b/reference.md @@ -676,7 +676,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.bankAccounts.list(); +let page = await client.bankAccounts.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -884,7 +884,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.bookings.list(); +let page = await client.bookings.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -1574,7 +1574,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.cards.list(); +let page = await client.cards.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -2169,7 +2169,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.catalog.list(); +let page = await client.catalog.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -2564,7 +2564,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.customers.list(); +let page = await client.customers.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -2964,12 +2964,12 @@ await client.customers.bulkUpdateCustomers({ "8DDA5NZVBZFGAX0V3HPF81HHE0": { emailAddress: "New.Amelia.Earhart@example.com", note: "updated customer note", - version: 2, + version: BigInt("2"), }, N18CPRVXR5214XPBBA6BZQWF3C: { givenName: "Marie", familyName: "Curie", - version: 0, + version: BigInt("0"), }, }, }); @@ -3044,7 +3044,7 @@ profiles can take closer to one minute or longer, especially during network inci ```typescript await client.customers.search({ - limit: 2, + limit: BigInt("2"), query: { filter: { creationSource: { @@ -3202,7 +3202,7 @@ await client.customers.update({ customerId: "customer_id", emailAddress: "New.Amelia.Earhart@example.com", note: "updated customer note", - version: 2, + version: BigInt("2"), }); ``` @@ -3342,7 +3342,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.devices.list(); +let page = await client.devices.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -3481,7 +3481,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.disputes.list(); +let page = await client.disputes.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -3892,7 +3892,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.employees.list(); +let page = await client.employees.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -4270,7 +4270,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.giftCards.list(); +let page = await client.giftCards.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -5194,7 +5194,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.inventory.batchGetChanges({ +let page = await client.inventory.batchGetChanges({ catalogObjectIds: ["W62UWFY35CWMYGVWK6TWJDNI"], locationIds: ["C6W5YS5QM06F5"], types: ["PHYSICAL_COUNT"], @@ -5287,7 +5287,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.inventory.batchGetCounts({ +let page = await client.inventory.batchGetCounts({ catalogObjectIds: ["W62UWFY35CWMYGVWK6TWJDNI"], locationIds: ["59TNP9SA8VGDA"], updatedAfter: "2016-11-16T00:00:00.000Z", @@ -5566,7 +5566,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.inventory.get({ +let page = await client.inventory.get({ catalogObjectId: "catalog_object_id", }); while (page.hasNextPage()) { @@ -5654,7 +5654,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.inventory.changes({ +let page = await client.inventory.changes({ catalogObjectId: "catalog_object_id", }); while (page.hasNextPage()) { @@ -5734,7 +5734,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.invoices.list({ +let page = await client.invoices.list({ locationId: "location_id", }); while (page.hasNextPage()) { @@ -6977,7 +6977,7 @@ await client.labor.createTimecard({ wage: { title: "Barista", hourlyRate: { - amount: 1100, + amount: BigInt("1100"), currency: "USD", }, tipEligible: true, @@ -6994,7 +6994,7 @@ await client.labor.createTimecard({ ], teamMemberId: "ormj0jJJZ5OZIzxrZYJI", declaredCashTipMoney: { - amount: 500, + amount: BigInt("500"), currency: "USD", }, }, @@ -7232,7 +7232,7 @@ await client.labor.updateTimecard({ wage: { title: "Bartender", hourlyRate: { - amount: 1500, + amount: BigInt("1500"), currency: "USD", }, tipEligible: true, @@ -7252,7 +7252,7 @@ await client.labor.updateTimecard({ version: 1, teamMemberId: "ormj0jJJZ5OZIzxrZYJI", declaredCashTipMoney: { - amount: 500, + amount: BigInt("500"), currency: "USD", }, }, @@ -7703,7 +7703,7 @@ await client.locations.checkouts({ }, ], basePriceMoney: { - amount: 1500, + amount: BigInt("1500"), currency: "USD", }, }, @@ -7711,7 +7711,7 @@ await client.locations.checkouts({ name: "Slim Jeans", quantity: "1", basePriceMoney: { - amount: 2500, + amount: BigInt("2500"), currency: "USD", }, }, @@ -7719,7 +7719,7 @@ await client.locations.checkouts({ name: "Woven Sweater", quantity: "3", basePriceMoney: { - amount: 3500, + amount: BigInt("3500"), currency: "USD", }, }, @@ -7737,7 +7737,7 @@ await client.locations.checkouts({ uid: "56ae1696-z1e3-9328-af6d-f1e04d947gd4", type: "FIXED_AMOUNT", amountMoney: { - amount: 100, + amount: BigInt("100"), currency: "USD", }, scope: "LINE_ITEM", @@ -7765,7 +7765,7 @@ await client.locations.checkouts({ locationId: "057P5VYJ4A5X1", description: "Application fees", amountMoney: { - amount: 60, + amount: BigInt("60"), currency: "USD", }, }, @@ -7931,7 +7931,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.merchants.list(); +let page = await client.merchants.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -8332,7 +8332,7 @@ await client.orders.create({ name: "New York Strip Steak", quantity: "1", basePriceMoney: { - amount: 1599, + amount: BigInt("1599"), currency: "USD", }, }, @@ -8375,7 +8375,7 @@ await client.orders.create({ uid: "one-dollar-off", name: "Sale - $1.00 off", amountMoney: { - amount: 100, + amount: BigInt("100"), currency: "USD", }, scope: "LINE_ITEM", @@ -8522,7 +8522,7 @@ await client.orders.calculate({ name: "Item 1", quantity: "1", basePriceMoney: { - amount: 500, + amount: BigInt("500"), currency: "USD", }, }, @@ -8530,7 +8530,7 @@ await client.orders.calculate({ name: "Item 2", quantity: "2", basePriceMoney: { - amount: 300, + amount: BigInt("300"), currency: "USD", }, }, @@ -8863,7 +8863,7 @@ await client.orders.update({ name: "COOKIE", quantity: "2", basePriceMoney: { - amount: 200, + amount: BigInt("200"), currency: "USD", }, }, @@ -9027,7 +9027,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.payments.list(); +let page = await client.payments.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -9104,11 +9104,11 @@ await client.payments.create({ sourceId: "ccof:GaJGNaZa8x4OgDJn4GB", idempotencyKey: "7b0f3ec5-086a-4871-8f13-3c81b3875218", amountMoney: { - amount: 1000, + amount: BigInt("1000"), currency: "USD", }, appFeeMoney: { - amount: 10, + amount: BigInt("10"), currency: "USD", }, autocomplete: true, @@ -9324,11 +9324,11 @@ await client.payments.update({ paymentId: "payment_id", payment: { amountMoney: { - amount: 1000, + amount: BigInt("1000"), currency: "USD", }, tipMoney: { - amount: 100, + amount: BigInt("100"), currency: "USD", }, versionToken: "ODhwVQ35xwlzRuoZEwKXucfu7583sPTzK48c5zoGd0g6o", @@ -9541,7 +9541,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.payouts.list(); +let page = await client.payouts.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -9682,7 +9682,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.payouts.listEntries({ +let page = await client.payouts.listEntries({ payoutId: "payout_id", }); while (page.hasNextPage()) { @@ -9763,7 +9763,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.refunds.list(); +let page = await client.refunds.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -9835,11 +9835,11 @@ refund of a cash or external payment. For more information, see await client.refunds.refundPayment({ idempotencyKey: "9b7f2dcf-49da-4411-b23e-a2d6af21333a", amountMoney: { - amount: 1000, + amount: BigInt("1000"), currency: "USD", }, appFeeMoney: { - amount: 10, + amount: BigInt("10"), currency: "USD", }, paymentId: "R2B3Z8WMVt3EAmzYWLZvz7Y69EbZY", @@ -10266,7 +10266,7 @@ await client.subscriptions.create({ }, phases: [ { - ordinal: 0, + ordinal: BigInt("0"), orderTemplateId: "U2NaowWxzXwpsZU697x7ZHOAnCNZY", }, ], @@ -10827,7 +10827,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.subscriptions.listEvents({ +let page = await client.subscriptions.listEvents({ subscriptionId: "subscription_id", }); while (page.hasNextPage()) { @@ -11031,7 +11031,7 @@ await client.subscriptions.swapPlan({ newPlanVariationId: "FQ7CDXXWSLUJRPM3GFJSJGZ7", phases: [ { - ordinal: 0, + ordinal: BigInt("0"), orderTemplateId: "uhhnjH9osVv3shUADwaC0b3hNxQZY", }, ], @@ -11124,7 +11124,7 @@ await client.teamMembers.create({ { payType: "SALARY", annualRate: { - amount: 3000000, + amount: BigInt("3000000"), currency: "USD", }, weeklyHours: 40, @@ -11133,7 +11133,7 @@ await client.teamMembers.create({ { payType: "HOURLY", hourlyRate: { - amount: 2000, + amount: BigInt("2000"), currency: "USD", }, jobId: "VDNpRv8da51NU8qZFC5zDWpF", @@ -11559,7 +11559,7 @@ await client.teamMembers.update({ { payType: "SALARY", annualRate: { - amount: 3000000, + amount: BigInt("3000000"), currency: "USD", }, weeklyHours: 40, @@ -11568,7 +11568,7 @@ await client.teamMembers.update({ { payType: "HOURLY", hourlyRate: { - amount: 1200, + amount: BigInt("1200"), currency: "USD", }, jobId: "VDNpRv8da51NU8qZFC5zDWpF", @@ -12636,7 +12636,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.bookings.customAttributeDefinitions.list(); +let page = await client.bookings.customAttributeDefinitions.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -13149,7 +13149,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.bookings.customAttributes.list({ +let page = await client.bookings.customAttributes.list({ bookingId: "booking_id", }); while (page.hasNextPage()) { @@ -13439,7 +13439,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.bookings.locationProfiles.list(); +let page = await client.bookings.locationProfiles.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -13513,7 +13513,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.bookings.teamMemberProfiles.list(); +let page = await client.bookings.teamMemberProfiles.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -13655,7 +13655,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.cashDrawers.shifts.list({ +let page = await client.cashDrawers.shifts.list({ locationId: "location_id", }); while (page.hasNextPage()) { @@ -13799,7 +13799,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.cashDrawers.shifts.listEvents({ +let page = await client.cashDrawers.shifts.listEvents({ shiftId: "shift_id", locationId: "location_id", }); @@ -14234,7 +14234,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.checkout.paymentLinks.list(); +let page = await client.checkout.paymentLinks.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -14305,7 +14305,7 @@ await client.checkout.paymentLinks.create({ quickPay: { name: "Auto Detailing", priceMoney: { - amount: 10000, + amount: BigInt("10000"), currency: "USD", }, locationId: "A9Y43N9ABXZBP", @@ -14589,7 +14589,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.customers.customAttributeDefinitions.list(); +let page = await client.customers.customAttributeDefinitions.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -15074,7 +15074,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.customers.groups.list(); +let page = await client.customers.groups.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -15553,7 +15553,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.customers.segments.list(); +let page = await client.customers.segments.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -15848,7 +15848,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.customers.customAttributes.list({ +let page = await client.customers.customAttributes.list({ customerId: "customer_id", }); while (page.hasNextPage()) { @@ -16144,7 +16144,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.devices.codes.list(); +let page = await client.devices.codes.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -16356,7 +16356,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.disputes.evidence.list({ +let page = await client.disputes.evidence.list({ disputeId: "dispute_id", }); while (page.hasNextPage()) { @@ -16570,7 +16570,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.giftCards.activities.list(); +let page = await client.giftCards.activities.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -16719,7 +16719,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.labor.breakTypes.list(); +let page = await client.labor.breakTypes.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -17081,7 +17081,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.labor.employeeWages.list(); +let page = await client.labor.employeeWages.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -17240,7 +17240,7 @@ await client.labor.shifts.create({ wage: { title: "Barista", hourlyRate: { - amount: 1100, + amount: BigInt("1100"), currency: "USD", }, tipEligible: true, @@ -17257,7 +17257,7 @@ await client.labor.shifts.create({ ], teamMemberId: "ormj0jJJZ5OZIzxrZYJI", declaredCashTipMoney: { - amount: 500, + amount: BigInt("500"), currency: "USD", }, }, @@ -17495,7 +17495,7 @@ await client.labor.shifts.update({ wage: { title: "Bartender", hourlyRate: { - amount: 1500, + amount: BigInt("1500"), currency: "USD", }, tipEligible: true, @@ -17514,7 +17514,7 @@ await client.labor.shifts.update({ version: 1, teamMemberId: "ormj0jJJZ5OZIzxrZYJI", declaredCashTipMoney: { - amount: 500, + amount: BigInt("500"), currency: "USD", }, }, @@ -17654,7 +17654,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.labor.teamMemberWages.list(); +let page = await client.labor.teamMemberWages.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -17793,7 +17793,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.labor.workweekConfigs.list(); +let page = await client.labor.workweekConfigs.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -17940,7 +17940,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.locations.customAttributeDefinitions.list(); +let page = await client.locations.customAttributeDefinitions.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -18480,7 +18480,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.locations.customAttributes.list({ +let page = await client.locations.customAttributes.list({ locationId: "location_id", }); while (page.hasNextPage()) { @@ -19994,7 +19994,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.loyalty.programs.promotions.list({ +let page = await client.loyalty.programs.promotions.list({ programId: "program_id", }); while (page.hasNextPage()) { @@ -20087,7 +20087,7 @@ await client.loyalty.programs.promotions.create({ interval: "DAY", }, minimumSpendAmountMoney: { - amount: 2000, + amount: BigInt("2000"), currency: "USD", }, qualifyingCategoryIds: ["XTQPYLR3IIU9C44VRCB3XD12"], @@ -20304,7 +20304,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.merchants.customAttributeDefinitions.list(); +let page = await client.merchants.customAttributeDefinitions.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -20834,7 +20834,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.merchants.customAttributes.list({ +let page = await client.merchants.customAttributes.list({ merchantId: "merchant_id", }); while (page.hasNextPage()) { @@ -21127,7 +21127,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.orders.customAttributeDefinitions.list(); +let page = await client.orders.customAttributeDefinitions.list(); while (page.hasNextPage()) { page = page.getNextPage(); } @@ -21679,7 +21679,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.orders.customAttributes.list({ +let page = await client.orders.customAttributes.list({ orderId: "order_id", }); while (page.hasNextPage()) { @@ -22056,7 +22056,7 @@ await client.teamMembers.wageSetting.update({ jobTitle: "Manager", payType: "SALARY", annualRate: { - amount: 3000000, + amount: BigInt("3000000"), currency: "USD", }, weeklyHours: 40, @@ -22065,7 +22065,7 @@ await client.teamMembers.wageSetting.update({ jobTitle: "Cashier", payType: "HOURLY", hourlyRate: { - amount: 2000, + amount: BigInt("2000"), currency: "USD", }, }, @@ -22423,7 +22423,7 @@ await client.terminal.checkouts.create({ idempotencyKey: "28a0c3bc-7839-11ea-bc55-0242ac130003", checkout: { amountMoney: { - amount: 2610, + amount: BigInt("2610"), currency: "USD", }, referenceId: "id11572", @@ -22702,7 +22702,7 @@ await client.terminal.refunds.create({ refund: { paymentId: "5O5OvgkcNUhl7JBuINflcjKqUzXZY", amountMoney: { - amount: 111, + amount: BigInt("111"), currency: "CAD", }, reason: "Returning items", @@ -23044,7 +23044,7 @@ for await (const item of response) { } // Or you can manually iterate page-by-page -const page = await client.webhooks.subscriptions.list(); +let page = await client.webhooks.subscriptions.list(); while (page.hasNextPage()) { page = page.getNextPage(); } diff --git a/scripts/rename-to-esm-files.js b/scripts/rename-to-esm-files.js index 81dac6a75..dc1df1cbb 100644 --- a/scripts/rename-to-esm-files.js +++ b/scripts/rename-to-esm-files.js @@ -50,8 +50,16 @@ async function updateFileContents(file) { let newContent = content; // Update each extension type defined in the map for (const [oldExt, newExt] of Object.entries(extensionMap)) { - const regex = new RegExp(`(import|export)(.+from\\s+['"])(\\.\\.?\\/[^'"]+)(\\${oldExt})(['"])`, "g"); - newContent = newContent.replace(regex, `$1$2$3${newExt}$5`); + // Handle static imports/exports + const staticRegex = new RegExp(`(import|export)(.+from\\s+['"])(\\.\\.?\\/[^'"]+)(\\${oldExt})(['"])`, "g"); + newContent = newContent.replace(staticRegex, `$1$2$3${newExt}$5`); + + // Handle dynamic imports (yield import, await import, regular import()) + const dynamicRegex = new RegExp( + `(yield\\s+import|await\\s+import|import)\\s*\\(\\s*['"](\\.\\.\?\\/[^'"]+)(\\${oldExt})['"]\\s*\\)`, + "g", + ); + newContent = newContent.replace(dynamicRegex, `$1("$2${newExt}")`); } if (content !== newContent) { diff --git a/src/Client.ts b/src/Client.ts index ad3bfb92a..0226ec583 100644 --- a/src/Client.ts +++ b/src/Client.ts @@ -4,6 +4,7 @@ import * as environments from "./environments"; import * as core from "./core"; +import { mergeHeaders } from "./core/headers"; import { Mobile } from "./api/resources/mobile/client/Client"; import { OAuth } from "./api/resources/oAuth/client/Client"; import { V1Transactions } from "./api/resources/v1Transactions/client/Client"; @@ -47,6 +48,8 @@ export declare namespace SquareClient { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -60,11 +63,12 @@ export declare namespace SquareClient { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class SquareClient { + protected readonly _options: SquareClient.Options; protected _mobile: Mobile | undefined; protected _oAuth: OAuth | undefined; protected _v1Transactions: V1Transactions | undefined; @@ -100,7 +104,23 @@ export class SquareClient { protected _cashDrawers: CashDrawers | undefined; protected _webhooks: Webhooks | undefined; - constructor(protected readonly _options: SquareClient.Options = {}) {} + constructor(_options: SquareClient.Options = {}) { + this._options = { + ..._options, + headers: mergeHeaders( + { + "Square-Version": _options?.version ?? "2025-07-16", + "X-Fern-Language": "JavaScript", + "X-Fern-SDK-Name": "square", + "X-Fern-SDK-Version": "43.0.1", + "User-Agent": "square/43.0.1", + "X-Fern-Runtime": core.RUNTIME.type, + "X-Fern-Runtime-Version": core.RUNTIME.version, + }, + _options?.headers, + ), + }; + } public get mobile(): Mobile { return (this._mobile ??= new Mobile(this._options)); diff --git a/src/api/resources/applePay/client/Client.ts b/src/api/resources/applePay/client/Client.ts index 7fe8fc31a..604bc6655 100644 --- a/src/api/resources/applePay/client/Client.ts +++ b/src/api/resources/applePay/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../errors/index"; export declare namespace ApplePay { @@ -17,6 +17,8 @@ export declare namespace ApplePay { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace ApplePay { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class ApplePay { - constructor(protected readonly _options: ApplePay.Options = {}) {} + protected readonly _options: ApplePay.Options; + + constructor(_options: ApplePay.Options = {}) { + this._options = _options; + } /** * Activates a domain for use with Apple Pay on the Web and Square. A validation @@ -61,29 +67,33 @@ export class ApplePay { * domainName: "example.com" * }) */ - public async registerDomain( + public registerDomain( + request: Square.RegisterDomainRequest, + requestOptions?: ApplePay.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__registerDomain(request, requestOptions)); + } + + private async __registerDomain( request: Square.RegisterDomainRequest, requestOptions?: ApplePay.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/apple-pay/domains", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.RegisterDomainRequest.jsonOrThrow(request, { @@ -95,19 +105,23 @@ export class ApplePay { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RegisterDomainResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RegisterDomainResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -116,12 +130,14 @@ export class ApplePay { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/apple-pay/domains."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/applePay/client/index.ts b/src/api/resources/applePay/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/applePay/client/index.ts +++ b/src/api/resources/applePay/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/bankAccounts/client/Client.ts b/src/api/resources/bankAccounts/client/Client.ts index f1d305a72..ce8a0be9a 100644 --- a/src/api/resources/bankAccounts/client/Client.ts +++ b/src/api/resources/bankAccounts/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; import * as errors from "../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace BankAccounts { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace BankAccounts { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class BankAccounts { - constructor(protected readonly _options: BankAccounts.Options = {}) {} + protected readonly _options: BankAccounts.Options; + + constructor(_options: BankAccounts.Options = {}) { + this._options = _options; + } /** * Returns a list of [BankAccount](entity:BankAccount) objects linked to a Square account. @@ -50,76 +56,85 @@ export class BankAccounts { request: Square.ListBankAccountsRequest = {}, requestOptions?: BankAccounts.RequestOptions, ): Promise> { - const list = async (request: Square.ListBankAccountsRequest): Promise => { - const { cursor, limit, locationId } = request; - const _queryParams: Record = {}; - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (locationId !== undefined) { - _queryParams["location_id"] = locationId; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/bank-accounts", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListBankAccountsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.ListBankAccountsRequest, + ): Promise> => { + const { cursor, limit, locationId } = request; + const _queryParams: Record = {}; + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (locationId !== undefined) { + _queryParams["location_id"] = locationId; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/bank-accounts", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListBankAccountsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/bank-accounts."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/bank-accounts."); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.bankAccounts ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -138,50 +153,56 @@ export class BankAccounts { * v1BankAccountId: "v1_bank_account_id" * }) */ - public async getByV1Id( + public getByV1Id( + request: Square.GetByV1IdBankAccountsRequest, + requestOptions?: BankAccounts.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__getByV1Id(request, requestOptions)); + } + + private async __getByV1Id( request: Square.GetByV1IdBankAccountsRequest, requestOptions?: BankAccounts.RequestOptions, - ): Promise { + ): Promise> { const { v1BankAccountId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/bank-accounts/by-v1-id/${encodeURIComponent(v1BankAccountId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetBankAccountByV1IdResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetBankAccountByV1IdResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -190,6 +211,7 @@ export class BankAccounts { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -198,6 +220,7 @@ export class BankAccounts { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -214,50 +237,56 @@ export class BankAccounts { * bankAccountId: "bank_account_id" * }) */ - public async get( + public get( + request: Square.GetBankAccountsRequest, + requestOptions?: BankAccounts.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.GetBankAccountsRequest, requestOptions?: BankAccounts.RequestOptions, - ): Promise { + ): Promise> { const { bankAccountId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/bank-accounts/${encodeURIComponent(bankAccountId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetBankAccountResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetBankAccountResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -266,6 +295,7 @@ export class BankAccounts { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -274,6 +304,7 @@ export class BankAccounts { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/bankAccounts/client/index.ts b/src/api/resources/bankAccounts/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/bankAccounts/client/index.ts +++ b/src/api/resources/bankAccounts/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/bookings/client/Client.ts b/src/api/resources/bookings/client/Client.ts index 5e299eff9..319875f61 100644 --- a/src/api/resources/bookings/client/Client.ts +++ b/src/api/resources/bookings/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; import * as errors from "../../../../errors/index"; import { CustomAttributeDefinitions } from "../resources/customAttributeDefinitions/client/Client"; @@ -21,6 +21,8 @@ export declare namespace Bookings { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -34,17 +36,20 @@ export declare namespace Bookings { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Bookings { + protected readonly _options: Bookings.Options; protected _customAttributeDefinitions: CustomAttributeDefinitions | undefined; protected _customAttributes: CustomAttributes | undefined; protected _locationProfiles: LocationProfiles | undefined; protected _teamMemberProfiles: TeamMemberProfiles | undefined; - constructor(protected readonly _options: Bookings.Options = {}) {} + constructor(_options: Bookings.Options = {}) { + this._options = _options; + } public get customAttributeDefinitions(): CustomAttributeDefinitions { return (this._customAttributeDefinitions ??= new CustomAttributeDefinitions(this._options)); @@ -78,88 +83,95 @@ export class Bookings { request: Square.ListBookingsRequest = {}, requestOptions?: Bookings.RequestOptions, ): Promise> { - const list = async (request: Square.ListBookingsRequest): Promise => { - const { limit, cursor, customerId, teamMemberId, locationId, startAtMin, startAtMax } = request; - const _queryParams: Record = {}; - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (customerId !== undefined) { - _queryParams["customer_id"] = customerId; - } - if (teamMemberId !== undefined) { - _queryParams["team_member_id"] = teamMemberId; - } - if (locationId !== undefined) { - _queryParams["location_id"] = locationId; - } - if (startAtMin !== undefined) { - _queryParams["start_at_min"] = startAtMin; - } - if (startAtMax !== undefined) { - _queryParams["start_at_max"] = startAtMax; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/bookings", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListBookingsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], + const list = core.HttpResponsePromise.interceptFunction( + async (request: Square.ListBookingsRequest): Promise> => { + const { limit, cursor, customerId, teamMemberId, locationId, startAtMin, startAtMax } = request; + const _queryParams: Record = {}; + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (customerId !== undefined) { + _queryParams["customer_id"] = customerId; + } + if (teamMemberId !== undefined) { + _queryParams["team_member_id"] = teamMemberId; + } + if (locationId !== undefined) { + _queryParams["location_id"] = locationId; + } + if (startAtMin !== undefined) { + _queryParams["start_at_min"] = startAtMin; + } + if (startAtMax !== undefined) { + _queryParams["start_at_max"] = startAtMax; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/bookings", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListBookingsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/bookings."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/bookings."); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.bookings ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -191,29 +203,33 @@ export class Bookings { * booking: {} * }) */ - public async create( + public create( + request: Square.CreateBookingRequest, + requestOptions?: Bookings.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( request: Square.CreateBookingRequest, requestOptions?: Bookings.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/bookings", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CreateBookingRequest.jsonOrThrow(request, { @@ -225,19 +241,23 @@ export class Bookings { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateBookingResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateBookingResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -246,12 +266,14 @@ export class Bookings { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/bookings."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -274,29 +296,33 @@ export class Bookings { * } * }) */ - public async searchAvailability( + public searchAvailability( + request: Square.SearchAvailabilityRequest, + requestOptions?: Bookings.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__searchAvailability(request, requestOptions)); + } + + private async __searchAvailability( request: Square.SearchAvailabilityRequest, requestOptions?: Bookings.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/bookings/availability/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.SearchAvailabilityRequest.jsonOrThrow(request, { @@ -308,19 +334,23 @@ export class Bookings { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchAvailabilityResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchAvailabilityResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -329,6 +359,7 @@ export class Bookings { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -337,6 +368,7 @@ export class Bookings { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -355,29 +387,33 @@ export class Bookings { * bookingIds: ["booking_ids"] * }) */ - public async bulkRetrieveBookings( + public bulkRetrieveBookings( request: Square.BulkRetrieveBookingsRequest, requestOptions?: Bookings.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__bulkRetrieveBookings(request, requestOptions)); + } + + private async __bulkRetrieveBookings( + request: Square.BulkRetrieveBookingsRequest, + requestOptions?: Bookings.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/bookings/bulk-retrieve", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BulkRetrieveBookingsRequest.jsonOrThrow(request, { @@ -389,19 +425,23 @@ export class Bookings { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BulkRetrieveBookingsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BulkRetrieveBookingsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -410,12 +450,14 @@ export class Bookings { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/bookings/bulk-retrieve."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -428,48 +470,53 @@ export class Bookings { * @example * await client.bookings.getBusinessProfile() */ - public async getBusinessProfile( + public getBusinessProfile( + requestOptions?: Bookings.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__getBusinessProfile(requestOptions)); + } + + private async __getBusinessProfile( requestOptions?: Bookings.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/bookings/business-booking-profile", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetBusinessBookingProfileResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetBusinessBookingProfileResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -478,6 +525,7 @@ export class Bookings { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -486,6 +534,7 @@ export class Bookings { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -501,50 +550,56 @@ export class Bookings { * locationId: "location_id" * }) */ - public async retrieveLocationBookingProfile( + public retrieveLocationBookingProfile( + request: Square.RetrieveLocationBookingProfileRequest, + requestOptions?: Bookings.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__retrieveLocationBookingProfile(request, requestOptions)); + } + + private async __retrieveLocationBookingProfile( request: Square.RetrieveLocationBookingProfileRequest, requestOptions?: Bookings.RequestOptions, - ): Promise { + ): Promise> { const { locationId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/bookings/location-booking-profiles/${encodeURIComponent(locationId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RetrieveLocationBookingProfileResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RetrieveLocationBookingProfileResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -553,6 +608,7 @@ export class Bookings { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -561,6 +617,7 @@ export class Bookings { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -576,29 +633,35 @@ export class Bookings { * teamMemberIds: ["team_member_ids"] * }) */ - public async bulkRetrieveTeamMemberBookingProfiles( + public bulkRetrieveTeamMemberBookingProfiles( + request: Square.BulkRetrieveTeamMemberBookingProfilesRequest, + requestOptions?: Bookings.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise( + this.__bulkRetrieveTeamMemberBookingProfiles(request, requestOptions), + ); + } + + private async __bulkRetrieveTeamMemberBookingProfiles( request: Square.BulkRetrieveTeamMemberBookingProfilesRequest, requestOptions?: Bookings.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/bookings/team-member-booking-profiles/bulk-retrieve", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BulkRetrieveTeamMemberBookingProfilesRequest.jsonOrThrow(request, { @@ -610,19 +673,23 @@ export class Bookings { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BulkRetrieveTeamMemberBookingProfilesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BulkRetrieveTeamMemberBookingProfilesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -631,6 +698,7 @@ export class Bookings { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -639,6 +707,7 @@ export class Bookings { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -657,50 +726,56 @@ export class Bookings { * bookingId: "booking_id" * }) */ - public async get( + public get( + request: Square.GetBookingsRequest, + requestOptions?: Bookings.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.GetBookingsRequest, requestOptions?: Bookings.RequestOptions, - ): Promise { + ): Promise> { const { bookingId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/bookings/${encodeURIComponent(bookingId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetBookingResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetBookingResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -709,12 +784,14 @@ export class Bookings { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/bookings/{booking_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -737,30 +814,34 @@ export class Bookings { * booking: {} * }) */ - public async update( + public update( request: Square.UpdateBookingRequest, requestOptions?: Bookings.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( + request: Square.UpdateBookingRequest, + requestOptions?: Bookings.RequestOptions, + ): Promise> { const { bookingId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/bookings/${encodeURIComponent(bookingId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.UpdateBookingRequest.jsonOrThrow(_body, { @@ -772,19 +853,23 @@ export class Bookings { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateBookingResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateBookingResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -793,12 +878,14 @@ export class Bookings { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling PUT /v2/bookings/{booking_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -820,30 +907,34 @@ export class Bookings { * bookingId: "booking_id" * }) */ - public async cancel( + public cancel( request: Square.CancelBookingRequest, requestOptions?: Bookings.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__cancel(request, requestOptions)); + } + + private async __cancel( + request: Square.CancelBookingRequest, + requestOptions?: Bookings.RequestOptions, + ): Promise> { const { bookingId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/bookings/${encodeURIComponent(bookingId)}/cancel`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CancelBookingRequest.jsonOrThrow(_body, { @@ -855,19 +946,23 @@ export class Bookings { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CancelBookingResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CancelBookingResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -876,6 +971,7 @@ export class Bookings { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -884,6 +980,7 @@ export class Bookings { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/bookings/client/index.ts b/src/api/resources/bookings/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/bookings/client/index.ts +++ b/src/api/resources/bookings/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/bookings/resources/customAttributeDefinitions/client/Client.ts b/src/api/resources/bookings/resources/customAttributeDefinitions/client/Client.ts index 46ac33927..2907f2f6e 100644 --- a/src/api/resources/bookings/resources/customAttributeDefinitions/client/Client.ts +++ b/src/api/resources/bookings/resources/customAttributeDefinitions/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; import * as errors from "../../../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace CustomAttributeDefinitions { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace CustomAttributeDefinitions { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class CustomAttributeDefinitions { - constructor(protected readonly _options: CustomAttributeDefinitions.Options = {}) {} + protected readonly _options: CustomAttributeDefinitions.Options; + + constructor(_options: CustomAttributeDefinitions.Options = {}) { + this._options = _options; + } /** * Get all bookings custom attribute definitions. @@ -53,80 +59,87 @@ export class CustomAttributeDefinitions { request: Square.bookings.ListCustomAttributeDefinitionsRequest = {}, requestOptions?: CustomAttributeDefinitions.RequestOptions, ): Promise> { - const list = async ( - request: Square.bookings.ListCustomAttributeDefinitionsRequest, - ): Promise => { - const { limit, cursor } = request; - const _queryParams: Record = {}; - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/bookings/custom-attribute-definitions", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListBookingCustomAttributeDefinitionsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.bookings.ListCustomAttributeDefinitionsRequest, + ): Promise> => { + const { limit, cursor } = request; + const _queryParams: Record = {}; + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/bookings/custom-attribute-definitions", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListBookingCustomAttributeDefinitionsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/bookings/custom-attribute-definitions.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/bookings/custom-attribute-definitions.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable< Square.ListBookingCustomAttributeDefinitionsResponse, Square.CustomAttributeDefinition >({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.customAttributeDefinitions ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -151,29 +164,33 @@ export class CustomAttributeDefinitions { * customAttributeDefinition: {} * }) */ - public async create( + public create( + request: Square.bookings.CreateBookingCustomAttributeDefinitionRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( request: Square.bookings.CreateBookingCustomAttributeDefinitionRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/bookings/custom-attribute-definitions", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.bookings.CreateBookingCustomAttributeDefinitionRequest.jsonOrThrow(request, { @@ -185,19 +202,23 @@ export class CustomAttributeDefinitions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateBookingCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateBookingCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -206,6 +227,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -214,6 +236,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -232,10 +255,17 @@ export class CustomAttributeDefinitions { * key: "key" * }) */ - public async get( + public get( + request: Square.bookings.GetCustomAttributeDefinitionsRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.bookings.GetCustomAttributeDefinitionsRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): Promise> { const { key, version } = request; const _queryParams: Record = {}; if (version !== undefined) { @@ -243,45 +273,44 @@ export class CustomAttributeDefinitions { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/bookings/custom-attribute-definitions/${encodeURIComponent(key)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RetrieveBookingCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RetrieveBookingCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -290,6 +319,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -298,6 +328,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -320,30 +351,34 @@ export class CustomAttributeDefinitions { * customAttributeDefinition: {} * }) */ - public async update( + public update( + request: Square.bookings.UpdateBookingCustomAttributeDefinitionRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( request: Square.bookings.UpdateBookingCustomAttributeDefinitionRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): Promise> { const { key, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/bookings/custom-attribute-definitions/${encodeURIComponent(key)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.bookings.UpdateBookingCustomAttributeDefinitionRequest.jsonOrThrow(_body, { @@ -355,19 +390,23 @@ export class CustomAttributeDefinitions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateBookingCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateBookingCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -376,6 +415,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -384,6 +424,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -405,50 +446,56 @@ export class CustomAttributeDefinitions { * key: "key" * }) */ - public async delete( + public delete( request: Square.bookings.DeleteCustomAttributeDefinitionsRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( + request: Square.bookings.DeleteCustomAttributeDefinitionsRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): Promise> { const { key } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/bookings/custom-attribute-definitions/${encodeURIComponent(key)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteBookingCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteBookingCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -457,6 +504,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -465,6 +513,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/bookings/resources/customAttributeDefinitions/client/index.ts b/src/api/resources/bookings/resources/customAttributeDefinitions/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/bookings/resources/customAttributeDefinitions/client/index.ts +++ b/src/api/resources/bookings/resources/customAttributeDefinitions/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/bookings/resources/customAttributes/client/Client.ts b/src/api/resources/bookings/resources/customAttributes/client/Client.ts index 2bdad8288..dc78b6055 100644 --- a/src/api/resources/bookings/resources/customAttributes/client/Client.ts +++ b/src/api/resources/bookings/resources/customAttributes/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../../../errors/index"; export declare namespace CustomAttributes { @@ -17,6 +17,8 @@ export declare namespace CustomAttributes { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace CustomAttributes { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class CustomAttributes { - constructor(protected readonly _options: CustomAttributes.Options = {}) {} + protected readonly _options: CustomAttributes.Options; + + constructor(_options: CustomAttributes.Options = {}) { + this._options = _options; + } /** * Bulk deletes bookings custom attributes. @@ -59,29 +65,33 @@ export class CustomAttributes { * } * }) */ - public async batchDelete( + public batchDelete( + request: Square.bookings.BulkDeleteBookingCustomAttributesRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchDelete(request, requestOptions)); + } + + private async __batchDelete( request: Square.bookings.BulkDeleteBookingCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/bookings/custom-attributes/bulk-delete", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.bookings.BulkDeleteBookingCustomAttributesRequest.jsonOrThrow(request, { @@ -93,19 +103,23 @@ export class CustomAttributes { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BulkDeleteBookingCustomAttributesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BulkDeleteBookingCustomAttributesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -114,6 +128,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -122,6 +137,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -148,29 +164,33 @@ export class CustomAttributes { * } * }) */ - public async batchUpsert( + public batchUpsert( + request: Square.bookings.BulkUpsertBookingCustomAttributesRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchUpsert(request, requestOptions)); + } + + private async __batchUpsert( request: Square.bookings.BulkUpsertBookingCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/bookings/custom-attributes/bulk-upsert", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.bookings.BulkUpsertBookingCustomAttributesRequest.jsonOrThrow(request, { @@ -182,19 +202,23 @@ export class CustomAttributes { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BulkUpsertBookingCustomAttributesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BulkUpsertBookingCustomAttributesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -203,6 +227,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -211,6 +236,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -233,80 +259,87 @@ export class CustomAttributes { request: Square.bookings.ListCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, ): Promise> { - const list = async ( - request: Square.bookings.ListCustomAttributesRequest, - ): Promise => { - const { bookingId, limit, cursor, withDefinitions } = request; - const _queryParams: Record = {}; - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (withDefinitions !== undefined) { - _queryParams["with_definitions"] = withDefinitions?.toString() ?? null; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - `v2/bookings/${encodeURIComponent(bookingId)}/custom-attributes`, - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListBookingCustomAttributesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.bookings.ListCustomAttributesRequest, + ): Promise> => { + const { bookingId, limit, cursor, withDefinitions } = request; + const _queryParams: Record = {}; + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (withDefinitions !== undefined) { + _queryParams["with_definitions"] = withDefinitions?.toString() ?? null; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + `v2/bookings/${encodeURIComponent(bookingId)}/custom-attributes`, + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListBookingCustomAttributesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/bookings/{booking_id}/custom-attributes.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/bookings/{booking_id}/custom-attributes.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.customAttributes ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -329,10 +362,17 @@ export class CustomAttributes { * key: "key" * }) */ - public async get( + public get( + request: Square.bookings.GetCustomAttributesRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.bookings.GetCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): Promise> { const { bookingId, key, withDefinition, version } = request; const _queryParams: Record = {}; if (withDefinition !== undefined) { @@ -344,45 +384,44 @@ export class CustomAttributes { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/bookings/${encodeURIComponent(bookingId)}/custom-attributes/${encodeURIComponent(key)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RetrieveBookingCustomAttributeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RetrieveBookingCustomAttributeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -391,6 +430,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -399,6 +439,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -422,30 +463,34 @@ export class CustomAttributes { * customAttribute: {} * }) */ - public async upsert( + public upsert( + request: Square.bookings.UpsertBookingCustomAttributeRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__upsert(request, requestOptions)); + } + + private async __upsert( request: Square.bookings.UpsertBookingCustomAttributeRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): Promise> { const { bookingId, key, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/bookings/${encodeURIComponent(bookingId)}/custom-attributes/${encodeURIComponent(key)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.bookings.UpsertBookingCustomAttributeRequest.jsonOrThrow(_body, { @@ -457,19 +502,23 @@ export class CustomAttributes { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpsertBookingCustomAttributeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpsertBookingCustomAttributeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -478,6 +527,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -486,6 +536,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -508,50 +559,56 @@ export class CustomAttributes { * key: "key" * }) */ - public async delete( + public delete( request: Square.bookings.DeleteCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( + request: Square.bookings.DeleteCustomAttributesRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): Promise> { const { bookingId, key } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/bookings/${encodeURIComponent(bookingId)}/custom-attributes/${encodeURIComponent(key)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteBookingCustomAttributeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteBookingCustomAttributeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -560,6 +617,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -568,6 +626,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/bookings/resources/customAttributes/client/index.ts b/src/api/resources/bookings/resources/customAttributes/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/bookings/resources/customAttributes/client/index.ts +++ b/src/api/resources/bookings/resources/customAttributes/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/bookings/resources/locationProfiles/client/Client.ts b/src/api/resources/bookings/resources/locationProfiles/client/Client.ts index 4ec1fc95d..6b42606c4 100644 --- a/src/api/resources/bookings/resources/locationProfiles/client/Client.ts +++ b/src/api/resources/bookings/resources/locationProfiles/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; import * as errors from "../../../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace LocationProfiles { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace LocationProfiles { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class LocationProfiles { - constructor(protected readonly _options: LocationProfiles.Options = {}) {} + protected readonly _options: LocationProfiles.Options; + + constructor(_options: LocationProfiles.Options = {}) { + this._options = _options; + } /** * Lists location booking profiles of a seller. @@ -50,77 +56,84 @@ export class LocationProfiles { request: Square.bookings.ListLocationProfilesRequest = {}, requestOptions?: LocationProfiles.RequestOptions, ): Promise> { - const list = async ( - request: Square.bookings.ListLocationProfilesRequest, - ): Promise => { - const { limit, cursor } = request; - const _queryParams: Record = {}; - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/bookings/location-booking-profiles", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListLocationBookingProfilesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.bookings.ListLocationProfilesRequest, + ): Promise> => { + const { limit, cursor } = request; + const _queryParams: Record = {}; + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/bookings/location-booking-profiles", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListLocationBookingProfilesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/bookings/location-booking-profiles.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, - }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/bookings/location-booking-profiles.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.locationBookingProfiles ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); diff --git a/src/api/resources/bookings/resources/locationProfiles/client/index.ts b/src/api/resources/bookings/resources/locationProfiles/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/bookings/resources/locationProfiles/client/index.ts +++ b/src/api/resources/bookings/resources/locationProfiles/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/bookings/resources/teamMemberProfiles/client/Client.ts b/src/api/resources/bookings/resources/teamMemberProfiles/client/Client.ts index b3dcd8fc4..685eea420 100644 --- a/src/api/resources/bookings/resources/teamMemberProfiles/client/Client.ts +++ b/src/api/resources/bookings/resources/teamMemberProfiles/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; import * as errors from "../../../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace TeamMemberProfiles { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace TeamMemberProfiles { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class TeamMemberProfiles { - constructor(protected readonly _options: TeamMemberProfiles.Options = {}) {} + protected readonly _options: TeamMemberProfiles.Options; + + constructor(_options: TeamMemberProfiles.Options = {}) { + this._options = _options; + } /** * Lists booking profiles for team members. @@ -50,83 +56,90 @@ export class TeamMemberProfiles { request: Square.bookings.ListTeamMemberProfilesRequest = {}, requestOptions?: TeamMemberProfiles.RequestOptions, ): Promise> { - const list = async ( - request: Square.bookings.ListTeamMemberProfilesRequest, - ): Promise => { - const { bookableOnly, limit, cursor, locationId } = request; - const _queryParams: Record = {}; - if (bookableOnly !== undefined) { - _queryParams["bookable_only"] = bookableOnly?.toString() ?? null; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (locationId !== undefined) { - _queryParams["location_id"] = locationId; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/bookings/team-member-booking-profiles", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListTeamMemberBookingProfilesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.bookings.ListTeamMemberProfilesRequest, + ): Promise> => { + const { bookableOnly, limit, cursor, locationId } = request; + const _queryParams: Record = {}; + if (bookableOnly !== undefined) { + _queryParams["bookable_only"] = bookableOnly?.toString() ?? null; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (locationId !== undefined) { + _queryParams["location_id"] = locationId; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/bookings/team-member-booking-profiles", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListTeamMemberBookingProfilesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/bookings/team-member-booking-profiles.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/bookings/team-member-booking-profiles.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.teamMemberBookingProfiles ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -145,50 +158,56 @@ export class TeamMemberProfiles { * teamMemberId: "team_member_id" * }) */ - public async get( + public get( request: Square.bookings.GetTeamMemberProfilesRequest, requestOptions?: TeamMemberProfiles.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.bookings.GetTeamMemberProfilesRequest, + requestOptions?: TeamMemberProfiles.RequestOptions, + ): Promise> { const { teamMemberId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/bookings/team-member-booking-profiles/${encodeURIComponent(teamMemberId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetTeamMemberBookingProfileResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetTeamMemberBookingProfileResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -197,6 +216,7 @@ export class TeamMemberProfiles { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -205,6 +225,7 @@ export class TeamMemberProfiles { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/bookings/resources/teamMemberProfiles/client/index.ts b/src/api/resources/bookings/resources/teamMemberProfiles/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/bookings/resources/teamMemberProfiles/client/index.ts +++ b/src/api/resources/bookings/resources/teamMemberProfiles/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/cards/client/Client.ts b/src/api/resources/cards/client/Client.ts index f9f7ac900..2f37c22c9 100644 --- a/src/api/resources/cards/client/Client.ts +++ b/src/api/resources/cards/client/Client.ts @@ -6,7 +6,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as errors from "../../../../errors/index"; export declare namespace Cards { @@ -17,6 +17,8 @@ export declare namespace Cards { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Cards { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Cards { - constructor(protected readonly _options: Cards.Options = {}) {} + protected readonly _options: Cards.Options; + + constructor(_options: Cards.Options = {}) { + this._options = _options; + } /** * Retrieves a list of cards owned by the account making the request. @@ -51,85 +57,92 @@ export class Cards { request: Square.ListCardsRequest = {}, requestOptions?: Cards.RequestOptions, ): Promise> { - const list = async (request: Square.ListCardsRequest): Promise => { - const { cursor, customerId, includeDisabled, referenceId, sortOrder } = request; - const _queryParams: Record = {}; - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (customerId !== undefined) { - _queryParams["customer_id"] = customerId; - } - if (includeDisabled !== undefined) { - _queryParams["include_disabled"] = includeDisabled?.toString() ?? null; - } - if (referenceId !== undefined) { - _queryParams["reference_id"] = referenceId; - } - if (sortOrder !== undefined) { - _queryParams["sort_order"] = serializers.SortOrder.jsonOrThrow(sortOrder, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/cards", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListCardsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async (request: Square.ListCardsRequest): Promise> => { + const { cursor, customerId, includeDisabled, referenceId, sortOrder } = request; + const _queryParams: Record = {}; + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (customerId !== undefined) { + _queryParams["customer_id"] = customerId; + } + if (includeDisabled !== undefined) { + _queryParams["include_disabled"] = includeDisabled?.toString() ?? null; + } + if (referenceId !== undefined) { + _queryParams["reference_id"] = referenceId; + } + if (sortOrder !== undefined) { + _queryParams["sort_order"] = serializers.SortOrder.jsonOrThrow(sortOrder, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/cards", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListCardsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/cards."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/cards."); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.cards ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -162,29 +175,33 @@ export class Cards { * } * }) */ - public async create( + public create( + request: Square.CreateCardRequest, + requestOptions?: Cards.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( request: Square.CreateCardRequest, requestOptions?: Cards.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/cards", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CreateCardRequest.jsonOrThrow(request, { @@ -196,19 +213,23 @@ export class Cards { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateCardResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateCardResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -217,12 +238,14 @@ export class Cards { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/cards."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -238,50 +261,56 @@ export class Cards { * cardId: "card_id" * }) */ - public async get( + public get( request: Square.GetCardsRequest, requestOptions?: Cards.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.GetCardsRequest, + requestOptions?: Cards.RequestOptions, + ): Promise> { const { cardId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/cards/${encodeURIComponent(cardId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetCardResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetCardResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -290,12 +319,14 @@ export class Cards { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/cards/{card_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -312,50 +343,56 @@ export class Cards { * cardId: "card_id" * }) */ - public async disable( + public disable( request: Square.DisableCardsRequest, requestOptions?: Cards.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__disable(request, requestOptions)); + } + + private async __disable( + request: Square.DisableCardsRequest, + requestOptions?: Cards.RequestOptions, + ): Promise> { const { cardId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/cards/${encodeURIComponent(cardId)}/disable`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DisableCardResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DisableCardResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -364,12 +401,14 @@ export class Cards { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/cards/{card_id}/disable."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/cards/client/index.ts b/src/api/resources/cards/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/cards/client/index.ts +++ b/src/api/resources/cards/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/cashDrawers/client/Client.ts b/src/api/resources/cashDrawers/client/Client.ts index a549c4509..16f60e97e 100644 --- a/src/api/resources/cashDrawers/client/Client.ts +++ b/src/api/resources/cashDrawers/client/Client.ts @@ -14,27 +14,19 @@ export declare namespace CashDrawers { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } - - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Override the Square-Version header */ - version?: "2025-07-16"; - /** Additional headers to include in the request. */ - headers?: Record; - } } export class CashDrawers { + protected readonly _options: CashDrawers.Options; protected _shifts: Shifts | undefined; - constructor(protected readonly _options: CashDrawers.Options = {}) {} + constructor(_options: CashDrawers.Options = {}) { + this._options = _options; + } public get shifts(): Shifts { return (this._shifts ??= new Shifts(this._options)); diff --git a/src/api/resources/cashDrawers/resources/shifts/client/Client.ts b/src/api/resources/cashDrawers/resources/shifts/client/Client.ts index af2d438b4..8d5672204 100644 --- a/src/api/resources/cashDrawers/resources/shifts/client/Client.ts +++ b/src/api/resources/cashDrawers/resources/shifts/client/Client.ts @@ -6,7 +6,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as errors from "../../../../../../errors/index"; export declare namespace Shifts { @@ -17,6 +17,8 @@ export declare namespace Shifts { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Shifts { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Shifts { - constructor(protected readonly _options: Shifts.Options = {}) {} + protected readonly _options: Shifts.Options; + + constructor(_options: Shifts.Options = {}) { + this._options = _options; + } /** * Provides the details for all of the cash drawer shifts for a location @@ -53,88 +59,97 @@ export class Shifts { request: Square.cashDrawers.ListShiftsRequest, requestOptions?: Shifts.RequestOptions, ): Promise> { - const list = async ( - request: Square.cashDrawers.ListShiftsRequest, - ): Promise => { - const { locationId, sortOrder, beginTime, endTime, limit, cursor } = request; - const _queryParams: Record = {}; - _queryParams["location_id"] = locationId; - if (sortOrder !== undefined) { - _queryParams["sort_order"] = serializers.SortOrder.jsonOrThrow(sortOrder, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - if (beginTime !== undefined) { - _queryParams["begin_time"] = beginTime; - } - if (endTime !== undefined) { - _queryParams["end_time"] = endTime; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/cash-drawers/shifts", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListCashDrawerShiftsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.cashDrawers.ListShiftsRequest, + ): Promise> => { + const { locationId, sortOrder, beginTime, endTime, limit, cursor } = request; + const _queryParams: Record = {}; + _queryParams["location_id"] = locationId; + if (sortOrder !== undefined) { + _queryParams["sort_order"] = serializers.SortOrder.jsonOrThrow(sortOrder, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + if (beginTime !== undefined) { + _queryParams["begin_time"] = beginTime; + } + if (endTime !== undefined) { + _queryParams["end_time"] = endTime; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/cash-drawers/shifts", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListCashDrawerShiftsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/cash-drawers/shifts."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, - }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/cash-drawers/shifts.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.cashDrawerShifts ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -155,53 +170,59 @@ export class Shifts { * locationId: "location_id" * }) */ - public async get( + public get( request: Square.cashDrawers.GetShiftsRequest, requestOptions?: Shifts.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.cashDrawers.GetShiftsRequest, + requestOptions?: Shifts.RequestOptions, + ): Promise> { const { shiftId, locationId } = request; const _queryParams: Record = {}; _queryParams["location_id"] = locationId; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/cash-drawers/shifts/${encodeURIComponent(shiftId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetCashDrawerShiftResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetCashDrawerShiftResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -210,6 +231,7 @@ export class Shifts { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -218,6 +240,7 @@ export class Shifts { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -238,78 +261,85 @@ export class Shifts { request: Square.cashDrawers.ListEventsShiftsRequest, requestOptions?: Shifts.RequestOptions, ): Promise> { - const list = async ( - request: Square.cashDrawers.ListEventsShiftsRequest, - ): Promise => { - const { shiftId, locationId, limit, cursor } = request; - const _queryParams: Record = {}; - _queryParams["location_id"] = locationId; - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - `v2/cash-drawers/shifts/${encodeURIComponent(shiftId)}/events`, - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListCashDrawerShiftEventsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.cashDrawers.ListEventsShiftsRequest, + ): Promise> => { + const { shiftId, locationId, limit, cursor } = request; + const _queryParams: Record = {}; + _queryParams["location_id"] = locationId; + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + `v2/cash-drawers/shifts/${encodeURIComponent(shiftId)}/events`, + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListCashDrawerShiftEventsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/cash-drawers/shifts/{shift_id}/events.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, - }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/cash-drawers/shifts/{shift_id}/events.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.cashDrawerShiftEvents ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); diff --git a/src/api/resources/cashDrawers/resources/shifts/client/index.ts b/src/api/resources/cashDrawers/resources/shifts/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/cashDrawers/resources/shifts/client/index.ts +++ b/src/api/resources/cashDrawers/resources/shifts/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/catalog/client/Client.ts b/src/api/resources/catalog/client/Client.ts index 986b1e086..a90f7b306 100644 --- a/src/api/resources/catalog/client/Client.ts +++ b/src/api/resources/catalog/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../errors/index"; import { Images } from "../resources/images/client/Client"; import { Object_ } from "../resources/object/client/Client"; @@ -19,6 +19,8 @@ export declare namespace Catalog { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -32,15 +34,18 @@ export declare namespace Catalog { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Catalog { + protected readonly _options: Catalog.Options; protected _images: Images | undefined; protected _object: Object_ | undefined; - constructor(protected readonly _options: Catalog.Options = {}) {} + constructor(_options: Catalog.Options = {}) { + this._options = _options; + } public get images(): Images { return (this._images ??= new Images(this._options)); @@ -74,29 +79,33 @@ export class Catalog { * objectIds: ["W62UWFY35CWMYGVWK6TWJDNI", "AA27W3M2GGTF3H6AVPNB77CK"] * }) */ - public async batchDelete( + public batchDelete( + request: Square.BatchDeleteCatalogObjectsRequest, + requestOptions?: Catalog.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchDelete(request, requestOptions)); + } + + private async __batchDelete( request: Square.BatchDeleteCatalogObjectsRequest, requestOptions?: Catalog.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/catalog/batch-delete", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BatchDeleteCatalogObjectsRequest.jsonOrThrow(request, { @@ -108,19 +117,23 @@ export class Catalog { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BatchDeleteCatalogObjectsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BatchDeleteCatalogObjectsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -129,12 +142,14 @@ export class Catalog { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/catalog/batch-delete."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -156,29 +171,33 @@ export class Catalog { * includeRelatedObjects: true * }) */ - public async batchGet( + public batchGet( + request: Square.BatchGetCatalogObjectsRequest, + requestOptions?: Catalog.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchGet(request, requestOptions)); + } + + private async __batchGet( request: Square.BatchGetCatalogObjectsRequest, requestOptions?: Catalog.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/catalog/batch-retrieve", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BatchGetCatalogObjectsRequest.jsonOrThrow(request, { @@ -190,19 +209,23 @@ export class Catalog { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BatchGetCatalogObjectsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BatchGetCatalogObjectsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -211,12 +234,14 @@ export class Catalog { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/catalog/batch-retrieve."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -259,29 +284,33 @@ export class Catalog { * }] * }) */ - public async batchUpsert( + public batchUpsert( + request: Square.BatchUpsertCatalogObjectsRequest, + requestOptions?: Catalog.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchUpsert(request, requestOptions)); + } + + private async __batchUpsert( request: Square.BatchUpsertCatalogObjectsRequest, requestOptions?: Catalog.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/catalog/batch-upsert", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BatchUpsertCatalogObjectsRequest.jsonOrThrow(request, { @@ -293,19 +322,23 @@ export class Catalog { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BatchUpsertCatalogObjectsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BatchUpsertCatalogObjectsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -314,12 +347,14 @@ export class Catalog { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/catalog/batch-upsert."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -333,46 +368,51 @@ export class Catalog { * @example * await client.catalog.info() */ - public async info(requestOptions?: Catalog.RequestOptions): Promise { + public info(requestOptions?: Catalog.RequestOptions): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__info(requestOptions)); + } + + private async __info( + requestOptions?: Catalog.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/catalog/info", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CatalogInfoResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CatalogInfoResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -381,12 +421,14 @@ export class Catalog { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/catalog/info."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -411,76 +453,83 @@ export class Catalog { request: Square.ListCatalogRequest = {}, requestOptions?: Catalog.RequestOptions, ): Promise> { - const list = async (request: Square.ListCatalogRequest): Promise => { - const { cursor, types, catalogVersion } = request; - const _queryParams: Record = {}; - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (types !== undefined) { - _queryParams["types"] = types; - } - if (catalogVersion !== undefined) { - _queryParams["catalog_version"] = catalogVersion?.toString() ?? null; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/catalog/list", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListCatalogResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async (request: Square.ListCatalogRequest): Promise> => { + const { cursor, types, catalogVersion } = request; + const _queryParams: Record = {}; + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (types !== undefined) { + _queryParams["types"] = types; + } + if (catalogVersion !== undefined) { + _queryParams["catalog_version"] = catalogVersion?.toString() ?? null; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/catalog/list", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListCatalogResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/catalog/list."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, - }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/catalog/list."); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.objects ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -515,29 +564,33 @@ export class Catalog { * limit: 100 * }) */ - public async search( + public search( request: Square.SearchCatalogObjectsRequest = {}, requestOptions?: Catalog.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__search(request, requestOptions)); + } + + private async __search( + request: Square.SearchCatalogObjectsRequest = {}, + requestOptions?: Catalog.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/catalog/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.SearchCatalogObjectsRequest.jsonOrThrow(request, { @@ -549,19 +602,23 @@ export class Catalog { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchCatalogObjectsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchCatalogObjectsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -570,12 +627,14 @@ export class Catalog { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/catalog/search."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -621,29 +680,33 @@ export class Catalog { * }] * }) */ - public async searchItems( + public searchItems( request: Square.SearchCatalogItemsRequest = {}, requestOptions?: Catalog.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__searchItems(request, requestOptions)); + } + + private async __searchItems( + request: Square.SearchCatalogItemsRequest = {}, + requestOptions?: Catalog.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/catalog/search-catalog-items", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.SearchCatalogItemsRequest.jsonOrThrow(request, { @@ -655,19 +718,23 @@ export class Catalog { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchCatalogItemsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchCatalogItemsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -676,6 +743,7 @@ export class Catalog { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -684,6 +752,7 @@ export class Catalog { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -703,29 +772,33 @@ export class Catalog { * modifierListsToDisable: ["7WRC16CJZDVLSNDQ35PP6YAD"] * }) */ - public async updateItemModifierLists( + public updateItemModifierLists( + request: Square.UpdateItemModifierListsRequest, + requestOptions?: Catalog.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__updateItemModifierLists(request, requestOptions)); + } + + private async __updateItemModifierLists( request: Square.UpdateItemModifierListsRequest, requestOptions?: Catalog.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/catalog/update-item-modifier-lists", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.UpdateItemModifierListsRequest.jsonOrThrow(request, { @@ -737,19 +810,23 @@ export class Catalog { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateItemModifierListsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateItemModifierListsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -758,6 +835,7 @@ export class Catalog { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -766,6 +844,7 @@ export class Catalog { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -785,29 +864,33 @@ export class Catalog { * taxesToDisable: ["AQCEGCEBBQONINDOHRGZISEX"] * }) */ - public async updateItemTaxes( + public updateItemTaxes( request: Square.UpdateItemTaxesRequest, requestOptions?: Catalog.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__updateItemTaxes(request, requestOptions)); + } + + private async __updateItemTaxes( + request: Square.UpdateItemTaxesRequest, + requestOptions?: Catalog.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/catalog/update-item-taxes", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.UpdateItemTaxesRequest.jsonOrThrow(request, { @@ -819,19 +902,23 @@ export class Catalog { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateItemTaxesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateItemTaxesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -840,6 +927,7 @@ export class Catalog { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -848,6 +936,7 @@ export class Catalog { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/catalog/client/index.ts b/src/api/resources/catalog/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/catalog/client/index.ts +++ b/src/api/resources/catalog/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/catalog/resources/images/client/Client.ts b/src/api/resources/catalog/resources/images/client/Client.ts index a27a056eb..ffbfcbf66 100644 --- a/src/api/resources/catalog/resources/images/client/Client.ts +++ b/src/api/resources/catalog/resources/images/client/Client.ts @@ -7,7 +7,7 @@ import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; import * as serializers from "../../../../../../serialization/index"; import { toJson } from "../../../../../../core/json"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as errors from "../../../../../../errors/index"; export declare namespace Images { @@ -18,6 +18,8 @@ export declare namespace Images { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -31,12 +33,16 @@ export declare namespace Images { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Images { - constructor(protected readonly _options: Images.Options = {}) {} + protected readonly _options: Images.Options; + + constructor(_options: Images.Options = {}) { + this._options = _options; + } /** * Uploads an image file to be represented by a [CatalogImage](entity:CatalogImage) object that can be linked to an existing @@ -52,10 +58,17 @@ export class Images { * @example * await client.catalog.images.create({}) */ - public async create( + public create( request: Square.catalog.CreateImagesRequest, requestOptions?: Images.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( + request: Square.catalog.CreateImagesRequest, + requestOptions?: Images.RequestOptions, + ): Promise> { const _request = await core.newFormData(); if (request.request != null) { _request.append( @@ -75,25 +88,22 @@ export class Images { const _maybeEncodedRequest = await _request.getRequest(); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/catalog/images", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ..._maybeEncodedRequest.headers, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + ..._maybeEncodedRequest.headers, + }), + requestOptions?.headers, + ), requestType: "file", duplex: _maybeEncodedRequest.duplex, body: _maybeEncodedRequest.body, @@ -102,19 +112,23 @@ export class Images { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateCatalogImageResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateCatalogImageResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -123,12 +137,14 @@ export class Images { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/catalog/images."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -147,10 +163,17 @@ export class Images { * imageId: "image_id" * }) */ - public async update( + public update( request: Square.catalog.UpdateImagesRequest, requestOptions?: Images.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( + request: Square.catalog.UpdateImagesRequest, + requestOptions?: Images.RequestOptions, + ): Promise> { const _request = await core.newFormData(); if (request.request != null) { _request.append( @@ -170,25 +193,22 @@ export class Images { const _maybeEncodedRequest = await _request.getRequest(); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/catalog/images/${encodeURIComponent(request.imageId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ..._maybeEncodedRequest.headers, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + ..._maybeEncodedRequest.headers, + }), + requestOptions?.headers, + ), requestType: "file", duplex: _maybeEncodedRequest.duplex, body: _maybeEncodedRequest.body, @@ -197,19 +217,23 @@ export class Images { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateCatalogImageResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateCatalogImageResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -218,12 +242,14 @@ export class Images { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling PUT /v2/catalog/images/{image_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/catalog/resources/images/client/index.ts b/src/api/resources/catalog/resources/images/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/catalog/resources/images/client/index.ts +++ b/src/api/resources/catalog/resources/images/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/catalog/resources/object/client/Client.ts b/src/api/resources/catalog/resources/object/client/Client.ts index 8b793b5b3..8aff47f98 100644 --- a/src/api/resources/catalog/resources/object/client/Client.ts +++ b/src/api/resources/catalog/resources/object/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../../../errors/index"; export declare namespace Object_ { @@ -17,6 +17,8 @@ export declare namespace Object_ { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Object_ { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Object_ { - constructor(protected readonly _options: Object_.Options = {}) {} + protected readonly _options: Object_.Options; + + constructor(_options: Object_.Options = {}) { + this._options = _options; + } /** * Creates a new or updates the specified [CatalogObject](entity:CatalogObject). @@ -56,29 +62,33 @@ export class Object_ { * } * }) */ - public async upsert( + public upsert( + request: Square.catalog.UpsertCatalogObjectRequest, + requestOptions?: Object_.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__upsert(request, requestOptions)); + } + + private async __upsert( request: Square.catalog.UpsertCatalogObjectRequest, requestOptions?: Object_.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/catalog/object", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.catalog.UpsertCatalogObjectRequest.jsonOrThrow(request, { @@ -90,19 +100,23 @@ export class Object_ { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpsertCatalogObjectResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpsertCatalogObjectResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -111,12 +125,14 @@ export class Object_ { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/catalog/object."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -138,10 +154,17 @@ export class Object_ { * objectId: "object_id" * }) */ - public async get( + public get( + request: Square.catalog.GetObjectRequest, + requestOptions?: Object_.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.catalog.GetObjectRequest, requestOptions?: Object_.RequestOptions, - ): Promise { + ): Promise> { const { objectId, includeRelatedObjects, catalogVersion, includeCategoryPathToRoot } = request; const _queryParams: Record = {}; if (includeRelatedObjects !== undefined) { @@ -157,45 +180,44 @@ export class Object_ { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/catalog/object/${encodeURIComponent(objectId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetCatalogObjectResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetCatalogObjectResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -204,6 +226,7 @@ export class Object_ { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -212,6 +235,7 @@ export class Object_ { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -236,50 +260,56 @@ export class Object_ { * objectId: "object_id" * }) */ - public async delete( + public delete( + request: Square.catalog.DeleteObjectRequest, + requestOptions?: Object_.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( request: Square.catalog.DeleteObjectRequest, requestOptions?: Object_.RequestOptions, - ): Promise { + ): Promise> { const { objectId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/catalog/object/${encodeURIComponent(objectId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteCatalogObjectResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteCatalogObjectResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -288,6 +318,7 @@ export class Object_ { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -296,6 +327,7 @@ export class Object_ { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/catalog/resources/object/client/index.ts b/src/api/resources/catalog/resources/object/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/catalog/resources/object/client/index.ts +++ b/src/api/resources/catalog/resources/object/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/checkout/client/Client.ts b/src/api/resources/checkout/client/Client.ts index a086a1357..b616387fe 100644 --- a/src/api/resources/checkout/client/Client.ts +++ b/src/api/resources/checkout/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; import * as errors from "../../../../errors/index"; import { PaymentLinks } from "../resources/paymentLinks/client/Client"; @@ -18,6 +18,8 @@ export declare namespace Checkout { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -31,14 +33,17 @@ export declare namespace Checkout { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Checkout { + protected readonly _options: Checkout.Options; protected _paymentLinks: PaymentLinks | undefined; - constructor(protected readonly _options: Checkout.Options = {}) {} + constructor(_options: Checkout.Options = {}) { + this._options = _options; + } public get paymentLinks(): PaymentLinks { return (this._paymentLinks ??= new PaymentLinks(this._options)); @@ -55,50 +60,56 @@ export class Checkout { * locationId: "location_id" * }) */ - public async retrieveLocationSettings( + public retrieveLocationSettings( request: Square.RetrieveLocationSettingsRequest, requestOptions?: Checkout.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__retrieveLocationSettings(request, requestOptions)); + } + + private async __retrieveLocationSettings( + request: Square.RetrieveLocationSettingsRequest, + requestOptions?: Checkout.RequestOptions, + ): Promise> { const { locationId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/online-checkout/location-settings/${encodeURIComponent(locationId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RetrieveLocationSettingsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RetrieveLocationSettingsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -107,6 +118,7 @@ export class Checkout { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -115,6 +127,7 @@ export class Checkout { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -131,30 +144,34 @@ export class Checkout { * locationSettings: {} * }) */ - public async updateLocationSettings( + public updateLocationSettings( request: Square.UpdateLocationSettingsRequest, requestOptions?: Checkout.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__updateLocationSettings(request, requestOptions)); + } + + private async __updateLocationSettings( + request: Square.UpdateLocationSettingsRequest, + requestOptions?: Checkout.RequestOptions, + ): Promise> { const { locationId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/online-checkout/location-settings/${encodeURIComponent(locationId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.UpdateLocationSettingsRequest.jsonOrThrow(_body, { @@ -166,19 +183,23 @@ export class Checkout { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateLocationSettingsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateLocationSettingsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -187,6 +208,7 @@ export class Checkout { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -195,6 +217,7 @@ export class Checkout { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -207,48 +230,53 @@ export class Checkout { * @example * await client.checkout.retrieveMerchantSettings() */ - public async retrieveMerchantSettings( + public retrieveMerchantSettings( + requestOptions?: Checkout.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__retrieveMerchantSettings(requestOptions)); + } + + private async __retrieveMerchantSettings( requestOptions?: Checkout.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/online-checkout/merchant-settings", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RetrieveMerchantSettingsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RetrieveMerchantSettingsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -257,6 +285,7 @@ export class Checkout { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -265,6 +294,7 @@ export class Checkout { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -280,29 +310,33 @@ export class Checkout { * merchantSettings: {} * }) */ - public async updateMerchantSettings( + public updateMerchantSettings( request: Square.UpdateMerchantSettingsRequest, requestOptions?: Checkout.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__updateMerchantSettings(request, requestOptions)); + } + + private async __updateMerchantSettings( + request: Square.UpdateMerchantSettingsRequest, + requestOptions?: Checkout.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/online-checkout/merchant-settings", ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.UpdateMerchantSettingsRequest.jsonOrThrow(request, { @@ -314,19 +348,23 @@ export class Checkout { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateMerchantSettingsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateMerchantSettingsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -335,6 +373,7 @@ export class Checkout { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -343,6 +382,7 @@ export class Checkout { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/checkout/client/index.ts b/src/api/resources/checkout/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/checkout/client/index.ts +++ b/src/api/resources/checkout/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/checkout/resources/paymentLinks/client/Client.ts b/src/api/resources/checkout/resources/paymentLinks/client/Client.ts index 8d018551b..48515be91 100644 --- a/src/api/resources/checkout/resources/paymentLinks/client/Client.ts +++ b/src/api/resources/checkout/resources/paymentLinks/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; import * as errors from "../../../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace PaymentLinks { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace PaymentLinks { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class PaymentLinks { - constructor(protected readonly _options: PaymentLinks.Options = {}) {} + protected readonly _options: PaymentLinks.Options; + + constructor(_options: PaymentLinks.Options = {}) { + this._options = _options; + } /** * Lists all payment links. @@ -50,77 +56,84 @@ export class PaymentLinks { request: Square.checkout.ListPaymentLinksRequest = {}, requestOptions?: PaymentLinks.RequestOptions, ): Promise> { - const list = async ( - request: Square.checkout.ListPaymentLinksRequest, - ): Promise => { - const { cursor, limit } = request; - const _queryParams: Record = {}; - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/online-checkout/payment-links", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListPaymentLinksResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.checkout.ListPaymentLinksRequest, + ): Promise> => { + const { cursor, limit } = request; + const _queryParams: Record = {}; + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/online-checkout/payment-links", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListPaymentLinksResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/online-checkout/payment-links.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/online-checkout/payment-links.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.paymentLinks ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -140,36 +153,40 @@ export class PaymentLinks { * quickPay: { * name: "Auto Detailing", * priceMoney: { - * amount: 10000, + * amount: BigInt("10000"), * currency: "USD" * }, * locationId: "A9Y43N9ABXZBP" * } * }) */ - public async create( + public create( + request: Square.checkout.CreatePaymentLinkRequest = {}, + requestOptions?: PaymentLinks.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( request: Square.checkout.CreatePaymentLinkRequest = {}, requestOptions?: PaymentLinks.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/online-checkout/payment-links", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.checkout.CreatePaymentLinkRequest.jsonOrThrow(request, { @@ -181,19 +198,23 @@ export class PaymentLinks { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreatePaymentLinkResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreatePaymentLinkResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -202,6 +223,7 @@ export class PaymentLinks { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -210,6 +232,7 @@ export class PaymentLinks { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -225,50 +248,56 @@ export class PaymentLinks { * id: "id" * }) */ - public async get( + public get( + request: Square.checkout.GetPaymentLinksRequest, + requestOptions?: PaymentLinks.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.checkout.GetPaymentLinksRequest, requestOptions?: PaymentLinks.RequestOptions, - ): Promise { + ): Promise> { const { id } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/online-checkout/payment-links/${encodeURIComponent(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetPaymentLinkResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetPaymentLinkResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -277,6 +306,7 @@ export class PaymentLinks { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -285,6 +315,7 @@ export class PaymentLinks { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -308,30 +339,34 @@ export class PaymentLinks { * } * }) */ - public async update( + public update( + request: Square.checkout.UpdatePaymentLinkRequest, + requestOptions?: PaymentLinks.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( request: Square.checkout.UpdatePaymentLinkRequest, requestOptions?: PaymentLinks.RequestOptions, - ): Promise { + ): Promise> { const { id, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/online-checkout/payment-links/${encodeURIComponent(id)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.checkout.UpdatePaymentLinkRequest.jsonOrThrow(_body, { @@ -343,19 +378,23 @@ export class PaymentLinks { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdatePaymentLinkResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdatePaymentLinkResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -364,6 +403,7 @@ export class PaymentLinks { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -372,6 +412,7 @@ export class PaymentLinks { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -387,50 +428,56 @@ export class PaymentLinks { * id: "id" * }) */ - public async delete( + public delete( request: Square.checkout.DeletePaymentLinksRequest, requestOptions?: PaymentLinks.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( + request: Square.checkout.DeletePaymentLinksRequest, + requestOptions?: PaymentLinks.RequestOptions, + ): Promise> { const { id } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/online-checkout/payment-links/${encodeURIComponent(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeletePaymentLinkResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeletePaymentLinkResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -439,6 +486,7 @@ export class PaymentLinks { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -447,6 +495,7 @@ export class PaymentLinks { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/checkout/resources/paymentLinks/client/index.ts b/src/api/resources/checkout/resources/paymentLinks/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/checkout/resources/paymentLinks/client/index.ts +++ b/src/api/resources/checkout/resources/paymentLinks/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/checkout/resources/paymentLinks/client/requests/CreatePaymentLinkRequest.ts b/src/api/resources/checkout/resources/paymentLinks/client/requests/CreatePaymentLinkRequest.ts index 042082f59..3aff25717 100644 --- a/src/api/resources/checkout/resources/paymentLinks/client/requests/CreatePaymentLinkRequest.ts +++ b/src/api/resources/checkout/resources/paymentLinks/client/requests/CreatePaymentLinkRequest.ts @@ -11,7 +11,7 @@ import * as Square from "../../../../../../index"; * quickPay: { * name: "Auto Detailing", * priceMoney: { - * amount: 10000, + * amount: BigInt("10000"), * currency: "USD" * }, * locationId: "A9Y43N9ABXZBP" diff --git a/src/api/resources/customers/client/Client.ts b/src/api/resources/customers/client/Client.ts index 4ecdd790f..1cd2e82e7 100644 --- a/src/api/resources/customers/client/Client.ts +++ b/src/api/resources/customers/client/Client.ts @@ -6,7 +6,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as errors from "../../../../errors/index"; import { CustomAttributeDefinitions } from "../resources/customAttributeDefinitions/client/Client"; import { Groups } from "../resources/groups/client/Client"; @@ -22,6 +22,8 @@ export declare namespace Customers { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -35,18 +37,21 @@ export declare namespace Customers { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Customers { + protected readonly _options: Customers.Options; protected _customAttributeDefinitions: CustomAttributeDefinitions | undefined; protected _groups: Groups | undefined; protected _segments: Segments | undefined; protected _cards: Cards | undefined; protected _customAttributes: CustomAttributes | undefined; - constructor(protected readonly _options: Customers.Options = {}) {} + constructor(_options: Customers.Options = {}) { + this._options = _options; + } public get customAttributeDefinitions(): CustomAttributeDefinitions { return (this._customAttributeDefinitions ??= new CustomAttributeDefinitions(this._options)); @@ -85,88 +90,97 @@ export class Customers { request: Square.ListCustomersRequest = {}, requestOptions?: Customers.RequestOptions, ): Promise> { - const list = async (request: Square.ListCustomersRequest): Promise => { - const { cursor, limit, sortField, sortOrder, count } = request; - const _queryParams: Record = {}; - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (sortField !== undefined) { - _queryParams["sort_field"] = serializers.CustomerSortField.jsonOrThrow(sortField, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - if (sortOrder !== undefined) { - _queryParams["sort_order"] = serializers.SortOrder.jsonOrThrow(sortOrder, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - if (count !== undefined) { - _queryParams["count"] = count?.toString() ?? null; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/customers", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListCustomersResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.ListCustomersRequest, + ): Promise> => { + const { cursor, limit, sortField, sortOrder, count } = request; + const _queryParams: Record = {}; + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (sortField !== undefined) { + _queryParams["sort_field"] = serializers.CustomerSortField.jsonOrThrow(sortField, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + if (sortOrder !== undefined) { + _queryParams["sort_order"] = serializers.SortOrder.jsonOrThrow(sortOrder, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + if (count !== undefined) { + _queryParams["count"] = count?.toString() ?? null; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/customers", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListCustomersResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/customers."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/customers."); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.customers ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -207,29 +221,33 @@ export class Customers { * note: "a customer" * }) */ - public async create( + public create( request: Square.CreateCustomerRequest = {}, requestOptions?: Customers.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( + request: Square.CreateCustomerRequest = {}, + requestOptions?: Customers.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/customers", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CreateCustomerRequest.jsonOrThrow(request, { @@ -241,19 +259,23 @@ export class Customers { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateCustomerResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateCustomerResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -262,12 +284,14 @@ export class Customers { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/customers."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -326,29 +350,33 @@ export class Customers { * } * }) */ - public async batchCreate( + public batchCreate( + request: Square.BulkCreateCustomersRequest, + requestOptions?: Customers.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchCreate(request, requestOptions)); + } + + private async __batchCreate( request: Square.BulkCreateCustomersRequest, requestOptions?: Customers.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/customers/bulk-create", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BulkCreateCustomersRequest.jsonOrThrow(request, { @@ -360,19 +388,23 @@ export class Customers { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BulkCreateCustomersResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BulkCreateCustomersResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -381,12 +413,14 @@ export class Customers { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/customers/bulk-create."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -404,29 +438,33 @@ export class Customers { * customerIds: ["8DDA5NZVBZFGAX0V3HPF81HHE0", "N18CPRVXR5214XPBBA6BZQWF3C", "2GYD7WNXF7BJZW1PMGNXZ3Y8M8"] * }) */ - public async bulkDeleteCustomers( + public bulkDeleteCustomers( request: Square.BulkDeleteCustomersRequest, requestOptions?: Customers.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__bulkDeleteCustomers(request, requestOptions)); + } + + private async __bulkDeleteCustomers( + request: Square.BulkDeleteCustomersRequest, + requestOptions?: Customers.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/customers/bulk-delete", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BulkDeleteCustomersRequest.jsonOrThrow(request, { @@ -438,19 +476,23 @@ export class Customers { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BulkDeleteCustomersResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BulkDeleteCustomersResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -459,12 +501,14 @@ export class Customers { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/customers/bulk-delete."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -482,29 +526,33 @@ export class Customers { * customerIds: ["8DDA5NZVBZFGAX0V3HPF81HHE0", "N18CPRVXR5214XPBBA6BZQWF3C", "2GYD7WNXF7BJZW1PMGNXZ3Y8M8"] * }) */ - public async bulkRetrieveCustomers( + public bulkRetrieveCustomers( request: Square.BulkRetrieveCustomersRequest, requestOptions?: Customers.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__bulkRetrieveCustomers(request, requestOptions)); + } + + private async __bulkRetrieveCustomers( + request: Square.BulkRetrieveCustomersRequest, + requestOptions?: Customers.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/customers/bulk-retrieve", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BulkRetrieveCustomersRequest.jsonOrThrow(request, { @@ -516,19 +564,23 @@ export class Customers { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BulkRetrieveCustomersResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BulkRetrieveCustomersResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -537,12 +589,14 @@ export class Customers { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/customers/bulk-retrieve."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -561,39 +615,43 @@ export class Customers { * "8DDA5NZVBZFGAX0V3HPF81HHE0": { * emailAddress: "New.Amelia.Earhart@example.com", * note: "updated customer note", - * version: 2 + * version: BigInt("2") * }, * "N18CPRVXR5214XPBBA6BZQWF3C": { * givenName: "Marie", * familyName: "Curie", - * version: 0 + * version: BigInt("0") * } * } * }) */ - public async bulkUpdateCustomers( + public bulkUpdateCustomers( request: Square.BulkUpdateCustomersRequest, requestOptions?: Customers.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__bulkUpdateCustomers(request, requestOptions)); + } + + private async __bulkUpdateCustomers( + request: Square.BulkUpdateCustomersRequest, + requestOptions?: Customers.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/customers/bulk-update", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BulkUpdateCustomersRequest.jsonOrThrow(request, { @@ -605,19 +663,23 @@ export class Customers { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BulkUpdateCustomersResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BulkUpdateCustomersResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -626,12 +688,14 @@ export class Customers { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/customers/bulk-update."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -652,7 +716,7 @@ export class Customers { * * @example * await client.customers.search({ - * limit: 2, + * limit: BigInt("2"), * query: { * filter: { * creationSource: { @@ -677,29 +741,33 @@ export class Customers { * } * }) */ - public async search( + public search( request: Square.SearchCustomersRequest = {}, requestOptions?: Customers.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__search(request, requestOptions)); + } + + private async __search( + request: Square.SearchCustomersRequest = {}, + requestOptions?: Customers.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/customers/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.SearchCustomersRequest.jsonOrThrow(request, { @@ -711,19 +779,23 @@ export class Customers { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchCustomersResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchCustomersResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -732,12 +804,14 @@ export class Customers { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/customers/search."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -753,50 +827,56 @@ export class Customers { * customerId: "customer_id" * }) */ - public async get( + public get( request: Square.GetCustomersRequest, requestOptions?: Customers.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.GetCustomersRequest, + requestOptions?: Customers.RequestOptions, + ): Promise> { const { customerId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/customers/${encodeURIComponent(customerId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetCustomerResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetCustomerResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -805,12 +885,14 @@ export class Customers { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/customers/{customer_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -829,33 +911,37 @@ export class Customers { * customerId: "customer_id", * emailAddress: "New.Amelia.Earhart@example.com", * note: "updated customer note", - * version: 2 + * version: BigInt("2") * }) */ - public async update( + public update( request: Square.UpdateCustomerRequest, requestOptions?: Customers.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( + request: Square.UpdateCustomerRequest, + requestOptions?: Customers.RequestOptions, + ): Promise> { const { customerId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/customers/${encodeURIComponent(customerId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.UpdateCustomerRequest.jsonOrThrow(_body, { @@ -867,19 +953,23 @@ export class Customers { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateCustomerResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateCustomerResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -888,12 +978,14 @@ export class Customers { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling PUT /v2/customers/{customer_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -911,10 +1003,17 @@ export class Customers { * customerId: "customer_id" * }) */ - public async delete( + public delete( request: Square.DeleteCustomersRequest, requestOptions?: Customers.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( + request: Square.DeleteCustomersRequest, + requestOptions?: Customers.RequestOptions, + ): Promise> { const { customerId, version } = request; const _queryParams: Record = {}; if (version !== undefined) { @@ -922,45 +1021,44 @@ export class Customers { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/customers/${encodeURIComponent(customerId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteCustomerResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteCustomerResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -969,6 +1067,7 @@ export class Customers { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -977,6 +1076,7 @@ export class Customers { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/customers/client/index.ts b/src/api/resources/customers/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/customers/client/index.ts +++ b/src/api/resources/customers/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/customers/client/requests/BulkUpdateCustomersRequest.ts b/src/api/resources/customers/client/requests/BulkUpdateCustomersRequest.ts index 7cfa8b1a8..2af49f166 100644 --- a/src/api/resources/customers/client/requests/BulkUpdateCustomersRequest.ts +++ b/src/api/resources/customers/client/requests/BulkUpdateCustomersRequest.ts @@ -11,12 +11,12 @@ import * as Square from "../../../../index"; * "8DDA5NZVBZFGAX0V3HPF81HHE0": { * emailAddress: "New.Amelia.Earhart@example.com", * note: "updated customer note", - * version: 2 + * version: BigInt("2") * }, * "N18CPRVXR5214XPBBA6BZQWF3C": { * givenName: "Marie", * familyName: "Curie", - * version: 0 + * version: BigInt("0") * } * } * } diff --git a/src/api/resources/customers/client/requests/SearchCustomersRequest.ts b/src/api/resources/customers/client/requests/SearchCustomersRequest.ts index 4b583487e..898381ffd 100644 --- a/src/api/resources/customers/client/requests/SearchCustomersRequest.ts +++ b/src/api/resources/customers/client/requests/SearchCustomersRequest.ts @@ -7,7 +7,7 @@ import * as Square from "../../../../index"; /** * @example * { - * limit: 2, + * limit: BigInt("2"), * query: { * filter: { * creationSource: { diff --git a/src/api/resources/customers/client/requests/UpdateCustomerRequest.ts b/src/api/resources/customers/client/requests/UpdateCustomerRequest.ts index 634ee8d34..8aae7b1ec 100644 --- a/src/api/resources/customers/client/requests/UpdateCustomerRequest.ts +++ b/src/api/resources/customers/client/requests/UpdateCustomerRequest.ts @@ -10,7 +10,7 @@ import * as Square from "../../../../index"; * customerId: "customer_id", * emailAddress: "New.Amelia.Earhart@example.com", * note: "updated customer note", - * version: 2 + * version: BigInt("2") * } */ export interface UpdateCustomerRequest { diff --git a/src/api/resources/customers/resources/cards/client/Client.ts b/src/api/resources/customers/resources/cards/client/Client.ts index 1f29d7a0b..f73bd187a 100644 --- a/src/api/resources/customers/resources/cards/client/Client.ts +++ b/src/api/resources/customers/resources/cards/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../../../errors/index"; export declare namespace Cards { @@ -17,6 +17,8 @@ export declare namespace Cards { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Cards { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Cards { - constructor(protected readonly _options: Cards.Options = {}) {} + protected readonly _options: Cards.Options; + + constructor(_options: Cards.Options = {}) { + this._options = _options; + } /** * Adds a card on file to an existing customer. @@ -62,30 +68,34 @@ export class Cards { * cardholderName: "Amelia Earhart" * }) */ - public async create( + public create( + request: Square.customers.CreateCustomerCardRequest, + requestOptions?: Cards.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( request: Square.customers.CreateCustomerCardRequest, requestOptions?: Cards.RequestOptions, - ): Promise { + ): Promise> { const { customerId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/customers/${encodeURIComponent(customerId)}/cards`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.customers.CreateCustomerCardRequest.jsonOrThrow(_body, { @@ -97,19 +107,23 @@ export class Cards { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateCustomerCardResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateCustomerCardResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -118,6 +132,7 @@ export class Cards { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -126,6 +141,7 @@ export class Cards { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -142,50 +158,56 @@ export class Cards { * cardId: "card_id" * }) */ - public async delete( + public delete( request: Square.customers.DeleteCardsRequest, requestOptions?: Cards.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( + request: Square.customers.DeleteCardsRequest, + requestOptions?: Cards.RequestOptions, + ): Promise> { const { customerId, cardId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/customers/${encodeURIComponent(customerId)}/cards/${encodeURIComponent(cardId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteCustomerCardResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteCustomerCardResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -194,6 +216,7 @@ export class Cards { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -202,6 +225,7 @@ export class Cards { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/customers/resources/cards/client/index.ts b/src/api/resources/customers/resources/cards/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/customers/resources/cards/client/index.ts +++ b/src/api/resources/customers/resources/cards/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/customers/resources/customAttributeDefinitions/client/Client.ts b/src/api/resources/customers/resources/customAttributeDefinitions/client/Client.ts index 85bb9526f..0d6820a42 100644 --- a/src/api/resources/customers/resources/customAttributeDefinitions/client/Client.ts +++ b/src/api/resources/customers/resources/customAttributeDefinitions/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; import * as errors from "../../../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace CustomAttributeDefinitions { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace CustomAttributeDefinitions { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class CustomAttributeDefinitions { - constructor(protected readonly _options: CustomAttributeDefinitions.Options = {}) {} + protected readonly _options: CustomAttributeDefinitions.Options; + + constructor(_options: CustomAttributeDefinitions.Options = {}) { + this._options = _options; + } /** * Lists the customer-related [custom attribute definitions](entity:CustomAttributeDefinition) that belong to a Square seller account. @@ -55,80 +61,87 @@ export class CustomAttributeDefinitions { request: Square.customers.ListCustomAttributeDefinitionsRequest = {}, requestOptions?: CustomAttributeDefinitions.RequestOptions, ): Promise> { - const list = async ( - request: Square.customers.ListCustomAttributeDefinitionsRequest, - ): Promise => { - const { limit, cursor } = request; - const _queryParams: Record = {}; - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/customers/custom-attribute-definitions", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListCustomerCustomAttributeDefinitionsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.customers.ListCustomAttributeDefinitionsRequest, + ): Promise> => { + const { limit, cursor } = request; + const _queryParams: Record = {}; + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/customers/custom-attribute-definitions", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListCustomerCustomAttributeDefinitionsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/customers/custom-attribute-definitions.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/customers/custom-attribute-definitions.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable< Square.ListCustomerCustomAttributeDefinitionsResponse, Square.CustomAttributeDefinition >({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.customAttributeDefinitions ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -165,29 +178,33 @@ export class CustomAttributeDefinitions { * } * }) */ - public async create( + public create( + request: Square.customers.CreateCustomerCustomAttributeDefinitionRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( request: Square.customers.CreateCustomerCustomAttributeDefinitionRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/customers/custom-attribute-definitions", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.customers.CreateCustomerCustomAttributeDefinitionRequest.jsonOrThrow(request, { @@ -199,19 +216,23 @@ export class CustomAttributeDefinitions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateCustomerCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateCustomerCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -220,6 +241,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -228,6 +250,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -247,10 +270,17 @@ export class CustomAttributeDefinitions { * key: "key" * }) */ - public async get( + public get( + request: Square.customers.GetCustomAttributeDefinitionsRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.customers.GetCustomAttributeDefinitionsRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): Promise> { const { key, version } = request; const _queryParams: Record = {}; if (version !== undefined) { @@ -258,45 +288,44 @@ export class CustomAttributeDefinitions { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/customers/custom-attribute-definitions/${encodeURIComponent(key)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetCustomerCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetCustomerCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -305,6 +334,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -313,6 +343,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -338,30 +369,34 @@ export class CustomAttributeDefinitions { * } * }) */ - public async update( + public update( + request: Square.customers.UpdateCustomerCustomAttributeDefinitionRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( request: Square.customers.UpdateCustomerCustomAttributeDefinitionRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): Promise> { const { key, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/customers/custom-attribute-definitions/${encodeURIComponent(key)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.customers.UpdateCustomerCustomAttributeDefinitionRequest.jsonOrThrow(_body, { @@ -373,19 +408,23 @@ export class CustomAttributeDefinitions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateCustomerCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateCustomerCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -394,6 +433,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -402,6 +442,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -422,50 +463,56 @@ export class CustomAttributeDefinitions { * key: "key" * }) */ - public async delete( + public delete( + request: Square.customers.DeleteCustomAttributeDefinitionsRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( request: Square.customers.DeleteCustomAttributeDefinitionsRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): Promise> { const { key } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/customers/custom-attribute-definitions/${encodeURIComponent(key)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteCustomerCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteCustomerCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -474,6 +521,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -482,6 +530,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -546,29 +595,33 @@ export class CustomAttributeDefinitions { * } * }) */ - public async batchUpsert( + public batchUpsert( request: Square.customers.BatchUpsertCustomerCustomAttributesRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchUpsert(request, requestOptions)); + } + + private async __batchUpsert( + request: Square.customers.BatchUpsertCustomerCustomAttributesRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/customers/custom-attributes/bulk-upsert", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.customers.BatchUpsertCustomerCustomAttributesRequest.jsonOrThrow(request, { @@ -580,19 +633,23 @@ export class CustomAttributeDefinitions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BatchUpsertCustomerCustomAttributesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BatchUpsertCustomerCustomAttributesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -601,6 +658,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -609,6 +667,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/customers/resources/customAttributeDefinitions/client/index.ts b/src/api/resources/customers/resources/customAttributeDefinitions/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/customers/resources/customAttributeDefinitions/client/index.ts +++ b/src/api/resources/customers/resources/customAttributeDefinitions/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/customers/resources/customAttributes/client/Client.ts b/src/api/resources/customers/resources/customAttributes/client/Client.ts index aa1364f0e..cc613e417 100644 --- a/src/api/resources/customers/resources/customAttributes/client/Client.ts +++ b/src/api/resources/customers/resources/customAttributes/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; import * as errors from "../../../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace CustomAttributes { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace CustomAttributes { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class CustomAttributes { - constructor(protected readonly _options: CustomAttributes.Options = {}) {} + protected readonly _options: CustomAttributes.Options; + + constructor(_options: CustomAttributes.Options = {}) { + this._options = _options; + } /** * Lists the [custom attributes](entity:CustomAttribute) associated with a customer profile. @@ -59,80 +65,87 @@ export class CustomAttributes { request: Square.customers.ListCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, ): Promise> { - const list = async ( - request: Square.customers.ListCustomAttributesRequest, - ): Promise => { - const { customerId, limit, cursor, withDefinitions } = request; - const _queryParams: Record = {}; - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (withDefinitions !== undefined) { - _queryParams["with_definitions"] = withDefinitions?.toString() ?? null; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - `v2/customers/${encodeURIComponent(customerId)}/custom-attributes`, - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListCustomerCustomAttributesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.customers.ListCustomAttributesRequest, + ): Promise> => { + const { customerId, limit, cursor, withDefinitions } = request; + const _queryParams: Record = {}; + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (withDefinitions !== undefined) { + _queryParams["with_definitions"] = withDefinitions?.toString() ?? null; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + `v2/customers/${encodeURIComponent(customerId)}/custom-attributes`, + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListCustomerCustomAttributesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/customers/{customer_id}/custom-attributes.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, - }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/customers/{customer_id}/custom-attributes.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.customAttributes ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -159,10 +172,17 @@ export class CustomAttributes { * key: "key" * }) */ - public async get( + public get( request: Square.customers.GetCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.customers.GetCustomAttributesRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): Promise> { const { customerId, key, withDefinition, version } = request; const _queryParams: Record = {}; if (withDefinition !== undefined) { @@ -174,45 +194,44 @@ export class CustomAttributes { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/customers/${encodeURIComponent(customerId)}/custom-attributes/${encodeURIComponent(key)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetCustomerCustomAttributeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetCustomerCustomAttributeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -221,6 +240,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -229,6 +249,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -256,30 +277,34 @@ export class CustomAttributes { * } * }) */ - public async upsert( + public upsert( + request: Square.customers.UpsertCustomerCustomAttributeRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__upsert(request, requestOptions)); + } + + private async __upsert( request: Square.customers.UpsertCustomerCustomAttributeRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): Promise> { const { customerId, key, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/customers/${encodeURIComponent(customerId)}/custom-attributes/${encodeURIComponent(key)}`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.customers.UpsertCustomerCustomAttributeRequest.jsonOrThrow(_body, { @@ -291,19 +316,23 @@ export class CustomAttributes { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpsertCustomerCustomAttributeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpsertCustomerCustomAttributeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -312,6 +341,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -320,6 +350,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -340,50 +371,56 @@ export class CustomAttributes { * key: "key" * }) */ - public async delete( + public delete( request: Square.customers.DeleteCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( + request: Square.customers.DeleteCustomAttributesRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): Promise> { const { customerId, key } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/customers/${encodeURIComponent(customerId)}/custom-attributes/${encodeURIComponent(key)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteCustomerCustomAttributeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteCustomerCustomAttributeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -392,6 +429,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -400,6 +438,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/customers/resources/customAttributes/client/index.ts b/src/api/resources/customers/resources/customAttributes/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/customers/resources/customAttributes/client/index.ts +++ b/src/api/resources/customers/resources/customAttributes/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/customers/resources/groups/client/Client.ts b/src/api/resources/customers/resources/groups/client/Client.ts index a0c37461b..03da469ac 100644 --- a/src/api/resources/customers/resources/groups/client/Client.ts +++ b/src/api/resources/customers/resources/groups/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; import * as errors from "../../../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace Groups { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Groups { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Groups { - constructor(protected readonly _options: Groups.Options = {}) {} + protected readonly _options: Groups.Options; + + constructor(_options: Groups.Options = {}) { + this._options = _options; + } /** * Retrieves the list of customer groups of a business. @@ -50,75 +56,82 @@ export class Groups { request: Square.customers.ListGroupsRequest = {}, requestOptions?: Groups.RequestOptions, ): Promise> { - const list = async ( - request: Square.customers.ListGroupsRequest, - ): Promise => { - const { cursor, limit } = request; - const _queryParams: Record = {}; - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/customers/groups", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListCustomerGroupsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.customers.ListGroupsRequest, + ): Promise> => { + const { cursor, limit } = request; + const _queryParams: Record = {}; + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/customers/groups", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListCustomerGroupsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/customers/groups."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/customers/groups."); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.groups ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -141,29 +154,33 @@ export class Groups { * } * }) */ - public async create( + public create( request: Square.customers.CreateCustomerGroupRequest, requestOptions?: Groups.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( + request: Square.customers.CreateCustomerGroupRequest, + requestOptions?: Groups.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/customers/groups", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.customers.CreateCustomerGroupRequest.jsonOrThrow(request, { @@ -175,19 +192,23 @@ export class Groups { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateCustomerGroupResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateCustomerGroupResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -196,12 +217,14 @@ export class Groups { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/customers/groups."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -217,50 +240,56 @@ export class Groups { * groupId: "group_id" * }) */ - public async get( + public get( request: Square.customers.GetGroupsRequest, requestOptions?: Groups.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.customers.GetGroupsRequest, + requestOptions?: Groups.RequestOptions, + ): Promise> { const { groupId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/customers/groups/${encodeURIComponent(groupId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetCustomerGroupResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetCustomerGroupResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -269,6 +298,7 @@ export class Groups { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -277,6 +307,7 @@ export class Groups { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -295,30 +326,34 @@ export class Groups { * } * }) */ - public async update( + public update( + request: Square.customers.UpdateCustomerGroupRequest, + requestOptions?: Groups.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( request: Square.customers.UpdateCustomerGroupRequest, requestOptions?: Groups.RequestOptions, - ): Promise { + ): Promise> { const { groupId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/customers/groups/${encodeURIComponent(groupId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.customers.UpdateCustomerGroupRequest.jsonOrThrow(_body, { @@ -330,19 +365,23 @@ export class Groups { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateCustomerGroupResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateCustomerGroupResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -351,6 +390,7 @@ export class Groups { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -359,6 +399,7 @@ export class Groups { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -374,50 +415,56 @@ export class Groups { * groupId: "group_id" * }) */ - public async delete( + public delete( request: Square.customers.DeleteGroupsRequest, requestOptions?: Groups.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( + request: Square.customers.DeleteGroupsRequest, + requestOptions?: Groups.RequestOptions, + ): Promise> { const { groupId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/customers/groups/${encodeURIComponent(groupId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteCustomerGroupResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteCustomerGroupResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -426,6 +473,7 @@ export class Groups { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -434,6 +482,7 @@ export class Groups { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -453,50 +502,56 @@ export class Groups { * groupId: "group_id" * }) */ - public async add( + public add( + request: Square.customers.AddGroupsRequest, + requestOptions?: Groups.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__add(request, requestOptions)); + } + + private async __add( request: Square.customers.AddGroupsRequest, requestOptions?: Groups.RequestOptions, - ): Promise { + ): Promise> { const { customerId, groupId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/customers/${encodeURIComponent(customerId)}/groups/${encodeURIComponent(groupId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.AddGroupToCustomerResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.AddGroupToCustomerResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -505,6 +560,7 @@ export class Groups { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -513,6 +569,7 @@ export class Groups { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -532,50 +589,56 @@ export class Groups { * groupId: "group_id" * }) */ - public async remove( + public remove( request: Square.customers.RemoveGroupsRequest, requestOptions?: Groups.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__remove(request, requestOptions)); + } + + private async __remove( + request: Square.customers.RemoveGroupsRequest, + requestOptions?: Groups.RequestOptions, + ): Promise> { const { customerId, groupId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/customers/${encodeURIComponent(customerId)}/groups/${encodeURIComponent(groupId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RemoveGroupFromCustomerResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RemoveGroupFromCustomerResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -584,6 +647,7 @@ export class Groups { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -592,6 +656,7 @@ export class Groups { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/customers/resources/groups/client/index.ts b/src/api/resources/customers/resources/groups/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/customers/resources/groups/client/index.ts +++ b/src/api/resources/customers/resources/groups/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/customers/resources/segments/client/Client.ts b/src/api/resources/customers/resources/segments/client/Client.ts index 3d4d9cbb8..1bf067efb 100644 --- a/src/api/resources/customers/resources/segments/client/Client.ts +++ b/src/api/resources/customers/resources/segments/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; import * as errors from "../../../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace Segments { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Segments { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Segments { - constructor(protected readonly _options: Segments.Options = {}) {} + protected readonly _options: Segments.Options; + + constructor(_options: Segments.Options = {}) { + this._options = _options; + } /** * Retrieves the list of customer segments of a business. @@ -50,75 +56,84 @@ export class Segments { request: Square.customers.ListSegmentsRequest = {}, requestOptions?: Segments.RequestOptions, ): Promise> { - const list = async ( - request: Square.customers.ListSegmentsRequest, - ): Promise => { - const { cursor, limit } = request; - const _queryParams: Record = {}; - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/customers/segments", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListCustomerSegmentsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.customers.ListSegmentsRequest, + ): Promise> => { + const { cursor, limit } = request; + const _queryParams: Record = {}; + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/customers/segments", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListCustomerSegmentsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/customers/segments."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/customers/segments.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.segments ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -137,50 +152,56 @@ export class Segments { * segmentId: "segment_id" * }) */ - public async get( + public get( request: Square.customers.GetSegmentsRequest, requestOptions?: Segments.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.customers.GetSegmentsRequest, + requestOptions?: Segments.RequestOptions, + ): Promise> { const { segmentId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/customers/segments/${encodeURIComponent(segmentId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetCustomerSegmentResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetCustomerSegmentResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -189,6 +210,7 @@ export class Segments { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -197,6 +219,7 @@ export class Segments { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/customers/resources/segments/client/index.ts b/src/api/resources/customers/resources/segments/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/customers/resources/segments/client/index.ts +++ b/src/api/resources/customers/resources/segments/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/devices/client/Client.ts b/src/api/resources/devices/client/Client.ts index 2dfabecaf..646b9b0e9 100644 --- a/src/api/resources/devices/client/Client.ts +++ b/src/api/resources/devices/client/Client.ts @@ -6,7 +6,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as errors from "../../../../errors/index"; import { Codes } from "../resources/codes/client/Client"; @@ -18,6 +18,8 @@ export declare namespace Devices { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -31,14 +33,17 @@ export declare namespace Devices { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Devices { + protected readonly _options: Devices.Options; protected _codes: Codes | undefined; - constructor(protected readonly _options: Devices.Options = {}) {} + constructor(_options: Devices.Options = {}) { + this._options = _options; + } public get codes(): Codes { return (this._codes ??= new Codes(this._options)); @@ -58,82 +63,89 @@ export class Devices { request: Square.ListDevicesRequest = {}, requestOptions?: Devices.RequestOptions, ): Promise> { - const list = async (request: Square.ListDevicesRequest): Promise => { - const { cursor, sortOrder, limit, locationId } = request; - const _queryParams: Record = {}; - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (sortOrder !== undefined) { - _queryParams["sort_order"] = serializers.SortOrder.jsonOrThrow(sortOrder, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (locationId !== undefined) { - _queryParams["location_id"] = locationId; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/devices", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListDevicesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async (request: Square.ListDevicesRequest): Promise> => { + const { cursor, sortOrder, limit, locationId } = request; + const _queryParams: Record = {}; + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (sortOrder !== undefined) { + _queryParams["sort_order"] = serializers.SortOrder.jsonOrThrow(sortOrder, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (locationId !== undefined) { + _queryParams["location_id"] = locationId; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/devices", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListDevicesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/devices."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/devices."); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.devices ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -152,50 +164,56 @@ export class Devices { * deviceId: "device_id" * }) */ - public async get( + public get( request: Square.GetDevicesRequest, requestOptions?: Devices.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.GetDevicesRequest, + requestOptions?: Devices.RequestOptions, + ): Promise> { const { deviceId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/devices/${encodeURIComponent(deviceId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetDeviceResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetDeviceResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -204,12 +222,14 @@ export class Devices { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/devices/{device_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/devices/client/index.ts b/src/api/resources/devices/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/devices/client/index.ts +++ b/src/api/resources/devices/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/devices/resources/codes/client/Client.ts b/src/api/resources/devices/resources/codes/client/Client.ts index 24ce8aad2..2fb402a21 100644 --- a/src/api/resources/devices/resources/codes/client/Client.ts +++ b/src/api/resources/devices/resources/codes/client/Client.ts @@ -6,7 +6,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as errors from "../../../../../../errors/index"; export declare namespace Codes { @@ -17,6 +17,8 @@ export declare namespace Codes { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Codes { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Codes { - constructor(protected readonly _options: Codes.Options = {}) {} + protected readonly _options: Codes.Options; + + constructor(_options: Codes.Options = {}) { + this._options = _options; + } /** * Lists all DeviceCodes associated with the merchant. @@ -50,85 +56,94 @@ export class Codes { request: Square.devices.ListCodesRequest = {}, requestOptions?: Codes.RequestOptions, ): Promise> { - const list = async (request: Square.devices.ListCodesRequest): Promise => { - const { cursor, locationId, productType, status } = request; - const _queryParams: Record = {}; - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (locationId !== undefined) { - _queryParams["location_id"] = locationId; - } - if (productType !== undefined) { - _queryParams["product_type"] = serializers.ProductType.jsonOrThrow(productType, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - if (status !== undefined) { - _queryParams["status"] = serializers.DeviceCodeStatus.jsonOrThrow(status, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/devices/codes", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListDeviceCodesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.devices.ListCodesRequest, + ): Promise> => { + const { cursor, locationId, productType, status } = request; + const _queryParams: Record = {}; + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (locationId !== undefined) { + _queryParams["location_id"] = locationId; + } + if (productType !== undefined) { + _queryParams["product_type"] = serializers.ProductType.jsonOrThrow(productType, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + if (status !== undefined) { + _queryParams["status"] = serializers.DeviceCodeStatus.jsonOrThrow(status, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/devices/codes", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListDeviceCodesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/devices/codes."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/devices/codes."); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.deviceCodes ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -153,29 +168,33 @@ export class Codes { * } * }) */ - public async create( + public create( + request: Square.devices.CreateDeviceCodeRequest, + requestOptions?: Codes.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( request: Square.devices.CreateDeviceCodeRequest, requestOptions?: Codes.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/devices/codes", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.devices.CreateDeviceCodeRequest.jsonOrThrow(request, { @@ -187,19 +206,23 @@ export class Codes { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateDeviceCodeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateDeviceCodeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -208,12 +231,14 @@ export class Codes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/devices/codes."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -229,50 +254,56 @@ export class Codes { * id: "id" * }) */ - public async get( + public get( + request: Square.devices.GetCodesRequest, + requestOptions?: Codes.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.devices.GetCodesRequest, requestOptions?: Codes.RequestOptions, - ): Promise { + ): Promise> { const { id } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/devices/codes/${encodeURIComponent(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetDeviceCodeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetDeviceCodeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -281,12 +312,14 @@ export class Codes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/devices/codes/{id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/devices/resources/codes/client/index.ts b/src/api/resources/devices/resources/codes/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/devices/resources/codes/client/index.ts +++ b/src/api/resources/devices/resources/codes/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/disputes/client/Client.ts b/src/api/resources/disputes/client/Client.ts index cbb523844..a16f1c06c 100644 --- a/src/api/resources/disputes/client/Client.ts +++ b/src/api/resources/disputes/client/Client.ts @@ -6,7 +6,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as errors from "../../../../errors/index"; import { toJson } from "../../../../core/json"; import { Evidence } from "../resources/evidence/client/Client"; @@ -19,6 +19,8 @@ export declare namespace Disputes { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -32,14 +34,17 @@ export declare namespace Disputes { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Disputes { + protected readonly _options: Disputes.Options; protected _evidence: Evidence | undefined; - constructor(protected readonly _options: Disputes.Options = {}) {} + constructor(_options: Disputes.Options = {}) { + this._options = _options; + } public get evidence(): Evidence { return (this._evidence ??= new Evidence(this._options)); @@ -58,79 +63,86 @@ export class Disputes { request: Square.ListDisputesRequest = {}, requestOptions?: Disputes.RequestOptions, ): Promise> { - const list = async (request: Square.ListDisputesRequest): Promise => { - const { cursor, states, locationId } = request; - const _queryParams: Record = {}; - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (states !== undefined) { - _queryParams["states"] = serializers.DisputeState.jsonOrThrow(states, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - if (locationId !== undefined) { - _queryParams["location_id"] = locationId; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/disputes", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListDisputesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async (request: Square.ListDisputesRequest): Promise> => { + const { cursor, states, locationId } = request; + const _queryParams: Record = {}; + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (states !== undefined) { + _queryParams["states"] = serializers.DisputeState.jsonOrThrow(states, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + if (locationId !== undefined) { + _queryParams["location_id"] = locationId; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/disputes", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListDisputesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/disputes."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/disputes."); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.disputes ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -149,50 +161,56 @@ export class Disputes { * disputeId: "dispute_id" * }) */ - public async get( + public get( + request: Square.GetDisputesRequest, + requestOptions?: Disputes.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.GetDisputesRequest, requestOptions?: Disputes.RequestOptions, - ): Promise { + ): Promise> { const { disputeId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/disputes/${encodeURIComponent(disputeId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetDisputeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetDisputeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -201,12 +219,14 @@ export class Disputes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/disputes/{dispute_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -226,50 +246,56 @@ export class Disputes { * disputeId: "dispute_id" * }) */ - public async accept( + public accept( request: Square.AcceptDisputesRequest, requestOptions?: Disputes.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__accept(request, requestOptions)); + } + + private async __accept( + request: Square.AcceptDisputesRequest, + requestOptions?: Disputes.RequestOptions, + ): Promise> { const { disputeId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/disputes/${encodeURIComponent(disputeId)}/accept`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.AcceptDisputeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.AcceptDisputeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -278,6 +304,7 @@ export class Disputes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -286,6 +313,7 @@ export class Disputes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -302,10 +330,17 @@ export class Disputes { * disputeId: "dispute_id" * }) */ - public async createEvidenceFile( + public createEvidenceFile( + request: Square.CreateEvidenceFileDisputesRequest, + requestOptions?: Disputes.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__createEvidenceFile(request, requestOptions)); + } + + private async __createEvidenceFile( request: Square.CreateEvidenceFileDisputesRequest, requestOptions?: Disputes.RequestOptions, - ): Promise { + ): Promise> { const _request = await core.newFormData(); if (request.request != null) { _request.append( @@ -325,25 +360,22 @@ export class Disputes { const _maybeEncodedRequest = await _request.getRequest(); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/disputes/${encodeURIComponent(request.disputeId)}/evidence-files`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ..._maybeEncodedRequest.headers, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + ..._maybeEncodedRequest.headers, + }), + requestOptions?.headers, + ), requestType: "file", duplex: _maybeEncodedRequest.duplex, body: _maybeEncodedRequest.body, @@ -352,19 +384,23 @@ export class Disputes { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateDisputeEvidenceFileResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateDisputeEvidenceFileResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -373,6 +409,7 @@ export class Disputes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -381,6 +418,7 @@ export class Disputes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -399,30 +437,34 @@ export class Disputes { * evidenceText: "1Z8888888888888888" * }) */ - public async createEvidenceText( + public createEvidenceText( request: Square.CreateDisputeEvidenceTextRequest, requestOptions?: Disputes.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__createEvidenceText(request, requestOptions)); + } + + private async __createEvidenceText( + request: Square.CreateDisputeEvidenceTextRequest, + requestOptions?: Disputes.RequestOptions, + ): Promise> { const { disputeId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/disputes/${encodeURIComponent(disputeId)}/evidence-text`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CreateDisputeEvidenceTextRequest.jsonOrThrow(_body, { @@ -434,19 +476,23 @@ export class Disputes { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateDisputeEvidenceTextResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateDisputeEvidenceTextResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -455,6 +501,7 @@ export class Disputes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -463,6 +510,7 @@ export class Disputes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -484,50 +532,56 @@ export class Disputes { * disputeId: "dispute_id" * }) */ - public async submitEvidence( + public submitEvidence( + request: Square.SubmitEvidenceDisputesRequest, + requestOptions?: Disputes.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__submitEvidence(request, requestOptions)); + } + + private async __submitEvidence( request: Square.SubmitEvidenceDisputesRequest, requestOptions?: Disputes.RequestOptions, - ): Promise { + ): Promise> { const { disputeId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/disputes/${encodeURIComponent(disputeId)}/submit-evidence`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SubmitEvidenceResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SubmitEvidenceResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -536,6 +590,7 @@ export class Disputes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -544,6 +599,7 @@ export class Disputes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/disputes/client/index.ts b/src/api/resources/disputes/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/disputes/client/index.ts +++ b/src/api/resources/disputes/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/disputes/resources/evidence/client/Client.ts b/src/api/resources/disputes/resources/evidence/client/Client.ts index 70b081629..575ac2b2b 100644 --- a/src/api/resources/disputes/resources/evidence/client/Client.ts +++ b/src/api/resources/disputes/resources/evidence/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; import * as errors from "../../../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace Evidence { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Evidence { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Evidence { - constructor(protected readonly _options: Evidence.Options = {}) {} + protected readonly _options: Evidence.Options; + + constructor(_options: Evidence.Options = {}) { + this._options = _options; + } /** * Returns a list of evidence associated with a dispute. @@ -52,74 +58,81 @@ export class Evidence { request: Square.disputes.ListEvidenceRequest, requestOptions?: Evidence.RequestOptions, ): Promise> { - const list = async ( - request: Square.disputes.ListEvidenceRequest, - ): Promise => { - const { disputeId, cursor } = request; - const _queryParams: Record = {}; - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - `v2/disputes/${encodeURIComponent(disputeId)}/evidence`, - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListDisputeEvidenceResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.disputes.ListEvidenceRequest, + ): Promise> => { + const { disputeId, cursor } = request; + const _queryParams: Record = {}; + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + `v2/disputes/${encodeURIComponent(disputeId)}/evidence`, + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListDisputeEvidenceResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/disputes/{dispute_id}/evidence.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/disputes/{dispute_id}/evidence.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.evidence ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -141,50 +154,56 @@ export class Evidence { * evidenceId: "evidence_id" * }) */ - public async get( + public get( + request: Square.disputes.GetEvidenceRequest, + requestOptions?: Evidence.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.disputes.GetEvidenceRequest, requestOptions?: Evidence.RequestOptions, - ): Promise { + ): Promise> { const { disputeId, evidenceId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/disputes/${encodeURIComponent(disputeId)}/evidence/${encodeURIComponent(evidenceId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetDisputeEvidenceResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetDisputeEvidenceResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -193,6 +212,7 @@ export class Evidence { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -201,6 +221,7 @@ export class Evidence { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -218,50 +239,56 @@ export class Evidence { * evidenceId: "evidence_id" * }) */ - public async delete( + public delete( + request: Square.disputes.DeleteEvidenceRequest, + requestOptions?: Evidence.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( request: Square.disputes.DeleteEvidenceRequest, requestOptions?: Evidence.RequestOptions, - ): Promise { + ): Promise> { const { disputeId, evidenceId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/disputes/${encodeURIComponent(disputeId)}/evidence/${encodeURIComponent(evidenceId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteDisputeEvidenceResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteDisputeEvidenceResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -270,6 +297,7 @@ export class Evidence { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -278,6 +306,7 @@ export class Evidence { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/disputes/resources/evidence/client/index.ts b/src/api/resources/disputes/resources/evidence/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/disputes/resources/evidence/client/index.ts +++ b/src/api/resources/disputes/resources/evidence/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/employees/client/Client.ts b/src/api/resources/employees/client/Client.ts index 9cc5f9f99..6018722b1 100644 --- a/src/api/resources/employees/client/Client.ts +++ b/src/api/resources/employees/client/Client.ts @@ -6,7 +6,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as errors from "../../../../errors/index"; export declare namespace Employees { @@ -17,6 +17,8 @@ export declare namespace Employees { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Employees { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Employees { - constructor(protected readonly _options: Employees.Options = {}) {} + protected readonly _options: Employees.Options; + + constructor(_options: Employees.Options = {}) { + this._options = _options; + } /** * @@ -50,82 +56,91 @@ export class Employees { request: Square.ListEmployeesRequest = {}, requestOptions?: Employees.RequestOptions, ): Promise> { - const list = async (request: Square.ListEmployeesRequest): Promise => { - const { locationId, status, limit, cursor } = request; - const _queryParams: Record = {}; - if (locationId !== undefined) { - _queryParams["location_id"] = locationId; - } - if (status !== undefined) { - _queryParams["status"] = serializers.EmployeeStatus.jsonOrThrow(status, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/employees", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListEmployeesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.ListEmployeesRequest, + ): Promise> => { + const { locationId, status, limit, cursor } = request; + const _queryParams: Record = {}; + if (locationId !== undefined) { + _queryParams["location_id"] = locationId; + } + if (status !== undefined) { + _queryParams["status"] = serializers.EmployeeStatus.jsonOrThrow(status, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/employees", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListEmployeesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/employees."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/employees."); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.employees ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -144,50 +159,56 @@ export class Employees { * id: "id" * }) */ - public async get( + public get( + request: Square.GetEmployeesRequest, + requestOptions?: Employees.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.GetEmployeesRequest, requestOptions?: Employees.RequestOptions, - ): Promise { + ): Promise> { const { id } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/employees/${encodeURIComponent(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetEmployeeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetEmployeeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -196,12 +217,14 @@ export class Employees { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/employees/{id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/employees/client/index.ts b/src/api/resources/employees/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/employees/client/index.ts +++ b/src/api/resources/employees/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/events/client/Client.ts b/src/api/resources/events/client/Client.ts index a62c6252b..a6b2b9035 100644 --- a/src/api/resources/events/client/Client.ts +++ b/src/api/resources/events/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../errors/index"; export declare namespace Events { @@ -17,6 +17,8 @@ export declare namespace Events { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Events { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Events { - constructor(protected readonly _options: Events.Options = {}) {} + protected readonly _options: Events.Options; + + constructor(_options: Events.Options = {}) { + this._options = _options; + } /** * Search for Square API events that occur within a 28-day timeframe. @@ -46,29 +52,33 @@ export class Events { * @example * await client.events.searchEvents() */ - public async searchEvents( + public searchEvents( + request: Square.SearchEventsRequest = {}, + requestOptions?: Events.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__searchEvents(request, requestOptions)); + } + + private async __searchEvents( request: Square.SearchEventsRequest = {}, requestOptions?: Events.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/events", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.SearchEventsRequest.jsonOrThrow(request, { @@ -80,19 +90,23 @@ export class Events { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchEventsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchEventsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -101,12 +115,14 @@ export class Events { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/events."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -121,46 +137,53 @@ export class Events { * @example * await client.events.disableEvents() */ - public async disableEvents(requestOptions?: Events.RequestOptions): Promise { + public disableEvents( + requestOptions?: Events.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__disableEvents(requestOptions)); + } + + private async __disableEvents( + requestOptions?: Events.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/events/disable", ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DisableEventsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DisableEventsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -169,12 +192,14 @@ export class Events { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling PUT /v2/events/disable."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -187,46 +212,51 @@ export class Events { * @example * await client.events.enableEvents() */ - public async enableEvents(requestOptions?: Events.RequestOptions): Promise { + public enableEvents(requestOptions?: Events.RequestOptions): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__enableEvents(requestOptions)); + } + + private async __enableEvents( + requestOptions?: Events.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/events/enable", ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.EnableEventsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.EnableEventsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -235,12 +265,14 @@ export class Events { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling PUT /v2/events/enable."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -254,10 +286,17 @@ export class Events { * @example * await client.events.listEventTypes() */ - public async listEventTypes( + public listEventTypes( request: Square.ListEventTypesRequest = {}, requestOptions?: Events.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__listEventTypes(request, requestOptions)); + } + + private async __listEventTypes( + request: Square.ListEventTypesRequest = {}, + requestOptions?: Events.RequestOptions, + ): Promise> { const { apiVersion } = request; const _queryParams: Record = {}; if (apiVersion !== undefined) { @@ -265,45 +304,44 @@ export class Events { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/events/types", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.ListEventTypesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.ListEventTypesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -312,12 +350,14 @@ export class Events { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/events/types."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/events/client/index.ts b/src/api/resources/events/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/events/client/index.ts +++ b/src/api/resources/events/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/giftCards/client/Client.ts b/src/api/resources/giftCards/client/Client.ts index 952a2ca1f..2ba952992 100644 --- a/src/api/resources/giftCards/client/Client.ts +++ b/src/api/resources/giftCards/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; import * as errors from "../../../../errors/index"; import { Activities } from "../resources/activities/client/Client"; @@ -18,6 +18,8 @@ export declare namespace GiftCards { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -31,14 +33,17 @@ export declare namespace GiftCards { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class GiftCards { + protected readonly _options: GiftCards.Options; protected _activities: Activities | undefined; - constructor(protected readonly _options: GiftCards.Options = {}) {} + constructor(_options: GiftCards.Options = {}) { + this._options = _options; + } public get activities(): Activities { return (this._activities ??= new Activities(this._options)); @@ -58,82 +63,91 @@ export class GiftCards { request: Square.ListGiftCardsRequest = {}, requestOptions?: GiftCards.RequestOptions, ): Promise> { - const list = async (request: Square.ListGiftCardsRequest): Promise => { - const { type: type_, state, limit, cursor, customerId } = request; - const _queryParams: Record = {}; - if (type_ !== undefined) { - _queryParams["type"] = type_; - } - if (state !== undefined) { - _queryParams["state"] = state; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (customerId !== undefined) { - _queryParams["customer_id"] = customerId; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/gift-cards", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListGiftCardsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.ListGiftCardsRequest, + ): Promise> => { + const { type: type_, state, limit, cursor, customerId } = request; + const _queryParams: Record = {}; + if (type_ !== undefined) { + _queryParams["type"] = type_; + } + if (state !== undefined) { + _queryParams["state"] = state; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (customerId !== undefined) { + _queryParams["customer_id"] = customerId; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/gift-cards", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListGiftCardsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/gift-cards."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/gift-cards."); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.giftCards ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -160,29 +174,33 @@ export class GiftCards { * } * }) */ - public async create( + public create( + request: Square.CreateGiftCardRequest, + requestOptions?: GiftCards.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( request: Square.CreateGiftCardRequest, requestOptions?: GiftCards.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/gift-cards", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CreateGiftCardRequest.jsonOrThrow(request, { @@ -194,19 +212,23 @@ export class GiftCards { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateGiftCardResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateGiftCardResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -215,12 +237,14 @@ export class GiftCards { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/gift-cards."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -236,29 +260,33 @@ export class GiftCards { * gan: "7783320001001635" * }) */ - public async getFromGan( + public getFromGan( + request: Square.GetGiftCardFromGanRequest, + requestOptions?: GiftCards.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__getFromGan(request, requestOptions)); + } + + private async __getFromGan( request: Square.GetGiftCardFromGanRequest, requestOptions?: GiftCards.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/gift-cards/from-gan", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.GetGiftCardFromGanRequest.jsonOrThrow(request, { @@ -270,19 +298,23 @@ export class GiftCards { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetGiftCardFromGanResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetGiftCardFromGanResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -291,12 +323,14 @@ export class GiftCards { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/gift-cards/from-gan."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -312,29 +346,33 @@ export class GiftCards { * nonce: "cnon:7783322135245171" * }) */ - public async getFromNonce( + public getFromNonce( request: Square.GetGiftCardFromNonceRequest, requestOptions?: GiftCards.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__getFromNonce(request, requestOptions)); + } + + private async __getFromNonce( + request: Square.GetGiftCardFromNonceRequest, + requestOptions?: GiftCards.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/gift-cards/from-nonce", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.GetGiftCardFromNonceRequest.jsonOrThrow(request, { @@ -346,19 +384,23 @@ export class GiftCards { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetGiftCardFromNonceResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetGiftCardFromNonceResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -367,12 +409,14 @@ export class GiftCards { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/gift-cards/from-nonce."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -389,30 +433,34 @@ export class GiftCards { * customerId: "GKY0FZ3V717AH8Q2D821PNT2ZW" * }) */ - public async linkCustomer( + public linkCustomer( request: Square.LinkCustomerToGiftCardRequest, requestOptions?: GiftCards.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__linkCustomer(request, requestOptions)); + } + + private async __linkCustomer( + request: Square.LinkCustomerToGiftCardRequest, + requestOptions?: GiftCards.RequestOptions, + ): Promise> { const { giftCardId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/gift-cards/${encodeURIComponent(giftCardId)}/link-customer`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.LinkCustomerToGiftCardRequest.jsonOrThrow(_body, { @@ -424,19 +472,23 @@ export class GiftCards { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.LinkCustomerToGiftCardResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.LinkCustomerToGiftCardResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -445,6 +497,7 @@ export class GiftCards { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -453,6 +506,7 @@ export class GiftCards { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -469,30 +523,34 @@ export class GiftCards { * customerId: "GKY0FZ3V717AH8Q2D821PNT2ZW" * }) */ - public async unlinkCustomer( + public unlinkCustomer( + request: Square.UnlinkCustomerFromGiftCardRequest, + requestOptions?: GiftCards.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__unlinkCustomer(request, requestOptions)); + } + + private async __unlinkCustomer( request: Square.UnlinkCustomerFromGiftCardRequest, requestOptions?: GiftCards.RequestOptions, - ): Promise { + ): Promise> { const { giftCardId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/gift-cards/${encodeURIComponent(giftCardId)}/unlink-customer`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.UnlinkCustomerFromGiftCardRequest.jsonOrThrow(_body, { @@ -504,19 +562,23 @@ export class GiftCards { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UnlinkCustomerFromGiftCardResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UnlinkCustomerFromGiftCardResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -525,6 +587,7 @@ export class GiftCards { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -533,6 +596,7 @@ export class GiftCards { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -548,50 +612,56 @@ export class GiftCards { * id: "id" * }) */ - public async get( + public get( + request: Square.GetGiftCardsRequest, + requestOptions?: GiftCards.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.GetGiftCardsRequest, requestOptions?: GiftCards.RequestOptions, - ): Promise { + ): Promise> { const { id } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/gift-cards/${encodeURIComponent(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetGiftCardResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetGiftCardResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -600,12 +670,14 @@ export class GiftCards { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/gift-cards/{id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/giftCards/client/index.ts b/src/api/resources/giftCards/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/giftCards/client/index.ts +++ b/src/api/resources/giftCards/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/giftCards/resources/activities/client/Client.ts b/src/api/resources/giftCards/resources/activities/client/Client.ts index e098fb549..8469b264a 100644 --- a/src/api/resources/giftCards/resources/activities/client/Client.ts +++ b/src/api/resources/giftCards/resources/activities/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; import * as errors from "../../../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace Activities { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Activities { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Activities { - constructor(protected readonly _options: Activities.Options = {}) {} + protected readonly _options: Activities.Options; + + constructor(_options: Activities.Options = {}) { + this._options = _options; + } /** * Lists gift card activities. By default, you get gift card activities for all @@ -53,93 +59,102 @@ export class Activities { request: Square.giftCards.ListActivitiesRequest = {}, requestOptions?: Activities.RequestOptions, ): Promise> { - const list = async ( - request: Square.giftCards.ListActivitiesRequest, - ): Promise => { - const { giftCardId, type: type_, locationId, beginTime, endTime, limit, cursor, sortOrder } = request; - const _queryParams: Record = {}; - if (giftCardId !== undefined) { - _queryParams["gift_card_id"] = giftCardId; - } - if (type_ !== undefined) { - _queryParams["type"] = type_; - } - if (locationId !== undefined) { - _queryParams["location_id"] = locationId; - } - if (beginTime !== undefined) { - _queryParams["begin_time"] = beginTime; - } - if (endTime !== undefined) { - _queryParams["end_time"] = endTime; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (sortOrder !== undefined) { - _queryParams["sort_order"] = sortOrder; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/gift-cards/activities", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListGiftCardActivitiesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.giftCards.ListActivitiesRequest, + ): Promise> => { + const { giftCardId, type: type_, locationId, beginTime, endTime, limit, cursor, sortOrder } = request; + const _queryParams: Record = {}; + if (giftCardId !== undefined) { + _queryParams["gift_card_id"] = giftCardId; + } + if (type_ !== undefined) { + _queryParams["type"] = type_; + } + if (locationId !== undefined) { + _queryParams["location_id"] = locationId; + } + if (beginTime !== undefined) { + _queryParams["begin_time"] = beginTime; + } + if (endTime !== undefined) { + _queryParams["end_time"] = endTime; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (sortOrder !== undefined) { + _queryParams["sort_order"] = sortOrder; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/gift-cards/activities", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListGiftCardActivitiesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/gift-cards/activities."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/gift-cards/activities.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.giftCardActivities ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -168,29 +183,33 @@ export class Activities { * } * }) */ - public async create( + public create( request: Square.giftCards.CreateGiftCardActivityRequest, requestOptions?: Activities.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( + request: Square.giftCards.CreateGiftCardActivityRequest, + requestOptions?: Activities.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/gift-cards/activities", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.giftCards.CreateGiftCardActivityRequest.jsonOrThrow(request, { @@ -202,19 +221,23 @@ export class Activities { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateGiftCardActivityResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateGiftCardActivityResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -223,12 +246,14 @@ export class Activities { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/gift-cards/activities."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/giftCards/resources/activities/client/index.ts b/src/api/resources/giftCards/resources/activities/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/giftCards/resources/activities/client/index.ts +++ b/src/api/resources/giftCards/resources/activities/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/inventory/client/Client.ts b/src/api/resources/inventory/client/Client.ts index 7bc9c02c8..6c7f7ab34 100644 --- a/src/api/resources/inventory/client/Client.ts +++ b/src/api/resources/inventory/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; import * as errors from "../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace Inventory { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Inventory { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Inventory { - constructor(protected readonly _options: Inventory.Options = {}) {} + protected readonly _options: Inventory.Options; + + constructor(_options: Inventory.Options = {}) { + this._options = _options; + } /** * Deprecated version of [RetrieveInventoryAdjustment](api-endpoint:Inventory-RetrieveInventoryAdjustment) after the endpoint URL @@ -49,50 +55,56 @@ export class Inventory { * adjustmentId: "adjustment_id" * }) */ - public async deprecatedGetAdjustment( + public deprecatedGetAdjustment( request: Square.DeprecatedGetAdjustmentInventoryRequest, requestOptions?: Inventory.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__deprecatedGetAdjustment(request, requestOptions)); + } + + private async __deprecatedGetAdjustment( + request: Square.DeprecatedGetAdjustmentInventoryRequest, + requestOptions?: Inventory.RequestOptions, + ): Promise> { const { adjustmentId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/inventory/adjustment/${encodeURIComponent(adjustmentId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetInventoryAdjustmentResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetInventoryAdjustmentResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -101,6 +113,7 @@ export class Inventory { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -109,6 +122,7 @@ export class Inventory { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -125,50 +139,56 @@ export class Inventory { * adjustmentId: "adjustment_id" * }) */ - public async getAdjustment( + public getAdjustment( request: Square.GetAdjustmentInventoryRequest, requestOptions?: Inventory.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__getAdjustment(request, requestOptions)); + } + + private async __getAdjustment( + request: Square.GetAdjustmentInventoryRequest, + requestOptions?: Inventory.RequestOptions, + ): Promise> { const { adjustmentId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/inventory/adjustments/${encodeURIComponent(adjustmentId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetInventoryAdjustmentResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetInventoryAdjustmentResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -177,6 +197,7 @@ export class Inventory { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -185,6 +206,7 @@ export class Inventory { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -214,29 +236,33 @@ export class Inventory { * ignoreUnchangedCounts: true * }) */ - public async deprecatedBatchChange( + public deprecatedBatchChange( request: Square.BatchChangeInventoryRequest, requestOptions?: Inventory.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__deprecatedBatchChange(request, requestOptions)); + } + + private async __deprecatedBatchChange( + request: Square.BatchChangeInventoryRequest, + requestOptions?: Inventory.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/inventory/batch-change", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BatchChangeInventoryRequest.jsonOrThrow(request, { @@ -248,19 +274,23 @@ export class Inventory { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BatchChangeInventoryResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BatchChangeInventoryResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -269,12 +299,14 @@ export class Inventory { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/inventory/batch-change."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -296,29 +328,33 @@ export class Inventory { * updatedBefore: "2016-12-01T00:00:00.000Z" * }) */ - public async deprecatedBatchGetChanges( + public deprecatedBatchGetChanges( request: Square.BatchRetrieveInventoryChangesRequest, requestOptions?: Inventory.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__deprecatedBatchGetChanges(request, requestOptions)); + } + + private async __deprecatedBatchGetChanges( + request: Square.BatchRetrieveInventoryChangesRequest, + requestOptions?: Inventory.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/inventory/batch-retrieve-changes", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BatchRetrieveInventoryChangesRequest.jsonOrThrow(request, { @@ -330,19 +366,23 @@ export class Inventory { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BatchGetInventoryChangesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BatchGetInventoryChangesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -351,6 +391,7 @@ export class Inventory { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -359,6 +400,7 @@ export class Inventory { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -377,29 +419,33 @@ export class Inventory { * updatedAfter: "2016-11-16T00:00:00.000Z" * }) */ - public async deprecatedBatchGetCounts( + public deprecatedBatchGetCounts( + request: Square.BatchGetInventoryCountsRequest, + requestOptions?: Inventory.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__deprecatedBatchGetCounts(request, requestOptions)); + } + + private async __deprecatedBatchGetCounts( request: Square.BatchGetInventoryCountsRequest, requestOptions?: Inventory.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/inventory/batch-retrieve-counts", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BatchGetInventoryCountsRequest.jsonOrThrow(request, { @@ -411,19 +457,23 @@ export class Inventory { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BatchGetInventoryCountsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BatchGetInventoryCountsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -432,6 +482,7 @@ export class Inventory { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -440,6 +491,7 @@ export class Inventory { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -472,29 +524,33 @@ export class Inventory { * ignoreUnchangedCounts: true * }) */ - public async batchCreateChanges( + public batchCreateChanges( request: Square.BatchChangeInventoryRequest, requestOptions?: Inventory.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchCreateChanges(request, requestOptions)); + } + + private async __batchCreateChanges( + request: Square.BatchChangeInventoryRequest, + requestOptions?: Inventory.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/inventory/changes/batch-create", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BatchChangeInventoryRequest.jsonOrThrow(request, { @@ -506,19 +562,23 @@ export class Inventory { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BatchChangeInventoryResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BatchChangeInventoryResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -527,6 +587,7 @@ export class Inventory { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -535,6 +596,7 @@ export class Inventory { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -566,72 +628,81 @@ export class Inventory { request: Square.BatchRetrieveInventoryChangesRequest, requestOptions?: Inventory.RequestOptions, ): Promise> { - const list = async ( - request: Square.BatchRetrieveInventoryChangesRequest, - ): Promise => { - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/inventory/changes/batch-retrieve", - ), - method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - body: serializers.BatchRetrieveInventoryChangesRequest.jsonOrThrow(request, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }), - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.BatchGetInventoryChangesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.BatchRetrieveInventoryChangesRequest, + ): Promise> => { + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/inventory/changes/batch-retrieve", + ), + method: "POST", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + contentType: "application/json", + requestType: "json", + body: serializers.BatchRetrieveInventoryChangesRequest.jsonOrThrow(request, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }), + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.BatchGetInventoryChangesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling POST /v2/inventory/changes/batch-retrieve.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, - }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling POST /v2/inventory/changes/batch-retrieve.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.changes ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -666,72 +737,81 @@ export class Inventory { request: Square.BatchGetInventoryCountsRequest, requestOptions?: Inventory.RequestOptions, ): Promise> { - const list = async ( - request: Square.BatchGetInventoryCountsRequest, - ): Promise => { - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/inventory/counts/batch-retrieve", - ), - method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", - body: serializers.BatchGetInventoryCountsRequest.jsonOrThrow(request, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }), - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.BatchGetInventoryCountsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.BatchGetInventoryCountsRequest, + ): Promise> => { + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/inventory/counts/batch-retrieve", + ), + method: "POST", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + contentType: "application/json", + requestType: "json", + body: serializers.BatchGetInventoryCountsRequest.jsonOrThrow(request, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }), + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.BatchGetInventoryCountsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling POST /v2/inventory/counts/batch-retrieve.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling POST /v2/inventory/counts/batch-retrieve.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.counts ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -751,50 +831,56 @@ export class Inventory { * physicalCountId: "physical_count_id" * }) */ - public async deprecatedGetPhysicalCount( + public deprecatedGetPhysicalCount( + request: Square.DeprecatedGetPhysicalCountInventoryRequest, + requestOptions?: Inventory.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__deprecatedGetPhysicalCount(request, requestOptions)); + } + + private async __deprecatedGetPhysicalCount( request: Square.DeprecatedGetPhysicalCountInventoryRequest, requestOptions?: Inventory.RequestOptions, - ): Promise { + ): Promise> { const { physicalCountId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/inventory/physical-count/${encodeURIComponent(physicalCountId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetInventoryPhysicalCountResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetInventoryPhysicalCountResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -803,6 +889,7 @@ export class Inventory { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -811,6 +898,7 @@ export class Inventory { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -827,50 +915,56 @@ export class Inventory { * physicalCountId: "physical_count_id" * }) */ - public async getPhysicalCount( + public getPhysicalCount( + request: Square.GetPhysicalCountInventoryRequest, + requestOptions?: Inventory.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__getPhysicalCount(request, requestOptions)); + } + + private async __getPhysicalCount( request: Square.GetPhysicalCountInventoryRequest, requestOptions?: Inventory.RequestOptions, - ): Promise { + ): Promise> { const { physicalCountId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/inventory/physical-counts/${encodeURIComponent(physicalCountId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetInventoryPhysicalCountResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetInventoryPhysicalCountResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -879,6 +973,7 @@ export class Inventory { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -887,6 +982,7 @@ export class Inventory { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -903,50 +999,56 @@ export class Inventory { * transferId: "transfer_id" * }) */ - public async getTransfer( + public getTransfer( request: Square.GetTransferInventoryRequest, requestOptions?: Inventory.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__getTransfer(request, requestOptions)); + } + + private async __getTransfer( + request: Square.GetTransferInventoryRequest, + requestOptions?: Inventory.RequestOptions, + ): Promise> { const { transferId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/inventory/transfers/${encodeURIComponent(transferId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetInventoryTransferResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetInventoryTransferResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -955,6 +1057,7 @@ export class Inventory { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -963,6 +1066,7 @@ export class Inventory { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -985,75 +1089,84 @@ export class Inventory { request: Square.GetInventoryRequest, requestOptions?: Inventory.RequestOptions, ): Promise> { - const list = async (request: Square.GetInventoryRequest): Promise => { - const { catalogObjectId, locationIds, cursor } = request; - const _queryParams: Record = {}; - if (locationIds !== undefined) { - _queryParams["location_ids"] = locationIds; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - `v2/inventory/${encodeURIComponent(catalogObjectId)}`, - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.GetInventoryCountResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.GetInventoryRequest, + ): Promise> => { + const { catalogObjectId, locationIds, cursor } = request; + const _queryParams: Record = {}; + if (locationIds !== undefined) { + _queryParams["location_ids"] = locationIds; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + `v2/inventory/${encodeURIComponent(catalogObjectId)}`, + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.GetInventoryCountResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/inventory/{catalog_object_id}.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/inventory/{catalog_object_id}.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.counts ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -1088,75 +1201,84 @@ export class Inventory { request: Square.ChangesInventoryRequest, requestOptions?: Inventory.RequestOptions, ): Promise> { - const list = async (request: Square.ChangesInventoryRequest): Promise => { - const { catalogObjectId, locationIds, cursor } = request; - const _queryParams: Record = {}; - if (locationIds !== undefined) { - _queryParams["location_ids"] = locationIds; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - `v2/inventory/${encodeURIComponent(catalogObjectId)}/changes`, - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.GetInventoryChangesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.ChangesInventoryRequest, + ): Promise> => { + const { catalogObjectId, locationIds, cursor } = request; + const _queryParams: Record = {}; + if (locationIds !== undefined) { + _queryParams["location_ids"] = locationIds; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + `v2/inventory/${encodeURIComponent(catalogObjectId)}/changes`, + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.GetInventoryChangesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/inventory/{catalog_object_id}/changes.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, - }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/inventory/{catalog_object_id}/changes.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.changes ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); diff --git a/src/api/resources/inventory/client/index.ts b/src/api/resources/inventory/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/inventory/client/index.ts +++ b/src/api/resources/inventory/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/invoices/client/Client.ts b/src/api/resources/invoices/client/Client.ts index 0e2531820..4ce718a9f 100644 --- a/src/api/resources/invoices/client/Client.ts +++ b/src/api/resources/invoices/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; import * as errors from "../../../../errors/index"; import { toJson } from "../../../../core/json"; @@ -18,6 +18,8 @@ export declare namespace Invoices { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -31,12 +33,16 @@ export declare namespace Invoices { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Invoices { - constructor(protected readonly _options: Invoices.Options = {}) {} + protected readonly _options: Invoices.Options; + + constructor(_options: Invoices.Options = {}) { + this._options = _options; + } /** * Returns a list of invoices for a given location. The response @@ -55,74 +61,81 @@ export class Invoices { request: Square.ListInvoicesRequest, requestOptions?: Invoices.RequestOptions, ): Promise> { - const list = async (request: Square.ListInvoicesRequest): Promise => { - const { locationId, cursor, limit } = request; - const _queryParams: Record = {}; - _queryParams["location_id"] = locationId; - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/invoices", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListInvoicesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], + const list = core.HttpResponsePromise.interceptFunction( + async (request: Square.ListInvoicesRequest): Promise> => { + const { locationId, cursor, limit } = request; + const _queryParams: Record = {}; + _queryParams["location_id"] = locationId; + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/invoices", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListInvoicesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/invoices."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, - }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/invoices."); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.invoices ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -185,29 +198,33 @@ export class Invoices { * idempotencyKey: "ce3748f9-5fc1-4762-aa12-aae5e843f1f4" * }) */ - public async create( + public create( request: Square.CreateInvoiceRequest, requestOptions?: Invoices.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( + request: Square.CreateInvoiceRequest, + requestOptions?: Invoices.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/invoices", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CreateInvoiceRequest.jsonOrThrow(request, { @@ -219,19 +236,23 @@ export class Invoices { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateInvoiceResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateInvoiceResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -240,12 +261,14 @@ export class Invoices { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/invoices."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -277,29 +300,33 @@ export class Invoices { * limit: 100 * }) */ - public async search( + public search( + request: Square.SearchInvoicesRequest, + requestOptions?: Invoices.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__search(request, requestOptions)); + } + + private async __search( request: Square.SearchInvoicesRequest, requestOptions?: Invoices.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/invoices/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.SearchInvoicesRequest.jsonOrThrow(request, { @@ -311,19 +338,23 @@ export class Invoices { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchInvoicesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchInvoicesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -332,12 +363,14 @@ export class Invoices { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/invoices/search."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -353,50 +386,56 @@ export class Invoices { * invoiceId: "invoice_id" * }) */ - public async get( + public get( + request: Square.GetInvoicesRequest, + requestOptions?: Invoices.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.GetInvoicesRequest, requestOptions?: Invoices.RequestOptions, - ): Promise { + ): Promise> { const { invoiceId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/invoices/${encodeURIComponent(invoiceId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetInvoiceResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetInvoiceResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -405,12 +444,14 @@ export class Invoices { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/invoices/{invoice_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -437,30 +478,34 @@ export class Invoices { * idempotencyKey: "4ee82288-0910-499e-ab4c-5d0071dad1be" * }) */ - public async update( + public update( request: Square.UpdateInvoiceRequest, requestOptions?: Invoices.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( + request: Square.UpdateInvoiceRequest, + requestOptions?: Invoices.RequestOptions, + ): Promise> { const { invoiceId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/invoices/${encodeURIComponent(invoiceId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.UpdateInvoiceRequest.jsonOrThrow(_body, { @@ -472,19 +517,23 @@ export class Invoices { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateInvoiceResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateInvoiceResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -493,12 +542,14 @@ export class Invoices { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling PUT /v2/invoices/{invoice_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -516,10 +567,17 @@ export class Invoices { * invoiceId: "invoice_id" * }) */ - public async delete( + public delete( request: Square.DeleteInvoicesRequest, requestOptions?: Invoices.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( + request: Square.DeleteInvoicesRequest, + requestOptions?: Invoices.RequestOptions, + ): Promise> { const { invoiceId, version } = request; const _queryParams: Record = {}; if (version !== undefined) { @@ -527,45 +585,44 @@ export class Invoices { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/invoices/${encodeURIComponent(invoiceId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteInvoiceResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteInvoiceResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -574,12 +631,14 @@ export class Invoices { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling DELETE /v2/invoices/{invoice_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -602,10 +661,17 @@ export class Invoices { * invoiceId: "invoice_id" * }) */ - public async createInvoiceAttachment( + public createInvoiceAttachment( request: Square.CreateInvoiceAttachmentRequest, requestOptions?: Invoices.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__createInvoiceAttachment(request, requestOptions)); + } + + private async __createInvoiceAttachment( + request: Square.CreateInvoiceAttachmentRequest, + requestOptions?: Invoices.RequestOptions, + ): Promise> { const _request = await core.newFormData(); if (request.request != null) { _request.append( @@ -625,25 +691,22 @@ export class Invoices { const _maybeEncodedRequest = await _request.getRequest(); const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/invoices/${encodeURIComponent(request.invoiceId)}/attachments`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ..._maybeEncodedRequest.headers, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + ..._maybeEncodedRequest.headers, + }), + requestOptions?.headers, + ), requestType: "file", duplex: _maybeEncodedRequest.duplex, body: _maybeEncodedRequest.body, @@ -652,19 +715,23 @@ export class Invoices { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateInvoiceAttachmentResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateInvoiceAttachmentResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -673,6 +740,7 @@ export class Invoices { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -681,6 +749,7 @@ export class Invoices { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -698,50 +767,56 @@ export class Invoices { * attachmentId: "attachment_id" * }) */ - public async deleteInvoiceAttachment( + public deleteInvoiceAttachment( + request: Square.DeleteInvoiceAttachmentRequest, + requestOptions?: Invoices.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__deleteInvoiceAttachment(request, requestOptions)); + } + + private async __deleteInvoiceAttachment( request: Square.DeleteInvoiceAttachmentRequest, requestOptions?: Invoices.RequestOptions, - ): Promise { + ): Promise> { const { invoiceId, attachmentId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/invoices/${encodeURIComponent(invoiceId)}/attachments/${encodeURIComponent(attachmentId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteInvoiceAttachmentResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteInvoiceAttachmentResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -750,6 +825,7 @@ export class Invoices { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -758,6 +834,7 @@ export class Invoices { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -777,30 +854,34 @@ export class Invoices { * version: 0 * }) */ - public async cancel( + public cancel( request: Square.CancelInvoiceRequest, requestOptions?: Invoices.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__cancel(request, requestOptions)); + } + + private async __cancel( + request: Square.CancelInvoiceRequest, + requestOptions?: Invoices.RequestOptions, + ): Promise> { const { invoiceId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/invoices/${encodeURIComponent(invoiceId)}/cancel`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CancelInvoiceRequest.jsonOrThrow(_body, { @@ -812,19 +893,23 @@ export class Invoices { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CancelInvoiceResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CancelInvoiceResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -833,6 +918,7 @@ export class Invoices { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -841,6 +927,7 @@ export class Invoices { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -871,30 +958,34 @@ export class Invoices { * idempotencyKey: "32da42d0-1997-41b0-826b-f09464fc2c2e" * }) */ - public async publish( + public publish( request: Square.PublishInvoiceRequest, requestOptions?: Invoices.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__publish(request, requestOptions)); + } + + private async __publish( + request: Square.PublishInvoiceRequest, + requestOptions?: Invoices.RequestOptions, + ): Promise> { const { invoiceId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/invoices/${encodeURIComponent(invoiceId)}/publish`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.PublishInvoiceRequest.jsonOrThrow(_body, { @@ -906,19 +997,23 @@ export class Invoices { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.PublishInvoiceResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.PublishInvoiceResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -927,6 +1022,7 @@ export class Invoices { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -935,6 +1031,7 @@ export class Invoices { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/invoices/client/index.ts b/src/api/resources/invoices/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/invoices/client/index.ts +++ b/src/api/resources/invoices/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/labor/client/Client.ts b/src/api/resources/labor/client/Client.ts index 231c4c58e..5e2289f41 100644 --- a/src/api/resources/labor/client/Client.ts +++ b/src/api/resources/labor/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../errors/index"; import { BreakTypes } from "../resources/breakTypes/client/Client"; import { EmployeeWages } from "../resources/employeeWages/client/Client"; @@ -22,6 +22,8 @@ export declare namespace Labor { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -35,18 +37,21 @@ export declare namespace Labor { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Labor { + protected readonly _options: Labor.Options; protected _breakTypes: BreakTypes | undefined; protected _employeeWages: EmployeeWages | undefined; protected _shifts: Shifts | undefined; protected _teamMemberWages: TeamMemberWages | undefined; protected _workweekConfigs: WorkweekConfigs | undefined; - constructor(protected readonly _options: Labor.Options = {}) {} + constructor(_options: Labor.Options = {}) { + this._options = _options; + } public get breakTypes(): BreakTypes { return (this._breakTypes ??= new BreakTypes(this._options)); @@ -97,29 +102,33 @@ export class Labor { * } * }) */ - public async createScheduledShift( + public createScheduledShift( + request: Square.CreateScheduledShiftRequest, + requestOptions?: Labor.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__createScheduledShift(request, requestOptions)); + } + + private async __createScheduledShift( request: Square.CreateScheduledShiftRequest, requestOptions?: Labor.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/labor/scheduled-shifts", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CreateScheduledShiftRequest.jsonOrThrow(request, { @@ -131,19 +140,23 @@ export class Labor { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateScheduledShiftResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateScheduledShiftResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -152,12 +165,14 @@ export class Labor { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/labor/scheduled-shifts."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -181,29 +196,33 @@ export class Labor { * scheduledShiftNotificationAudience: "AFFECTED" * }) */ - public async bulkPublishScheduledShifts( + public bulkPublishScheduledShifts( request: Square.BulkPublishScheduledShiftsRequest, requestOptions?: Labor.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__bulkPublishScheduledShifts(request, requestOptions)); + } + + private async __bulkPublishScheduledShifts( + request: Square.BulkPublishScheduledShiftsRequest, + requestOptions?: Labor.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/labor/scheduled-shifts/bulk-publish", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BulkPublishScheduledShiftsRequest.jsonOrThrow(request, { @@ -215,19 +234,23 @@ export class Labor { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BulkPublishScheduledShiftsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BulkPublishScheduledShiftsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -236,6 +259,7 @@ export class Labor { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -244,6 +268,7 @@ export class Labor { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -270,29 +295,33 @@ export class Labor { * cursor: "xoxp-1234-5678-90123" * }) */ - public async searchScheduledShifts( + public searchScheduledShifts( request: Square.SearchScheduledShiftsRequest = {}, requestOptions?: Labor.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__searchScheduledShifts(request, requestOptions)); + } + + private async __searchScheduledShifts( + request: Square.SearchScheduledShiftsRequest = {}, + requestOptions?: Labor.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/labor/scheduled-shifts/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.SearchScheduledShiftsRequest.jsonOrThrow(request, { @@ -304,19 +333,23 @@ export class Labor { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchScheduledShiftsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchScheduledShiftsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -325,6 +358,7 @@ export class Labor { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -333,6 +367,7 @@ export class Labor { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -348,50 +383,56 @@ export class Labor { * id: "id" * }) */ - public async retrieveScheduledShift( + public retrieveScheduledShift( request: Square.RetrieveScheduledShiftRequest, requestOptions?: Labor.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__retrieveScheduledShift(request, requestOptions)); + } + + private async __retrieveScheduledShift( + request: Square.RetrieveScheduledShiftRequest, + requestOptions?: Labor.RequestOptions, + ): Promise> { const { id } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/labor/scheduled-shifts/${encodeURIComponent(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RetrieveScheduledShiftResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RetrieveScheduledShiftResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -400,6 +441,7 @@ export class Labor { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -408,6 +450,7 @@ export class Labor { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -444,30 +487,34 @@ export class Labor { * } * }) */ - public async updateScheduledShift( + public updateScheduledShift( + request: Square.UpdateScheduledShiftRequest, + requestOptions?: Labor.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__updateScheduledShift(request, requestOptions)); + } + + private async __updateScheduledShift( request: Square.UpdateScheduledShiftRequest, requestOptions?: Labor.RequestOptions, - ): Promise { + ): Promise> { const { id, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/labor/scheduled-shifts/${encodeURIComponent(id)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.UpdateScheduledShiftRequest.jsonOrThrow(_body, { @@ -479,19 +526,23 @@ export class Labor { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateScheduledShiftResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateScheduledShiftResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -500,6 +551,7 @@ export class Labor { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -508,6 +560,7 @@ export class Labor { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -527,30 +580,34 @@ export class Labor { * scheduledShiftNotificationAudience: "ALL" * }) */ - public async publishScheduledShift( + public publishScheduledShift( + request: Square.PublishScheduledShiftRequest, + requestOptions?: Labor.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__publishScheduledShift(request, requestOptions)); + } + + private async __publishScheduledShift( request: Square.PublishScheduledShiftRequest, requestOptions?: Labor.RequestOptions, - ): Promise { + ): Promise> { const { id, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/labor/scheduled-shifts/${encodeURIComponent(id)}/publish`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.PublishScheduledShiftRequest.jsonOrThrow(_body, { @@ -562,19 +619,23 @@ export class Labor { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.PublishScheduledShiftResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.PublishScheduledShiftResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -583,6 +644,7 @@ export class Labor { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -591,6 +653,7 @@ export class Labor { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -628,7 +691,7 @@ export class Labor { * wage: { * title: "Barista", * hourlyRate: { - * amount: 1100, + * amount: BigInt("1100"), * currency: "USD" * }, * tipEligible: true @@ -643,35 +706,39 @@ export class Labor { * }], * teamMemberId: "ormj0jJJZ5OZIzxrZYJI", * declaredCashTipMoney: { - * amount: 500, + * amount: BigInt("500"), * currency: "USD" * } * } * }) */ - public async createTimecard( + public createTimecard( request: Square.CreateTimecardRequest, requestOptions?: Labor.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__createTimecard(request, requestOptions)); + } + + private async __createTimecard( + request: Square.CreateTimecardRequest, + requestOptions?: Labor.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/labor/timecards", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CreateTimecardRequest.jsonOrThrow(request, { @@ -683,19 +750,23 @@ export class Labor { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateTimecardResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateTimecardResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -704,12 +775,14 @@ export class Labor { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/labor/timecards."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -750,29 +823,33 @@ export class Labor { * limit: 100 * }) */ - public async searchTimecards( + public searchTimecards( + request: Square.SearchTimecardsRequest = {}, + requestOptions?: Labor.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__searchTimecards(request, requestOptions)); + } + + private async __searchTimecards( request: Square.SearchTimecardsRequest = {}, requestOptions?: Labor.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/labor/timecards/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.SearchTimecardsRequest.jsonOrThrow(request, { @@ -784,19 +861,23 @@ export class Labor { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchTimecardsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchTimecardsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -805,12 +886,14 @@ export class Labor { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/labor/timecards/search."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -826,50 +909,56 @@ export class Labor { * id: "id" * }) */ - public async retrieveTimecard( + public retrieveTimecard( + request: Square.RetrieveTimecardRequest, + requestOptions?: Labor.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__retrieveTimecard(request, requestOptions)); + } + + private async __retrieveTimecard( request: Square.RetrieveTimecardRequest, requestOptions?: Labor.RequestOptions, - ): Promise { + ): Promise> { const { id } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/labor/timecards/${encodeURIComponent(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RetrieveTimecardResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RetrieveTimecardResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -878,12 +967,14 @@ export class Labor { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/labor/timecards/{id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -910,7 +1001,7 @@ export class Labor { * wage: { * title: "Bartender", * hourlyRate: { - * amount: 1500, + * amount: BigInt("1500"), * currency: "USD" * }, * tipEligible: true @@ -928,36 +1019,40 @@ export class Labor { * version: 1, * teamMemberId: "ormj0jJJZ5OZIzxrZYJI", * declaredCashTipMoney: { - * amount: 500, + * amount: BigInt("500"), * currency: "USD" * } * } * }) */ - public async updateTimecard( + public updateTimecard( request: Square.UpdateTimecardRequest, requestOptions?: Labor.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__updateTimecard(request, requestOptions)); + } + + private async __updateTimecard( + request: Square.UpdateTimecardRequest, + requestOptions?: Labor.RequestOptions, + ): Promise> { const { id, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/labor/timecards/${encodeURIComponent(id)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.UpdateTimecardRequest.jsonOrThrow(_body, { @@ -969,19 +1064,23 @@ export class Labor { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateTimecardResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateTimecardResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -990,12 +1089,14 @@ export class Labor { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling PUT /v2/labor/timecards/{id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -1011,50 +1112,56 @@ export class Labor { * id: "id" * }) */ - public async deleteTimecard( + public deleteTimecard( + request: Square.DeleteTimecardRequest, + requestOptions?: Labor.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__deleteTimecard(request, requestOptions)); + } + + private async __deleteTimecard( request: Square.DeleteTimecardRequest, requestOptions?: Labor.RequestOptions, - ): Promise { + ): Promise> { const { id } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/labor/timecards/${encodeURIComponent(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteTimecardResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteTimecardResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -1063,12 +1170,14 @@ export class Labor { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling DELETE /v2/labor/timecards/{id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/labor/client/index.ts b/src/api/resources/labor/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/labor/client/index.ts +++ b/src/api/resources/labor/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/labor/client/requests/CreateTimecardRequest.ts b/src/api/resources/labor/client/requests/CreateTimecardRequest.ts index 27fb8ebbf..1e70da741 100644 --- a/src/api/resources/labor/client/requests/CreateTimecardRequest.ts +++ b/src/api/resources/labor/client/requests/CreateTimecardRequest.ts @@ -15,7 +15,7 @@ import * as Square from "../../../../index"; * wage: { * title: "Barista", * hourlyRate: { - * amount: 1100, + * amount: BigInt("1100"), * currency: "USD" * }, * tipEligible: true @@ -30,7 +30,7 @@ import * as Square from "../../../../index"; * }], * teamMemberId: "ormj0jJJZ5OZIzxrZYJI", * declaredCashTipMoney: { - * amount: 500, + * amount: BigInt("500"), * currency: "USD" * } * } diff --git a/src/api/resources/labor/client/requests/UpdateTimecardRequest.ts b/src/api/resources/labor/client/requests/UpdateTimecardRequest.ts index 2dd76467d..c9ffafaae 100644 --- a/src/api/resources/labor/client/requests/UpdateTimecardRequest.ts +++ b/src/api/resources/labor/client/requests/UpdateTimecardRequest.ts @@ -15,7 +15,7 @@ import * as Square from "../../../../index"; * wage: { * title: "Bartender", * hourlyRate: { - * amount: 1500, + * amount: BigInt("1500"), * currency: "USD" * }, * tipEligible: true @@ -33,7 +33,7 @@ import * as Square from "../../../../index"; * version: 1, * teamMemberId: "ormj0jJJZ5OZIzxrZYJI", * declaredCashTipMoney: { - * amount: 500, + * amount: BigInt("500"), * currency: "USD" * } * } diff --git a/src/api/resources/labor/resources/breakTypes/client/Client.ts b/src/api/resources/labor/resources/breakTypes/client/Client.ts index a6b51ee7a..6f11dc3d5 100644 --- a/src/api/resources/labor/resources/breakTypes/client/Client.ts +++ b/src/api/resources/labor/resources/breakTypes/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; import * as errors from "../../../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace BreakTypes { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace BreakTypes { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class BreakTypes { - constructor(protected readonly _options: BreakTypes.Options = {}) {} + protected readonly _options: BreakTypes.Options; + + constructor(_options: BreakTypes.Options = {}) { + this._options = _options; + } /** * Returns a paginated list of `BreakType` instances for a business. @@ -50,76 +56,85 @@ export class BreakTypes { request: Square.labor.ListBreakTypesRequest = {}, requestOptions?: BreakTypes.RequestOptions, ): Promise> { - const list = async (request: Square.labor.ListBreakTypesRequest): Promise => { - const { locationId, limit, cursor } = request; - const _queryParams: Record = {}; - if (locationId !== undefined) { - _queryParams["location_id"] = locationId; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/labor/break-types", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListBreakTypesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.labor.ListBreakTypesRequest, + ): Promise> => { + const { locationId, limit, cursor } = request; + const _queryParams: Record = {}; + if (locationId !== undefined) { + _queryParams["location_id"] = locationId; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/labor/break-types", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListBreakTypesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/labor/break-types."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/labor/break-types."); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.breakTypes ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -157,29 +172,33 @@ export class BreakTypes { * } * }) */ - public async create( + public create( + request: Square.labor.CreateBreakTypeRequest, + requestOptions?: BreakTypes.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( request: Square.labor.CreateBreakTypeRequest, requestOptions?: BreakTypes.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/labor/break-types", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.labor.CreateBreakTypeRequest.jsonOrThrow(request, { @@ -191,19 +210,23 @@ export class BreakTypes { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateBreakTypeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateBreakTypeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -212,12 +235,14 @@ export class BreakTypes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/labor/break-types."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -233,50 +258,56 @@ export class BreakTypes { * id: "id" * }) */ - public async get( + public get( + request: Square.labor.GetBreakTypesRequest, + requestOptions?: BreakTypes.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.labor.GetBreakTypesRequest, requestOptions?: BreakTypes.RequestOptions, - ): Promise { + ): Promise> { const { id } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/labor/break-types/${encodeURIComponent(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetBreakTypeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetBreakTypeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -285,12 +316,14 @@ export class BreakTypes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/labor/break-types/{id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -313,30 +346,34 @@ export class BreakTypes { * } * }) */ - public async update( + public update( + request: Square.labor.UpdateBreakTypeRequest, + requestOptions?: BreakTypes.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( request: Square.labor.UpdateBreakTypeRequest, requestOptions?: BreakTypes.RequestOptions, - ): Promise { + ): Promise> { const { id, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/labor/break-types/${encodeURIComponent(id)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.labor.UpdateBreakTypeRequest.jsonOrThrow(_body, { @@ -348,19 +385,23 @@ export class BreakTypes { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateBreakTypeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateBreakTypeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -369,12 +410,14 @@ export class BreakTypes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling PUT /v2/labor/break-types/{id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -392,50 +435,56 @@ export class BreakTypes { * id: "id" * }) */ - public async delete( + public delete( request: Square.labor.DeleteBreakTypesRequest, requestOptions?: BreakTypes.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( + request: Square.labor.DeleteBreakTypesRequest, + requestOptions?: BreakTypes.RequestOptions, + ): Promise> { const { id } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/labor/break-types/${encodeURIComponent(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteBreakTypeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteBreakTypeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -444,12 +493,14 @@ export class BreakTypes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling DELETE /v2/labor/break-types/{id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/labor/resources/breakTypes/client/index.ts b/src/api/resources/labor/resources/breakTypes/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/labor/resources/breakTypes/client/index.ts +++ b/src/api/resources/labor/resources/breakTypes/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/labor/resources/employeeWages/client/Client.ts b/src/api/resources/labor/resources/employeeWages/client/Client.ts index ec461c6e0..f4ffaf630 100644 --- a/src/api/resources/labor/resources/employeeWages/client/Client.ts +++ b/src/api/resources/labor/resources/employeeWages/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; import * as errors from "../../../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace EmployeeWages { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace EmployeeWages { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class EmployeeWages { - constructor(protected readonly _options: EmployeeWages.Options = {}) {} + protected readonly _options: EmployeeWages.Options; + + constructor(_options: EmployeeWages.Options = {}) { + this._options = _options; + } /** * Returns a paginated list of `EmployeeWage` instances for a business. @@ -50,78 +56,87 @@ export class EmployeeWages { request: Square.labor.ListEmployeeWagesRequest = {}, requestOptions?: EmployeeWages.RequestOptions, ): Promise> { - const list = async ( - request: Square.labor.ListEmployeeWagesRequest, - ): Promise => { - const { employeeId, limit, cursor } = request; - const _queryParams: Record = {}; - if (employeeId !== undefined) { - _queryParams["employee_id"] = employeeId; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/labor/employee-wages", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListEmployeeWagesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.labor.ListEmployeeWagesRequest, + ): Promise> => { + const { employeeId, limit, cursor } = request; + const _queryParams: Record = {}; + if (employeeId !== undefined) { + _queryParams["employee_id"] = employeeId; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/labor/employee-wages", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListEmployeeWagesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/labor/employee-wages."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/labor/employee-wages.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.employeeWages ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -140,50 +155,56 @@ export class EmployeeWages { * id: "id" * }) */ - public async get( + public get( request: Square.labor.GetEmployeeWagesRequest, requestOptions?: EmployeeWages.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.labor.GetEmployeeWagesRequest, + requestOptions?: EmployeeWages.RequestOptions, + ): Promise> { const { id } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/labor/employee-wages/${encodeURIComponent(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetEmployeeWageResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetEmployeeWageResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -192,12 +213,14 @@ export class EmployeeWages { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/labor/employee-wages/{id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/labor/resources/employeeWages/client/index.ts b/src/api/resources/labor/resources/employeeWages/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/labor/resources/employeeWages/client/index.ts +++ b/src/api/resources/labor/resources/employeeWages/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/labor/resources/shifts/client/Client.ts b/src/api/resources/labor/resources/shifts/client/Client.ts index c2dd3a5f5..fe3690188 100644 --- a/src/api/resources/labor/resources/shifts/client/Client.ts +++ b/src/api/resources/labor/resources/shifts/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../../../errors/index"; export declare namespace Shifts { @@ -17,6 +17,8 @@ export declare namespace Shifts { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Shifts { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Shifts { - constructor(protected readonly _options: Shifts.Options = {}) {} + protected readonly _options: Shifts.Options; + + constructor(_options: Shifts.Options = {}) { + this._options = _options; + } /** * Creates a new `Shift`. @@ -70,7 +76,7 @@ export class Shifts { * wage: { * title: "Barista", * hourlyRate: { - * amount: 1100, + * amount: BigInt("1100"), * currency: "USD" * }, * tipEligible: true @@ -85,35 +91,39 @@ export class Shifts { * }], * teamMemberId: "ormj0jJJZ5OZIzxrZYJI", * declaredCashTipMoney: { - * amount: 500, + * amount: BigInt("500"), * currency: "USD" * } * } * }) */ - public async create( + public create( request: Square.labor.CreateShiftRequest, requestOptions?: Shifts.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( + request: Square.labor.CreateShiftRequest, + requestOptions?: Shifts.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/labor/shifts", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.labor.CreateShiftRequest.jsonOrThrow(request, { @@ -125,19 +135,23 @@ export class Shifts { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateShiftResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateShiftResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -146,12 +160,14 @@ export class Shifts { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/labor/shifts."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -192,29 +208,33 @@ export class Shifts { * limit: 100 * }) */ - public async search( + public search( + request: Square.labor.SearchShiftsRequest = {}, + requestOptions?: Shifts.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__search(request, requestOptions)); + } + + private async __search( request: Square.labor.SearchShiftsRequest = {}, requestOptions?: Shifts.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/labor/shifts/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.labor.SearchShiftsRequest.jsonOrThrow(request, { @@ -226,19 +246,23 @@ export class Shifts { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchShiftsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchShiftsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -247,12 +271,14 @@ export class Shifts { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/labor/shifts/search."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -268,50 +294,56 @@ export class Shifts { * id: "id" * }) */ - public async get( + public get( + request: Square.labor.GetShiftsRequest, + requestOptions?: Shifts.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.labor.GetShiftsRequest, requestOptions?: Shifts.RequestOptions, - ): Promise { + ): Promise> { const { id } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/labor/shifts/${encodeURIComponent(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetShiftResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetShiftResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -320,12 +352,14 @@ export class Shifts { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/labor/shifts/{id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -352,7 +386,7 @@ export class Shifts { * wage: { * title: "Bartender", * hourlyRate: { - * amount: 1500, + * amount: BigInt("1500"), * currency: "USD" * }, * tipEligible: true @@ -369,36 +403,40 @@ export class Shifts { * version: 1, * teamMemberId: "ormj0jJJZ5OZIzxrZYJI", * declaredCashTipMoney: { - * amount: 500, + * amount: BigInt("500"), * currency: "USD" * } * } * }) */ - public async update( + public update( request: Square.labor.UpdateShiftRequest, requestOptions?: Shifts.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( + request: Square.labor.UpdateShiftRequest, + requestOptions?: Shifts.RequestOptions, + ): Promise> { const { id, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/labor/shifts/${encodeURIComponent(id)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.labor.UpdateShiftRequest.jsonOrThrow(_body, { @@ -410,19 +448,23 @@ export class Shifts { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateShiftResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateShiftResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -431,12 +473,14 @@ export class Shifts { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling PUT /v2/labor/shifts/{id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -452,50 +496,56 @@ export class Shifts { * id: "id" * }) */ - public async delete( + public delete( + request: Square.labor.DeleteShiftsRequest, + requestOptions?: Shifts.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( request: Square.labor.DeleteShiftsRequest, requestOptions?: Shifts.RequestOptions, - ): Promise { + ): Promise> { const { id } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/labor/shifts/${encodeURIComponent(id)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteShiftResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteShiftResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -504,12 +554,14 @@ export class Shifts { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling DELETE /v2/labor/shifts/{id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/labor/resources/shifts/client/index.ts b/src/api/resources/labor/resources/shifts/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/labor/resources/shifts/client/index.ts +++ b/src/api/resources/labor/resources/shifts/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/labor/resources/shifts/client/requests/CreateShiftRequest.ts b/src/api/resources/labor/resources/shifts/client/requests/CreateShiftRequest.ts index c887a2938..6c258c04a 100644 --- a/src/api/resources/labor/resources/shifts/client/requests/CreateShiftRequest.ts +++ b/src/api/resources/labor/resources/shifts/client/requests/CreateShiftRequest.ts @@ -15,7 +15,7 @@ import * as Square from "../../../../../../index"; * wage: { * title: "Barista", * hourlyRate: { - * amount: 1100, + * amount: BigInt("1100"), * currency: "USD" * }, * tipEligible: true @@ -30,7 +30,7 @@ import * as Square from "../../../../../../index"; * }], * teamMemberId: "ormj0jJJZ5OZIzxrZYJI", * declaredCashTipMoney: { - * amount: 500, + * amount: BigInt("500"), * currency: "USD" * } * } diff --git a/src/api/resources/labor/resources/shifts/client/requests/UpdateShiftRequest.ts b/src/api/resources/labor/resources/shifts/client/requests/UpdateShiftRequest.ts index cb078e7b0..e14a46844 100644 --- a/src/api/resources/labor/resources/shifts/client/requests/UpdateShiftRequest.ts +++ b/src/api/resources/labor/resources/shifts/client/requests/UpdateShiftRequest.ts @@ -15,7 +15,7 @@ import * as Square from "../../../../../../index"; * wage: { * title: "Bartender", * hourlyRate: { - * amount: 1500, + * amount: BigInt("1500"), * currency: "USD" * }, * tipEligible: true @@ -32,7 +32,7 @@ import * as Square from "../../../../../../index"; * version: 1, * teamMemberId: "ormj0jJJZ5OZIzxrZYJI", * declaredCashTipMoney: { - * amount: 500, + * amount: BigInt("500"), * currency: "USD" * } * } diff --git a/src/api/resources/labor/resources/teamMemberWages/client/Client.ts b/src/api/resources/labor/resources/teamMemberWages/client/Client.ts index 2291a6bc2..ad6dac1da 100644 --- a/src/api/resources/labor/resources/teamMemberWages/client/Client.ts +++ b/src/api/resources/labor/resources/teamMemberWages/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; import * as errors from "../../../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace TeamMemberWages { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace TeamMemberWages { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class TeamMemberWages { - constructor(protected readonly _options: TeamMemberWages.Options = {}) {} + protected readonly _options: TeamMemberWages.Options; + + constructor(_options: TeamMemberWages.Options = {}) { + this._options = _options; + } /** * Returns a paginated list of `TeamMemberWage` instances for a business. @@ -50,80 +56,87 @@ export class TeamMemberWages { request: Square.labor.ListTeamMemberWagesRequest = {}, requestOptions?: TeamMemberWages.RequestOptions, ): Promise> { - const list = async ( - request: Square.labor.ListTeamMemberWagesRequest, - ): Promise => { - const { teamMemberId, limit, cursor } = request; - const _queryParams: Record = {}; - if (teamMemberId !== undefined) { - _queryParams["team_member_id"] = teamMemberId; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/labor/team-member-wages", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListTeamMemberWagesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.labor.ListTeamMemberWagesRequest, + ): Promise> => { + const { teamMemberId, limit, cursor } = request; + const _queryParams: Record = {}; + if (teamMemberId !== undefined) { + _queryParams["team_member_id"] = teamMemberId; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/labor/team-member-wages", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListTeamMemberWagesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/labor/team-member-wages.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/labor/team-member-wages.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.teamMemberWages ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -142,50 +155,56 @@ export class TeamMemberWages { * id: "id" * }) */ - public async get( + public get( request: Square.labor.GetTeamMemberWagesRequest, requestOptions?: TeamMemberWages.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.labor.GetTeamMemberWagesRequest, + requestOptions?: TeamMemberWages.RequestOptions, + ): Promise> { const { id } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/labor/team-member-wages/${encodeURIComponent(id)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetTeamMemberWageResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetTeamMemberWageResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -194,6 +213,7 @@ export class TeamMemberWages { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -202,6 +222,7 @@ export class TeamMemberWages { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/labor/resources/teamMemberWages/client/index.ts b/src/api/resources/labor/resources/teamMemberWages/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/labor/resources/teamMemberWages/client/index.ts +++ b/src/api/resources/labor/resources/teamMemberWages/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/labor/resources/workweekConfigs/client/Client.ts b/src/api/resources/labor/resources/workweekConfigs/client/Client.ts index 668269098..9ea0d1ba8 100644 --- a/src/api/resources/labor/resources/workweekConfigs/client/Client.ts +++ b/src/api/resources/labor/resources/workweekConfigs/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; import * as errors from "../../../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace WorkweekConfigs { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace WorkweekConfigs { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class WorkweekConfigs { - constructor(protected readonly _options: WorkweekConfigs.Options = {}) {} + protected readonly _options: WorkweekConfigs.Options; + + constructor(_options: WorkweekConfigs.Options = {}) { + this._options = _options; + } /** * Returns a list of `WorkweekConfig` instances for a business. @@ -50,77 +56,84 @@ export class WorkweekConfigs { request: Square.labor.ListWorkweekConfigsRequest = {}, requestOptions?: WorkweekConfigs.RequestOptions, ): Promise> { - const list = async ( - request: Square.labor.ListWorkweekConfigsRequest, - ): Promise => { - const { limit, cursor } = request; - const _queryParams: Record = {}; - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/labor/workweek-configs", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListWorkweekConfigsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.labor.ListWorkweekConfigsRequest, + ): Promise> => { + const { limit, cursor } = request; + const _queryParams: Record = {}; + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/labor/workweek-configs", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListWorkweekConfigsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/labor/workweek-configs.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/labor/workweek-configs.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.workweekConfigs ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -144,30 +157,34 @@ export class WorkweekConfigs { * } * }) */ - public async get( + public get( request: Square.labor.UpdateWorkweekConfigRequest, requestOptions?: WorkweekConfigs.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.labor.UpdateWorkweekConfigRequest, + requestOptions?: WorkweekConfigs.RequestOptions, + ): Promise> { const { id, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/labor/workweek-configs/${encodeURIComponent(id)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.labor.UpdateWorkweekConfigRequest.jsonOrThrow(_body, { @@ -179,19 +196,23 @@ export class WorkweekConfigs { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateWorkweekConfigResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateWorkweekConfigResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -200,6 +221,7 @@ export class WorkweekConfigs { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -208,6 +230,7 @@ export class WorkweekConfigs { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/labor/resources/workweekConfigs/client/index.ts b/src/api/resources/labor/resources/workweekConfigs/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/labor/resources/workweekConfigs/client/index.ts +++ b/src/api/resources/labor/resources/workweekConfigs/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/locations/client/Client.ts b/src/api/resources/locations/client/Client.ts index 36804519d..9b8241521 100644 --- a/src/api/resources/locations/client/Client.ts +++ b/src/api/resources/locations/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; import * as errors from "../../../../errors/index"; import { CustomAttributeDefinitions } from "../resources/customAttributeDefinitions/client/Client"; @@ -20,6 +20,8 @@ export declare namespace Locations { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -33,16 +35,19 @@ export declare namespace Locations { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Locations { + protected readonly _options: Locations.Options; protected _customAttributeDefinitions: CustomAttributeDefinitions | undefined; protected _customAttributes: CustomAttributes | undefined; protected _transactions: Transactions | undefined; - constructor(protected readonly _options: Locations.Options = {}) {} + constructor(_options: Locations.Options = {}) { + this._options = _options; + } public get customAttributeDefinitions(): CustomAttributeDefinitions { return (this._customAttributeDefinitions ??= new CustomAttributeDefinitions(this._options)); @@ -65,46 +70,51 @@ export class Locations { * @example * await client.locations.list() */ - public async list(requestOptions?: Locations.RequestOptions): Promise { + public list(requestOptions?: Locations.RequestOptions): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__list(requestOptions)); + } + + private async __list( + requestOptions?: Locations.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/locations", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.ListLocationsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.ListLocationsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -113,12 +123,14 @@ export class Locations { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/locations."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -149,29 +161,33 @@ export class Locations { * } * }) */ - public async create( + public create( request: Square.CreateLocationRequest = {}, requestOptions?: Locations.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( + request: Square.CreateLocationRequest = {}, + requestOptions?: Locations.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/locations", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CreateLocationRequest.jsonOrThrow(request, { @@ -183,19 +199,23 @@ export class Locations { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateLocationResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateLocationResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -204,12 +224,14 @@ export class Locations { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/locations."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -226,50 +248,56 @@ export class Locations { * locationId: "location_id" * }) */ - public async get( + public get( + request: Square.GetLocationsRequest, + requestOptions?: Locations.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.GetLocationsRequest, requestOptions?: Locations.RequestOptions, - ): Promise { + ): Promise> { const { locationId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/locations/${encodeURIComponent(locationId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetLocationResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetLocationResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -278,12 +306,14 @@ export class Locations { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/locations/{location_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -317,30 +347,34 @@ export class Locations { * } * }) */ - public async update( + public update( + request: Square.UpdateLocationRequest, + requestOptions?: Locations.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( request: Square.UpdateLocationRequest, requestOptions?: Locations.RequestOptions, - ): Promise { + ): Promise> { const { locationId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/locations/${encodeURIComponent(locationId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.UpdateLocationRequest.jsonOrThrow(_body, { @@ -352,19 +386,23 @@ export class Locations { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateLocationResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateLocationResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -373,12 +411,14 @@ export class Locations { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling PUT /v2/locations/{location_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -414,21 +454,21 @@ export class Locations { * discountUid: "56ae1696-z1e3-9328-af6d-f1e04d947gd4" * }], * basePriceMoney: { - * amount: 1500, + * amount: BigInt("1500"), * currency: "USD" * } * }, { * name: "Slim Jeans", * quantity: "1", * basePriceMoney: { - * amount: 2500, + * amount: BigInt("2500"), * currency: "USD" * } * }, { * name: "Woven Sweater", * quantity: "3", * basePriceMoney: { - * amount: 3500, + * amount: BigInt("3500"), * currency: "USD" * } * }], @@ -442,7 +482,7 @@ export class Locations { * uid: "56ae1696-z1e3-9328-af6d-f1e04d947gd4", * type: "FIXED_AMOUNT", * amountMoney: { - * amount: 100, + * amount: BigInt("100"), * currency: "USD" * }, * scope: "LINE_ITEM" @@ -468,36 +508,40 @@ export class Locations { * locationId: "057P5VYJ4A5X1", * description: "Application fees", * amountMoney: { - * amount: 60, + * amount: BigInt("60"), * currency: "USD" * } * }] * }) */ - public async checkouts( + public checkouts( + request: Square.CreateCheckoutRequest, + requestOptions?: Locations.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__checkouts(request, requestOptions)); + } + + private async __checkouts( request: Square.CreateCheckoutRequest, requestOptions?: Locations.RequestOptions, - ): Promise { + ): Promise> { const { locationId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/locations/${encodeURIComponent(locationId)}/checkouts`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CreateCheckoutRequest.jsonOrThrow(_body, { @@ -509,19 +553,23 @@ export class Locations { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateCheckoutResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateCheckoutResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -530,6 +578,7 @@ export class Locations { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -538,6 +587,7 @@ export class Locations { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/locations/client/index.ts b/src/api/resources/locations/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/locations/client/index.ts +++ b/src/api/resources/locations/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/locations/client/requests/CreateCheckoutRequest.ts b/src/api/resources/locations/client/requests/CreateCheckoutRequest.ts index cd6a62f0a..b7371e9d4 100644 --- a/src/api/resources/locations/client/requests/CreateCheckoutRequest.ts +++ b/src/api/resources/locations/client/requests/CreateCheckoutRequest.ts @@ -24,21 +24,21 @@ import * as Square from "../../../../index"; * discountUid: "56ae1696-z1e3-9328-af6d-f1e04d947gd4" * }], * basePriceMoney: { - * amount: 1500, + * amount: BigInt("1500"), * currency: "USD" * } * }, { * name: "Slim Jeans", * quantity: "1", * basePriceMoney: { - * amount: 2500, + * amount: BigInt("2500"), * currency: "USD" * } * }, { * name: "Woven Sweater", * quantity: "3", * basePriceMoney: { - * amount: 3500, + * amount: BigInt("3500"), * currency: "USD" * } * }], @@ -52,7 +52,7 @@ import * as Square from "../../../../index"; * uid: "56ae1696-z1e3-9328-af6d-f1e04d947gd4", * type: "FIXED_AMOUNT", * amountMoney: { - * amount: 100, + * amount: BigInt("100"), * currency: "USD" * }, * scope: "LINE_ITEM" @@ -78,7 +78,7 @@ import * as Square from "../../../../index"; * locationId: "057P5VYJ4A5X1", * description: "Application fees", * amountMoney: { - * amount: 60, + * amount: BigInt("60"), * currency: "USD" * } * }] diff --git a/src/api/resources/locations/resources/customAttributeDefinitions/client/Client.ts b/src/api/resources/locations/resources/customAttributeDefinitions/client/Client.ts index 2f767d953..67970a251 100644 --- a/src/api/resources/locations/resources/customAttributeDefinitions/client/Client.ts +++ b/src/api/resources/locations/resources/customAttributeDefinitions/client/Client.ts @@ -6,7 +6,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as errors from "../../../../../../errors/index"; export declare namespace CustomAttributeDefinitions { @@ -17,6 +17,8 @@ export declare namespace CustomAttributeDefinitions { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace CustomAttributeDefinitions { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class CustomAttributeDefinitions { - constructor(protected readonly _options: CustomAttributeDefinitions.Options = {}) {} + protected readonly _options: CustomAttributeDefinitions.Options; + + constructor(_options: CustomAttributeDefinitions.Options = {}) { + this._options = _options; + } /** * Lists the location-related [custom attribute definitions](entity:CustomAttributeDefinition) that belong to a Square seller account. @@ -53,86 +59,93 @@ export class CustomAttributeDefinitions { request: Square.locations.ListCustomAttributeDefinitionsRequest = {}, requestOptions?: CustomAttributeDefinitions.RequestOptions, ): Promise> { - const list = async ( - request: Square.locations.ListCustomAttributeDefinitionsRequest, - ): Promise => { - const { visibilityFilter, limit, cursor } = request; - const _queryParams: Record = {}; - if (visibilityFilter !== undefined) { - _queryParams["visibility_filter"] = serializers.VisibilityFilter.jsonOrThrow(visibilityFilter, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/locations/custom-attribute-definitions", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListLocationCustomAttributeDefinitionsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.locations.ListCustomAttributeDefinitionsRequest, + ): Promise> => { + const { visibilityFilter, limit, cursor } = request; + const _queryParams: Record = {}; + if (visibilityFilter !== undefined) { + _queryParams["visibility_filter"] = serializers.VisibilityFilter.jsonOrThrow(visibilityFilter, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/locations/custom-attribute-definitions", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListLocationCustomAttributeDefinitionsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/locations/custom-attribute-definitions.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, - }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/locations/custom-attribute-definitions.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable< Square.ListLocationCustomAttributeDefinitionsResponse, Square.CustomAttributeDefinition >({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.customAttributeDefinitions ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -165,29 +178,33 @@ export class CustomAttributeDefinitions { * } * }) */ - public async create( + public create( request: Square.locations.CreateLocationCustomAttributeDefinitionRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( + request: Square.locations.CreateLocationCustomAttributeDefinitionRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/locations/custom-attribute-definitions", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.locations.CreateLocationCustomAttributeDefinitionRequest.jsonOrThrow(request, { @@ -199,19 +216,23 @@ export class CustomAttributeDefinitions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateLocationCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateLocationCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -220,6 +241,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -228,6 +250,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -245,10 +268,17 @@ export class CustomAttributeDefinitions { * key: "key" * }) */ - public async get( + public get( request: Square.locations.GetCustomAttributeDefinitionsRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.locations.GetCustomAttributeDefinitionsRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): Promise> { const { key, version } = request; const _queryParams: Record = {}; if (version !== undefined) { @@ -256,45 +286,44 @@ export class CustomAttributeDefinitions { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/locations/custom-attribute-definitions/${encodeURIComponent(key)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RetrieveLocationCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RetrieveLocationCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -303,6 +332,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -311,6 +341,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -333,30 +364,34 @@ export class CustomAttributeDefinitions { * } * }) */ - public async update( + public update( + request: Square.locations.UpdateLocationCustomAttributeDefinitionRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( request: Square.locations.UpdateLocationCustomAttributeDefinitionRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): Promise> { const { key, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/locations/custom-attribute-definitions/${encodeURIComponent(key)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.locations.UpdateLocationCustomAttributeDefinitionRequest.jsonOrThrow(_body, { @@ -368,19 +403,23 @@ export class CustomAttributeDefinitions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateLocationCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateLocationCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -389,6 +428,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -397,6 +437,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -415,50 +456,56 @@ export class CustomAttributeDefinitions { * key: "key" * }) */ - public async delete( + public delete( request: Square.locations.DeleteCustomAttributeDefinitionsRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( + request: Square.locations.DeleteCustomAttributeDefinitionsRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): Promise> { const { key } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/locations/custom-attribute-definitions/${encodeURIComponent(key)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteLocationCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteLocationCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -467,6 +514,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -475,6 +523,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/locations/resources/customAttributeDefinitions/client/index.ts b/src/api/resources/locations/resources/customAttributeDefinitions/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/locations/resources/customAttributeDefinitions/client/index.ts +++ b/src/api/resources/locations/resources/customAttributeDefinitions/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/locations/resources/customAttributes/client/Client.ts b/src/api/resources/locations/resources/customAttributes/client/Client.ts index 94c0c63c2..6c2af6245 100644 --- a/src/api/resources/locations/resources/customAttributes/client/Client.ts +++ b/src/api/resources/locations/resources/customAttributes/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../../../errors/index"; export declare namespace CustomAttributes { @@ -17,6 +17,8 @@ export declare namespace CustomAttributes { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace CustomAttributes { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class CustomAttributes { - constructor(protected readonly _options: CustomAttributes.Options = {}) {} + protected readonly _options: CustomAttributes.Options; + + constructor(_options: CustomAttributes.Options = {}) { + this._options = _options; + } /** * Deletes [custom attributes](entity:CustomAttribute) for locations as a bulk operation. @@ -60,29 +66,33 @@ export class CustomAttributes { * } * }) */ - public async batchDelete( + public batchDelete( + request: Square.locations.BulkDeleteLocationCustomAttributesRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchDelete(request, requestOptions)); + } + + private async __batchDelete( request: Square.locations.BulkDeleteLocationCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/locations/custom-attributes/bulk-delete", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.locations.BulkDeleteLocationCustomAttributesRequest.jsonOrThrow(request, { @@ -94,19 +104,23 @@ export class CustomAttributes { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BulkDeleteLocationCustomAttributesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BulkDeleteLocationCustomAttributesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -115,6 +129,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -123,6 +138,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -169,29 +185,33 @@ export class CustomAttributes { * } * }) */ - public async batchUpsert( + public batchUpsert( request: Square.locations.BulkUpsertLocationCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchUpsert(request, requestOptions)); + } + + private async __batchUpsert( + request: Square.locations.BulkUpsertLocationCustomAttributesRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/locations/custom-attributes/bulk-upsert", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.locations.BulkUpsertLocationCustomAttributesRequest.jsonOrThrow(request, { @@ -203,19 +223,23 @@ export class CustomAttributes { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BulkUpsertLocationCustomAttributesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BulkUpsertLocationCustomAttributesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -224,6 +248,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -232,6 +257,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -256,86 +282,93 @@ export class CustomAttributes { request: Square.locations.ListCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, ): Promise> { - const list = async ( - request: Square.locations.ListCustomAttributesRequest, - ): Promise => { - const { locationId, visibilityFilter, limit, cursor, withDefinitions } = request; - const _queryParams: Record = {}; - if (visibilityFilter !== undefined) { - _queryParams["visibility_filter"] = serializers.VisibilityFilter.jsonOrThrow(visibilityFilter, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (withDefinitions !== undefined) { - _queryParams["with_definitions"] = withDefinitions?.toString() ?? null; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - `v2/locations/${encodeURIComponent(locationId)}/custom-attributes`, - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListLocationCustomAttributesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.locations.ListCustomAttributesRequest, + ): Promise> => { + const { locationId, visibilityFilter, limit, cursor, withDefinitions } = request; + const _queryParams: Record = {}; + if (visibilityFilter !== undefined) { + _queryParams["visibility_filter"] = serializers.VisibilityFilter.jsonOrThrow(visibilityFilter, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (withDefinitions !== undefined) { + _queryParams["with_definitions"] = withDefinitions?.toString() ?? null; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + `v2/locations/${encodeURIComponent(locationId)}/custom-attributes`, + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListLocationCustomAttributesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/locations/{location_id}/custom-attributes.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, - }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/locations/{location_id}/custom-attributes.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.customAttributes ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -359,10 +392,17 @@ export class CustomAttributes { * key: "key" * }) */ - public async get( + public get( request: Square.locations.GetCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.locations.GetCustomAttributesRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): Promise> { const { locationId, key, withDefinition, version } = request; const _queryParams: Record = {}; if (withDefinition !== undefined) { @@ -374,45 +414,44 @@ export class CustomAttributes { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/locations/${encodeURIComponent(locationId)}/custom-attributes/${encodeURIComponent(key)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RetrieveLocationCustomAttributeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RetrieveLocationCustomAttributeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -421,6 +460,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -429,6 +469,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -453,30 +494,34 @@ export class CustomAttributes { * } * }) */ - public async upsert( + public upsert( request: Square.locations.UpsertLocationCustomAttributeRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__upsert(request, requestOptions)); + } + + private async __upsert( + request: Square.locations.UpsertLocationCustomAttributeRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): Promise> { const { locationId, key, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/locations/${encodeURIComponent(locationId)}/custom-attributes/${encodeURIComponent(key)}`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.locations.UpsertLocationCustomAttributeRequest.jsonOrThrow(_body, { @@ -488,19 +533,23 @@ export class CustomAttributes { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpsertLocationCustomAttributeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpsertLocationCustomAttributeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -509,6 +558,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -517,6 +567,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -535,50 +586,56 @@ export class CustomAttributes { * key: "key" * }) */ - public async delete( + public delete( request: Square.locations.DeleteCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( + request: Square.locations.DeleteCustomAttributesRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): Promise> { const { locationId, key } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/locations/${encodeURIComponent(locationId)}/custom-attributes/${encodeURIComponent(key)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteLocationCustomAttributeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteLocationCustomAttributeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -587,6 +644,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -595,6 +653,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/locations/resources/customAttributes/client/index.ts b/src/api/resources/locations/resources/customAttributes/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/locations/resources/customAttributes/client/index.ts +++ b/src/api/resources/locations/resources/customAttributes/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/locations/resources/transactions/client/Client.ts b/src/api/resources/locations/resources/transactions/client/Client.ts index a2ad8caae..4fcd88eb8 100644 --- a/src/api/resources/locations/resources/transactions/client/Client.ts +++ b/src/api/resources/locations/resources/transactions/client/Client.ts @@ -6,7 +6,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as errors from "../../../../../../errors/index"; export declare namespace Transactions { @@ -17,6 +17,8 @@ export declare namespace Transactions { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Transactions { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Transactions { - constructor(protected readonly _options: Transactions.Options = {}) {} + protected readonly _options: Transactions.Options; + + constructor(_options: Transactions.Options = {}) { + this._options = _options; + } /** * Lists transactions for a particular location. @@ -53,10 +59,17 @@ export class Transactions { * locationId: "location_id" * }) */ - public async list( + public list( request: Square.locations.ListTransactionsRequest, requestOptions?: Transactions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__list(request, requestOptions)); + } + + private async __list( + request: Square.locations.ListTransactionsRequest, + requestOptions?: Transactions.RequestOptions, + ): Promise> { const { locationId, beginTime, endTime, sortOrder, cursor } = request; const _queryParams: Record = {}; if (beginTime !== undefined) { @@ -79,45 +92,44 @@ export class Transactions { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/locations/${encodeURIComponent(locationId)}/transactions`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.ListTransactionsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.ListTransactionsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -126,6 +138,7 @@ export class Transactions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -134,6 +147,7 @@ export class Transactions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -150,50 +164,56 @@ export class Transactions { * transactionId: "transaction_id" * }) */ - public async get( + public get( + request: Square.locations.GetTransactionsRequest, + requestOptions?: Transactions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.locations.GetTransactionsRequest, requestOptions?: Transactions.RequestOptions, - ): Promise { + ): Promise> { const { locationId, transactionId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/locations/${encodeURIComponent(locationId)}/transactions/${encodeURIComponent(transactionId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetTransactionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetTransactionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -202,6 +222,7 @@ export class Transactions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -210,6 +231,7 @@ export class Transactions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -231,50 +253,56 @@ export class Transactions { * transactionId: "transaction_id" * }) */ - public async capture( + public capture( request: Square.locations.CaptureTransactionsRequest, requestOptions?: Transactions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__capture(request, requestOptions)); + } + + private async __capture( + request: Square.locations.CaptureTransactionsRequest, + requestOptions?: Transactions.RequestOptions, + ): Promise> { const { locationId, transactionId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/locations/${encodeURIComponent(locationId)}/transactions/${encodeURIComponent(transactionId)}/capture`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CaptureTransactionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CaptureTransactionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -283,6 +311,7 @@ export class Transactions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -291,6 +320,7 @@ export class Transactions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -312,50 +342,56 @@ export class Transactions { * transactionId: "transaction_id" * }) */ - public async void( + public void( request: Square.locations.VoidTransactionsRequest, requestOptions?: Transactions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__void(request, requestOptions)); + } + + private async __void( + request: Square.locations.VoidTransactionsRequest, + requestOptions?: Transactions.RequestOptions, + ): Promise> { const { locationId, transactionId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/locations/${encodeURIComponent(locationId)}/transactions/${encodeURIComponent(transactionId)}/void`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.VoidTransactionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.VoidTransactionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -364,6 +400,7 @@ export class Transactions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -372,6 +409,7 @@ export class Transactions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/locations/resources/transactions/client/index.ts b/src/api/resources/locations/resources/transactions/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/locations/resources/transactions/client/index.ts +++ b/src/api/resources/locations/resources/transactions/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/loyalty/client/Client.ts b/src/api/resources/loyalty/client/Client.ts index 0278e1036..ec281fcf1 100644 --- a/src/api/resources/loyalty/client/Client.ts +++ b/src/api/resources/loyalty/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../errors/index"; import { Accounts } from "../resources/accounts/client/Client"; import { Programs } from "../resources/programs/client/Client"; @@ -20,6 +20,8 @@ export declare namespace Loyalty { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -33,16 +35,19 @@ export declare namespace Loyalty { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Loyalty { + protected readonly _options: Loyalty.Options; protected _accounts: Accounts | undefined; protected _programs: Programs | undefined; protected _rewards: Rewards | undefined; - constructor(protected readonly _options: Loyalty.Options = {}) {} + constructor(_options: Loyalty.Options = {}) { + this._options = _options; + } public get accounts(): Accounts { return (this._accounts ??= new Accounts(this._options)); @@ -81,29 +86,33 @@ export class Loyalty { * limit: 30 * }) */ - public async searchEvents( + public searchEvents( request: Square.SearchLoyaltyEventsRequest = {}, requestOptions?: Loyalty.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__searchEvents(request, requestOptions)); + } + + private async __searchEvents( + request: Square.SearchLoyaltyEventsRequest = {}, + requestOptions?: Loyalty.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/loyalty/events/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.SearchLoyaltyEventsRequest.jsonOrThrow(request, { @@ -115,19 +124,23 @@ export class Loyalty { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchLoyaltyEventsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchLoyaltyEventsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -136,12 +149,14 @@ export class Loyalty { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/loyalty/events/search."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/loyalty/client/index.ts b/src/api/resources/loyalty/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/loyalty/client/index.ts +++ b/src/api/resources/loyalty/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/loyalty/resources/accounts/client/Client.ts b/src/api/resources/loyalty/resources/accounts/client/Client.ts index 5066aad99..51e6164be 100644 --- a/src/api/resources/loyalty/resources/accounts/client/Client.ts +++ b/src/api/resources/loyalty/resources/accounts/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../../../errors/index"; export declare namespace Accounts { @@ -17,6 +17,8 @@ export declare namespace Accounts { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Accounts { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Accounts { - constructor(protected readonly _options: Accounts.Options = {}) {} + protected readonly _options: Accounts.Options; + + constructor(_options: Accounts.Options = {}) { + this._options = _options; + } /** * Creates a loyalty account. To create a loyalty account, you must provide the `program_id` and a `mapping` with the `phone_number` of the buyer. @@ -54,29 +60,33 @@ export class Accounts { * idempotencyKey: "ec78c477-b1c3-4899-a209-a4e71337c996" * }) */ - public async create( + public create( request: Square.loyalty.CreateLoyaltyAccountRequest, requestOptions?: Accounts.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( + request: Square.loyalty.CreateLoyaltyAccountRequest, + requestOptions?: Accounts.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/loyalty/accounts", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.loyalty.CreateLoyaltyAccountRequest.jsonOrThrow(request, { @@ -88,19 +98,23 @@ export class Accounts { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateLoyaltyAccountResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateLoyaltyAccountResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -109,12 +123,14 @@ export class Accounts { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/loyalty/accounts."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -139,29 +155,33 @@ export class Accounts { * limit: 10 * }) */ - public async search( + public search( request: Square.loyalty.SearchLoyaltyAccountsRequest = {}, requestOptions?: Accounts.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__search(request, requestOptions)); + } + + private async __search( + request: Square.loyalty.SearchLoyaltyAccountsRequest = {}, + requestOptions?: Accounts.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/loyalty/accounts/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.loyalty.SearchLoyaltyAccountsRequest.jsonOrThrow(request, { @@ -173,19 +193,23 @@ export class Accounts { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchLoyaltyAccountsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchLoyaltyAccountsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -194,12 +218,14 @@ export class Accounts { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/loyalty/accounts/search."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -215,50 +241,56 @@ export class Accounts { * accountId: "account_id" * }) */ - public async get( + public get( + request: Square.loyalty.GetAccountsRequest, + requestOptions?: Accounts.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.loyalty.GetAccountsRequest, requestOptions?: Accounts.RequestOptions, - ): Promise { + ): Promise> { const { accountId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/loyalty/accounts/${encodeURIComponent(accountId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetLoyaltyAccountResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetLoyaltyAccountResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -267,6 +299,7 @@ export class Accounts { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -275,6 +308,7 @@ export class Accounts { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -308,30 +342,34 @@ export class Accounts { * locationId: "P034NEENMD09F" * }) */ - public async accumulatePoints( + public accumulatePoints( + request: Square.loyalty.AccumulateLoyaltyPointsRequest, + requestOptions?: Accounts.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__accumulatePoints(request, requestOptions)); + } + + private async __accumulatePoints( request: Square.loyalty.AccumulateLoyaltyPointsRequest, requestOptions?: Accounts.RequestOptions, - ): Promise { + ): Promise> { const { accountId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/loyalty/accounts/${encodeURIComponent(accountId)}/accumulate`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.loyalty.AccumulateLoyaltyPointsRequest.jsonOrThrow(_body, { @@ -343,19 +381,23 @@ export class Accounts { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.AccumulateLoyaltyPointsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.AccumulateLoyaltyPointsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -364,6 +406,7 @@ export class Accounts { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -372,6 +415,7 @@ export class Accounts { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -396,30 +440,34 @@ export class Accounts { * } * }) */ - public async adjust( + public adjust( + request: Square.loyalty.AdjustLoyaltyPointsRequest, + requestOptions?: Accounts.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__adjust(request, requestOptions)); + } + + private async __adjust( request: Square.loyalty.AdjustLoyaltyPointsRequest, requestOptions?: Accounts.RequestOptions, - ): Promise { + ): Promise> { const { accountId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/loyalty/accounts/${encodeURIComponent(accountId)}/adjust`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.loyalty.AdjustLoyaltyPointsRequest.jsonOrThrow(_body, { @@ -431,19 +479,23 @@ export class Accounts { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.AdjustLoyaltyPointsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.AdjustLoyaltyPointsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -452,6 +504,7 @@ export class Accounts { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -460,6 +513,7 @@ export class Accounts { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/loyalty/resources/accounts/client/index.ts b/src/api/resources/loyalty/resources/accounts/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/loyalty/resources/accounts/client/index.ts +++ b/src/api/resources/loyalty/resources/accounts/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/loyalty/resources/programs/client/Client.ts b/src/api/resources/loyalty/resources/programs/client/Client.ts index d4cb23dd2..93a899bb0 100644 --- a/src/api/resources/loyalty/resources/programs/client/Client.ts +++ b/src/api/resources/loyalty/resources/programs/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; import * as errors from "../../../../../../errors/index"; import { Promotions } from "../resources/promotions/client/Client"; @@ -18,6 +18,8 @@ export declare namespace Programs { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -31,14 +33,17 @@ export declare namespace Programs { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Programs { + protected readonly _options: Programs.Options; protected _promotions: Promotions | undefined; - constructor(protected readonly _options: Programs.Options = {}) {} + constructor(_options: Programs.Options = {}) { + this._options = _options; + } public get promotions(): Promotions { return (this._promotions ??= new Promotions(this._options)); @@ -56,46 +61,53 @@ export class Programs { * @example * await client.loyalty.programs.list() */ - public async list(requestOptions?: Programs.RequestOptions): Promise { + public list( + requestOptions?: Programs.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__list(requestOptions)); + } + + private async __list( + requestOptions?: Programs.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/loyalty/programs", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.ListLoyaltyProgramsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.ListLoyaltyProgramsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -104,12 +116,14 @@ export class Programs { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/loyalty/programs."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -127,50 +141,56 @@ export class Programs { * programId: "program_id" * }) */ - public async get( + public get( request: Square.loyalty.GetProgramsRequest, requestOptions?: Programs.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.loyalty.GetProgramsRequest, + requestOptions?: Programs.RequestOptions, + ): Promise> { const { programId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/loyalty/programs/${encodeURIComponent(programId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetLoyaltyProgramResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetLoyaltyProgramResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -179,6 +199,7 @@ export class Programs { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -187,6 +208,7 @@ export class Programs { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -218,30 +240,34 @@ export class Programs { * loyaltyAccountId: "79b807d2-d786-46a9-933b-918028d7a8c5" * }) */ - public async calculate( + public calculate( request: Square.loyalty.CalculateLoyaltyPointsRequest, requestOptions?: Programs.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__calculate(request, requestOptions)); + } + + private async __calculate( + request: Square.loyalty.CalculateLoyaltyPointsRequest, + requestOptions?: Programs.RequestOptions, + ): Promise> { const { programId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/loyalty/programs/${encodeURIComponent(programId)}/calculate`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.loyalty.CalculateLoyaltyPointsRequest.jsonOrThrow(_body, { @@ -253,19 +279,23 @@ export class Programs { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CalculateLoyaltyPointsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CalculateLoyaltyPointsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -274,6 +304,7 @@ export class Programs { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -282,6 +313,7 @@ export class Programs { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/loyalty/resources/programs/client/index.ts b/src/api/resources/loyalty/resources/programs/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/loyalty/resources/programs/client/index.ts +++ b/src/api/resources/loyalty/resources/programs/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/loyalty/resources/programs/resources/promotions/client/Client.ts b/src/api/resources/loyalty/resources/programs/resources/promotions/client/Client.ts index 37eb4e388..5c8aebb8d 100644 --- a/src/api/resources/loyalty/resources/programs/resources/promotions/client/Client.ts +++ b/src/api/resources/loyalty/resources/programs/resources/promotions/client/Client.ts @@ -6,7 +6,7 @@ import * as environments from "../../../../../../../../environments"; import * as core from "../../../../../../../../core"; import * as Square from "../../../../../../../index"; import * as serializers from "../../../../../../../../serialization/index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../../../core/headers"; import * as errors from "../../../../../../../../errors/index"; export declare namespace Promotions { @@ -17,6 +17,8 @@ export declare namespace Promotions { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Promotions { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Promotions { - constructor(protected readonly _options: Promotions.Options = {}) {} + protected readonly _options: Promotions.Options; + + constructor(_options: Promotions.Options = {}) { + this._options = _options; + } /** * Lists the loyalty promotions associated with a [loyalty program](entity:LoyaltyProgram). @@ -53,83 +59,90 @@ export class Promotions { request: Square.loyalty.programs.ListPromotionsRequest, requestOptions?: Promotions.RequestOptions, ): Promise> { - const list = async ( - request: Square.loyalty.programs.ListPromotionsRequest, - ): Promise => { - const { programId, status, cursor, limit } = request; - const _queryParams: Record = {}; - if (status !== undefined) { - _queryParams["status"] = serializers.LoyaltyPromotionStatus.jsonOrThrow(status, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - `v2/loyalty/programs/${encodeURIComponent(programId)}/promotions`, - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListLoyaltyPromotionsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.loyalty.programs.ListPromotionsRequest, + ): Promise> => { + const { programId, status, cursor, limit } = request; + const _queryParams: Record = {}; + if (status !== undefined) { + _queryParams["status"] = serializers.LoyaltyPromotionStatus.jsonOrThrow(status, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + `v2/loyalty/programs/${encodeURIComponent(programId)}/promotions`, + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListLoyaltyPromotionsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/loyalty/programs/{program_id}/promotions.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/loyalty/programs/{program_id}/promotions.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.loyaltyPromotions ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -167,7 +180,7 @@ export class Promotions { * interval: "DAY" * }, * minimumSpendAmountMoney: { - * amount: 2000, + * amount: BigInt("2000"), * currency: "USD" * }, * qualifyingCategoryIds: ["XTQPYLR3IIU9C44VRCB3XD12"] @@ -175,30 +188,34 @@ export class Promotions { * idempotencyKey: "ec78c477-b1c3-4899-a209-a4e71337c996" * }) */ - public async create( + public create( + request: Square.loyalty.programs.CreateLoyaltyPromotionRequest, + requestOptions?: Promotions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( request: Square.loyalty.programs.CreateLoyaltyPromotionRequest, requestOptions?: Promotions.RequestOptions, - ): Promise { + ): Promise> { const { programId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/loyalty/programs/${encodeURIComponent(programId)}/promotions`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.loyalty.programs.CreateLoyaltyPromotionRequest.jsonOrThrow(_body, { @@ -210,19 +227,23 @@ export class Promotions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateLoyaltyPromotionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateLoyaltyPromotionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -231,6 +252,7 @@ export class Promotions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -239,6 +261,7 @@ export class Promotions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -255,50 +278,56 @@ export class Promotions { * programId: "program_id" * }) */ - public async get( + public get( request: Square.loyalty.programs.GetPromotionsRequest, requestOptions?: Promotions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.loyalty.programs.GetPromotionsRequest, + requestOptions?: Promotions.RequestOptions, + ): Promise> { const { promotionId, programId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/loyalty/programs/${encodeURIComponent(programId)}/promotions/${encodeURIComponent(promotionId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetLoyaltyPromotionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetLoyaltyPromotionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -307,6 +336,7 @@ export class Promotions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -315,6 +345,7 @@ export class Promotions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -336,50 +367,56 @@ export class Promotions { * programId: "program_id" * }) */ - public async cancel( + public cancel( request: Square.loyalty.programs.CancelPromotionsRequest, requestOptions?: Promotions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__cancel(request, requestOptions)); + } + + private async __cancel( + request: Square.loyalty.programs.CancelPromotionsRequest, + requestOptions?: Promotions.RequestOptions, + ): Promise> { const { promotionId, programId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/loyalty/programs/${encodeURIComponent(programId)}/promotions/${encodeURIComponent(promotionId)}/cancel`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CancelLoyaltyPromotionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CancelLoyaltyPromotionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -388,6 +425,7 @@ export class Promotions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -396,6 +434,7 @@ export class Promotions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/loyalty/resources/programs/resources/promotions/client/index.ts b/src/api/resources/loyalty/resources/programs/resources/promotions/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/loyalty/resources/programs/resources/promotions/client/index.ts +++ b/src/api/resources/loyalty/resources/programs/resources/promotions/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/loyalty/resources/programs/resources/promotions/client/requests/CreateLoyaltyPromotionRequest.ts b/src/api/resources/loyalty/resources/programs/resources/promotions/client/requests/CreateLoyaltyPromotionRequest.ts index fb8e389ed..7e69310f0 100644 --- a/src/api/resources/loyalty/resources/programs/resources/promotions/client/requests/CreateLoyaltyPromotionRequest.ts +++ b/src/api/resources/loyalty/resources/programs/resources/promotions/client/requests/CreateLoyaltyPromotionRequest.ts @@ -24,7 +24,7 @@ import * as Square from "../../../../../../../../index"; * interval: "DAY" * }, * minimumSpendAmountMoney: { - * amount: 2000, + * amount: BigInt("2000"), * currency: "USD" * }, * qualifyingCategoryIds: ["XTQPYLR3IIU9C44VRCB3XD12"] diff --git a/src/api/resources/loyalty/resources/rewards/client/Client.ts b/src/api/resources/loyalty/resources/rewards/client/Client.ts index 0834e79fb..377b3f6a1 100644 --- a/src/api/resources/loyalty/resources/rewards/client/Client.ts +++ b/src/api/resources/loyalty/resources/rewards/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../../../errors/index"; export declare namespace Rewards { @@ -17,6 +17,8 @@ export declare namespace Rewards { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Rewards { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Rewards { - constructor(protected readonly _options: Rewards.Options = {}) {} + protected readonly _options: Rewards.Options; + + constructor(_options: Rewards.Options = {}) { + this._options = _options; + } /** * Creates a loyalty reward. In the process, the endpoint does following: @@ -60,29 +66,33 @@ export class Rewards { * idempotencyKey: "18c2e5ea-a620-4b1f-ad60-7b167285e451" * }) */ - public async create( + public create( request: Square.loyalty.CreateLoyaltyRewardRequest, requestOptions?: Rewards.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( + request: Square.loyalty.CreateLoyaltyRewardRequest, + requestOptions?: Rewards.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/loyalty/rewards", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.loyalty.CreateLoyaltyRewardRequest.jsonOrThrow(request, { @@ -94,19 +104,23 @@ export class Rewards { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateLoyaltyRewardResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateLoyaltyRewardResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -115,12 +129,14 @@ export class Rewards { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/loyalty/rewards."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -145,29 +161,33 @@ export class Rewards { * limit: 10 * }) */ - public async search( + public search( + request: Square.loyalty.SearchLoyaltyRewardsRequest = {}, + requestOptions?: Rewards.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__search(request, requestOptions)); + } + + private async __search( request: Square.loyalty.SearchLoyaltyRewardsRequest = {}, requestOptions?: Rewards.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/loyalty/rewards/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.loyalty.SearchLoyaltyRewardsRequest.jsonOrThrow(request, { @@ -179,19 +199,23 @@ export class Rewards { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchLoyaltyRewardsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchLoyaltyRewardsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -200,12 +224,14 @@ export class Rewards { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/loyalty/rewards/search."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -221,50 +247,56 @@ export class Rewards { * rewardId: "reward_id" * }) */ - public async get( + public get( + request: Square.loyalty.GetRewardsRequest, + requestOptions?: Rewards.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.loyalty.GetRewardsRequest, requestOptions?: Rewards.RequestOptions, - ): Promise { + ): Promise> { const { rewardId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/loyalty/rewards/${encodeURIComponent(rewardId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetLoyaltyRewardResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetLoyaltyRewardResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -273,6 +305,7 @@ export class Rewards { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -281,6 +314,7 @@ export class Rewards { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -304,50 +338,56 @@ export class Rewards { * rewardId: "reward_id" * }) */ - public async delete( + public delete( request: Square.loyalty.DeleteRewardsRequest, requestOptions?: Rewards.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( + request: Square.loyalty.DeleteRewardsRequest, + requestOptions?: Rewards.RequestOptions, + ): Promise> { const { rewardId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/loyalty/rewards/${encodeURIComponent(rewardId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteLoyaltyRewardResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteLoyaltyRewardResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -356,6 +396,7 @@ export class Rewards { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -364,6 +405,7 @@ export class Rewards { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -391,30 +433,34 @@ export class Rewards { * locationId: "P034NEENMD09F" * }) */ - public async redeem( + public redeem( request: Square.loyalty.RedeemLoyaltyRewardRequest, requestOptions?: Rewards.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__redeem(request, requestOptions)); + } + + private async __redeem( + request: Square.loyalty.RedeemLoyaltyRewardRequest, + requestOptions?: Rewards.RequestOptions, + ): Promise> { const { rewardId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/loyalty/rewards/${encodeURIComponent(rewardId)}/redeem`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.loyalty.RedeemLoyaltyRewardRequest.jsonOrThrow(_body, { @@ -426,19 +472,23 @@ export class Rewards { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RedeemLoyaltyRewardResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RedeemLoyaltyRewardResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -447,6 +497,7 @@ export class Rewards { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -455,6 +506,7 @@ export class Rewards { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/loyalty/resources/rewards/client/index.ts b/src/api/resources/loyalty/resources/rewards/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/loyalty/resources/rewards/client/index.ts +++ b/src/api/resources/loyalty/resources/rewards/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/merchants/client/Client.ts b/src/api/resources/merchants/client/Client.ts index c10549417..4498a1f13 100644 --- a/src/api/resources/merchants/client/Client.ts +++ b/src/api/resources/merchants/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; import * as errors from "../../../../errors/index"; import { CustomAttributeDefinitions } from "../resources/customAttributeDefinitions/client/Client"; @@ -19,6 +19,8 @@ export declare namespace Merchants { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -32,15 +34,18 @@ export declare namespace Merchants { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Merchants { + protected readonly _options: Merchants.Options; protected _customAttributeDefinitions: CustomAttributeDefinitions | undefined; protected _customAttributes: CustomAttributes | undefined; - constructor(protected readonly _options: Merchants.Options = {}) {} + constructor(_options: Merchants.Options = {}) { + this._options = _options; + } public get customAttributeDefinitions(): CustomAttributeDefinitions { return (this._customAttributeDefinitions ??= new CustomAttributeDefinitions(this._options)); @@ -72,70 +77,79 @@ export class Merchants { request: Square.ListMerchantsRequest = {}, requestOptions?: Merchants.RequestOptions, ): Promise> { - const list = async (request: Square.ListMerchantsRequest): Promise => { - const { cursor } = request; - const _queryParams: Record = {}; - if (cursor !== undefined) { - _queryParams["cursor"] = cursor?.toString() ?? null; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/merchants", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListMerchantsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.ListMerchantsRequest, + ): Promise> => { + const { cursor } = request; + const _queryParams: Record = {}; + if (cursor !== undefined) { + _queryParams["cursor"] = cursor?.toString() ?? null; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/merchants", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListMerchantsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/merchants."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, - }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/merchants."); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.merchant ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -154,50 +168,56 @@ export class Merchants { * merchantId: "merchant_id" * }) */ - public async get( + public get( request: Square.GetMerchantsRequest, requestOptions?: Merchants.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.GetMerchantsRequest, + requestOptions?: Merchants.RequestOptions, + ): Promise> { const { merchantId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/merchants/${encodeURIComponent(merchantId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetMerchantResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetMerchantResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -206,12 +226,14 @@ export class Merchants { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/merchants/{merchant_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/merchants/client/index.ts b/src/api/resources/merchants/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/merchants/client/index.ts +++ b/src/api/resources/merchants/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/merchants/resources/customAttributeDefinitions/client/Client.ts b/src/api/resources/merchants/resources/customAttributeDefinitions/client/Client.ts index c70924e65..76e9db99f 100644 --- a/src/api/resources/merchants/resources/customAttributeDefinitions/client/Client.ts +++ b/src/api/resources/merchants/resources/customAttributeDefinitions/client/Client.ts @@ -6,7 +6,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as errors from "../../../../../../errors/index"; export declare namespace CustomAttributeDefinitions { @@ -17,6 +17,8 @@ export declare namespace CustomAttributeDefinitions { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace CustomAttributeDefinitions { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class CustomAttributeDefinitions { - constructor(protected readonly _options: CustomAttributeDefinitions.Options = {}) {} + protected readonly _options: CustomAttributeDefinitions.Options; + + constructor(_options: CustomAttributeDefinitions.Options = {}) { + this._options = _options; + } /** * Lists the merchant-related [custom attribute definitions](entity:CustomAttributeDefinition) that belong to a Square seller account. @@ -53,86 +59,93 @@ export class CustomAttributeDefinitions { request: Square.merchants.ListCustomAttributeDefinitionsRequest = {}, requestOptions?: CustomAttributeDefinitions.RequestOptions, ): Promise> { - const list = async ( - request: Square.merchants.ListCustomAttributeDefinitionsRequest, - ): Promise => { - const { visibilityFilter, limit, cursor } = request; - const _queryParams: Record = {}; - if (visibilityFilter !== undefined) { - _queryParams["visibility_filter"] = serializers.VisibilityFilter.jsonOrThrow(visibilityFilter, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/merchants/custom-attribute-definitions", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListMerchantCustomAttributeDefinitionsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.merchants.ListCustomAttributeDefinitionsRequest, + ): Promise> => { + const { visibilityFilter, limit, cursor } = request; + const _queryParams: Record = {}; + if (visibilityFilter !== undefined) { + _queryParams["visibility_filter"] = serializers.VisibilityFilter.jsonOrThrow(visibilityFilter, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/merchants/custom-attribute-definitions", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListMerchantCustomAttributeDefinitionsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/merchants/custom-attribute-definitions.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, - }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/merchants/custom-attribute-definitions.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable< Square.ListMerchantCustomAttributeDefinitionsResponse, Square.CustomAttributeDefinition >({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.customAttributeDefinitions ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -165,29 +178,33 @@ export class CustomAttributeDefinitions { * } * }) */ - public async create( + public create( request: Square.merchants.CreateMerchantCustomAttributeDefinitionRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( + request: Square.merchants.CreateMerchantCustomAttributeDefinitionRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/merchants/custom-attribute-definitions", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.merchants.CreateMerchantCustomAttributeDefinitionRequest.jsonOrThrow(request, { @@ -199,19 +216,23 @@ export class CustomAttributeDefinitions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateMerchantCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateMerchantCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -220,6 +241,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -228,6 +250,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -245,10 +268,17 @@ export class CustomAttributeDefinitions { * key: "key" * }) */ - public async get( + public get( request: Square.merchants.GetCustomAttributeDefinitionsRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.merchants.GetCustomAttributeDefinitionsRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): Promise> { const { key, version } = request; const _queryParams: Record = {}; if (version !== undefined) { @@ -256,45 +286,44 @@ export class CustomAttributeDefinitions { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/merchants/custom-attribute-definitions/${encodeURIComponent(key)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RetrieveMerchantCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RetrieveMerchantCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -303,6 +332,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -311,6 +341,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -333,30 +364,34 @@ export class CustomAttributeDefinitions { * } * }) */ - public async update( + public update( + request: Square.merchants.UpdateMerchantCustomAttributeDefinitionRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( request: Square.merchants.UpdateMerchantCustomAttributeDefinitionRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): Promise> { const { key, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/merchants/custom-attribute-definitions/${encodeURIComponent(key)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.merchants.UpdateMerchantCustomAttributeDefinitionRequest.jsonOrThrow(_body, { @@ -368,19 +403,23 @@ export class CustomAttributeDefinitions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateMerchantCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateMerchantCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -389,6 +428,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -397,6 +437,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -415,50 +456,56 @@ export class CustomAttributeDefinitions { * key: "key" * }) */ - public async delete( + public delete( request: Square.merchants.DeleteCustomAttributeDefinitionsRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( + request: Square.merchants.DeleteCustomAttributeDefinitionsRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): Promise> { const { key } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/merchants/custom-attribute-definitions/${encodeURIComponent(key)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteMerchantCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteMerchantCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -467,6 +514,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -475,6 +523,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/merchants/resources/customAttributeDefinitions/client/index.ts b/src/api/resources/merchants/resources/customAttributeDefinitions/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/merchants/resources/customAttributeDefinitions/client/index.ts +++ b/src/api/resources/merchants/resources/customAttributeDefinitions/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/merchants/resources/customAttributes/client/Client.ts b/src/api/resources/merchants/resources/customAttributes/client/Client.ts index a65584f2b..43b7f7467 100644 --- a/src/api/resources/merchants/resources/customAttributes/client/Client.ts +++ b/src/api/resources/merchants/resources/customAttributes/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../../../errors/index"; export declare namespace CustomAttributes { @@ -17,6 +17,8 @@ export declare namespace CustomAttributes { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace CustomAttributes { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class CustomAttributes { - constructor(protected readonly _options: CustomAttributes.Options = {}) {} + protected readonly _options: CustomAttributes.Options; + + constructor(_options: CustomAttributes.Options = {}) { + this._options = _options; + } /** * Deletes [custom attributes](entity:CustomAttribute) for a merchant as a bulk operation. @@ -57,29 +63,33 @@ export class CustomAttributes { * } * }) */ - public async batchDelete( + public batchDelete( + request: Square.merchants.BulkDeleteMerchantCustomAttributesRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchDelete(request, requestOptions)); + } + + private async __batchDelete( request: Square.merchants.BulkDeleteMerchantCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/merchants/custom-attributes/bulk-delete", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.merchants.BulkDeleteMerchantCustomAttributesRequest.jsonOrThrow(request, { @@ -91,19 +101,23 @@ export class CustomAttributes { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BulkDeleteMerchantCustomAttributesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BulkDeleteMerchantCustomAttributesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -112,6 +126,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -120,6 +135,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -159,29 +175,33 @@ export class CustomAttributes { * } * }) */ - public async batchUpsert( + public batchUpsert( request: Square.merchants.BulkUpsertMerchantCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchUpsert(request, requestOptions)); + } + + private async __batchUpsert( + request: Square.merchants.BulkUpsertMerchantCustomAttributesRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/merchants/custom-attributes/bulk-upsert", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.merchants.BulkUpsertMerchantCustomAttributesRequest.jsonOrThrow(request, { @@ -193,19 +213,23 @@ export class CustomAttributes { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BulkUpsertMerchantCustomAttributesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BulkUpsertMerchantCustomAttributesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -214,6 +238,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -222,6 +247,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -246,86 +272,93 @@ export class CustomAttributes { request: Square.merchants.ListCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, ): Promise> { - const list = async ( - request: Square.merchants.ListCustomAttributesRequest, - ): Promise => { - const { merchantId, visibilityFilter, limit, cursor, withDefinitions } = request; - const _queryParams: Record = {}; - if (visibilityFilter !== undefined) { - _queryParams["visibility_filter"] = serializers.VisibilityFilter.jsonOrThrow(visibilityFilter, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (withDefinitions !== undefined) { - _queryParams["with_definitions"] = withDefinitions?.toString() ?? null; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - `v2/merchants/${encodeURIComponent(merchantId)}/custom-attributes`, - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListMerchantCustomAttributesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.merchants.ListCustomAttributesRequest, + ): Promise> => { + const { merchantId, visibilityFilter, limit, cursor, withDefinitions } = request; + const _queryParams: Record = {}; + if (visibilityFilter !== undefined) { + _queryParams["visibility_filter"] = serializers.VisibilityFilter.jsonOrThrow(visibilityFilter, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (withDefinitions !== undefined) { + _queryParams["with_definitions"] = withDefinitions?.toString() ?? null; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + `v2/merchants/${encodeURIComponent(merchantId)}/custom-attributes`, + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListMerchantCustomAttributesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/merchants/{merchant_id}/custom-attributes.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, - }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/merchants/{merchant_id}/custom-attributes.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.customAttributes ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -349,10 +382,17 @@ export class CustomAttributes { * key: "key" * }) */ - public async get( + public get( request: Square.merchants.GetCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.merchants.GetCustomAttributesRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): Promise> { const { merchantId, key, withDefinition, version } = request; const _queryParams: Record = {}; if (withDefinition !== undefined) { @@ -364,45 +404,44 @@ export class CustomAttributes { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/merchants/${encodeURIComponent(merchantId)}/custom-attributes/${encodeURIComponent(key)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RetrieveMerchantCustomAttributeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RetrieveMerchantCustomAttributeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -411,6 +450,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -419,6 +459,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -443,30 +484,34 @@ export class CustomAttributes { * } * }) */ - public async upsert( + public upsert( request: Square.merchants.UpsertMerchantCustomAttributeRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__upsert(request, requestOptions)); + } + + private async __upsert( + request: Square.merchants.UpsertMerchantCustomAttributeRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): Promise> { const { merchantId, key, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/merchants/${encodeURIComponent(merchantId)}/custom-attributes/${encodeURIComponent(key)}`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.merchants.UpsertMerchantCustomAttributeRequest.jsonOrThrow(_body, { @@ -478,19 +523,23 @@ export class CustomAttributes { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpsertMerchantCustomAttributeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpsertMerchantCustomAttributeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -499,6 +548,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -507,6 +557,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -525,50 +576,56 @@ export class CustomAttributes { * key: "key" * }) */ - public async delete( + public delete( request: Square.merchants.DeleteCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( + request: Square.merchants.DeleteCustomAttributesRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): Promise> { const { merchantId, key } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/merchants/${encodeURIComponent(merchantId)}/custom-attributes/${encodeURIComponent(key)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteMerchantCustomAttributeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteMerchantCustomAttributeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -577,6 +634,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -585,6 +643,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/merchants/resources/customAttributes/client/index.ts b/src/api/resources/merchants/resources/customAttributes/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/merchants/resources/customAttributes/client/index.ts +++ b/src/api/resources/merchants/resources/customAttributes/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/mobile/client/Client.ts b/src/api/resources/mobile/client/Client.ts index 2bf815085..c14e0e942 100644 --- a/src/api/resources/mobile/client/Client.ts +++ b/src/api/resources/mobile/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../errors/index"; export declare namespace Mobile { @@ -17,6 +17,8 @@ export declare namespace Mobile { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Mobile { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Mobile { - constructor(protected readonly _options: Mobile.Options = {}) {} + protected readonly _options: Mobile.Options; + + constructor(_options: Mobile.Options = {}) { + this._options = _options; + } /** * __Note:__ This endpoint is used by the deprecated Reader SDK. @@ -62,29 +68,33 @@ export class Mobile { * locationId: "YOUR_LOCATION_ID" * }) */ - public async authorizationCode( + public authorizationCode( + request: Square.CreateMobileAuthorizationCodeRequest = {}, + requestOptions?: Mobile.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__authorizationCode(request, requestOptions)); + } + + private async __authorizationCode( request: Square.CreateMobileAuthorizationCodeRequest = {}, requestOptions?: Mobile.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "mobile/authorization-code", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CreateMobileAuthorizationCodeRequest.jsonOrThrow(request, { @@ -96,19 +106,23 @@ export class Mobile { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateMobileAuthorizationCodeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateMobileAuthorizationCodeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -117,12 +131,14 @@ export class Mobile { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /mobile/authorization-code."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/mobile/client/index.ts b/src/api/resources/mobile/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/mobile/client/index.ts +++ b/src/api/resources/mobile/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/oAuth/client/Client.ts b/src/api/resources/oAuth/client/Client.ts index 780776144..8e3a31fc5 100644 --- a/src/api/resources/oAuth/client/Client.ts +++ b/src/api/resources/oAuth/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../errors/index"; export declare namespace OAuth { @@ -17,6 +17,8 @@ export declare namespace OAuth { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace OAuth { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class OAuth { - constructor(protected readonly _options: OAuth.Options = {}) {} + protected readonly _options: OAuth.Options; + + constructor(_options: OAuth.Options = {}) { + this._options = _options; + } /** * Revokes an access token generated with the OAuth flow. @@ -62,29 +68,33 @@ export class OAuth { * accessToken: "ACCESS_TOKEN" * }) */ - public async revokeToken( + public revokeToken( request: Square.RevokeTokenRequest = {}, requestOptions?: OAuth.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__revokeToken(request, requestOptions)); + } + + private async __revokeToken( + request: Square.RevokeTokenRequest = {}, + requestOptions?: OAuth.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "oauth2/revoke", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.RevokeTokenRequest.jsonOrThrow(request, { @@ -96,19 +106,23 @@ export class OAuth { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RevokeTokenResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RevokeTokenResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -117,12 +131,14 @@ export class OAuth { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /oauth2/revoke."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -161,29 +177,33 @@ export class OAuth { * grantType: "authorization_code" * }) */ - public async obtainToken( + public obtainToken( + request: Square.ObtainTokenRequest, + requestOptions?: OAuth.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__obtainToken(request, requestOptions)); + } + + private async __obtainToken( request: Square.ObtainTokenRequest, requestOptions?: OAuth.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "oauth2/token", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.ObtainTokenRequest.jsonOrThrow(request, { @@ -195,19 +215,23 @@ export class OAuth { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.ObtainTokenResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.ObtainTokenResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -216,12 +240,14 @@ export class OAuth { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /oauth2/token."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -247,48 +273,53 @@ export class OAuth { * @example * await client.oAuth.retrieveTokenStatus() */ - public async retrieveTokenStatus( + public retrieveTokenStatus( + requestOptions?: OAuth.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__retrieveTokenStatus(requestOptions)); + } + + private async __retrieveTokenStatus( requestOptions?: OAuth.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "oauth2/token/status", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RetrieveTokenStatusResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RetrieveTokenStatusResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -297,12 +328,14 @@ export class OAuth { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /oauth2/token/status."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -313,40 +346,40 @@ export class OAuth { * @example * await client.oAuth.authorize() */ - public async authorize(requestOptions?: OAuth.RequestOptions): Promise { + public authorize(requestOptions?: OAuth.RequestOptions): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__authorize(requestOptions)); + } + + private async __authorize(requestOptions?: OAuth.RequestOptions): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "oauth2/authorize", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return; + return { data: undefined, rawResponse: _response.rawResponse }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -355,12 +388,14 @@ export class OAuth { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /oauth2/authorize."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/oAuth/client/index.ts b/src/api/resources/oAuth/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/oAuth/client/index.ts +++ b/src/api/resources/oAuth/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/orders/client/Client.ts b/src/api/resources/orders/client/Client.ts index 573bb05a3..233b506aa 100644 --- a/src/api/resources/orders/client/Client.ts +++ b/src/api/resources/orders/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../errors/index"; import { CustomAttributeDefinitions } from "../resources/customAttributeDefinitions/client/Client"; import { CustomAttributes } from "../resources/customAttributes/client/Client"; @@ -19,6 +19,8 @@ export declare namespace Orders { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -32,15 +34,18 @@ export declare namespace Orders { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Orders { + protected readonly _options: Orders.Options; protected _customAttributeDefinitions: CustomAttributeDefinitions | undefined; protected _customAttributes: CustomAttributes | undefined; - constructor(protected readonly _options: Orders.Options = {}) {} + constructor(_options: Orders.Options = {}) { + this._options = _options; + } public get customAttributeDefinitions(): CustomAttributeDefinitions { return (this._customAttributeDefinitions ??= new CustomAttributeDefinitions(this._options)); @@ -71,7 +76,7 @@ export class Orders { * name: "New York Strip Steak", * quantity: "1", * basePriceMoney: { - * amount: 1599, + * amount: BigInt("1599"), * currency: "USD" * } * }, { @@ -103,7 +108,7 @@ export class Orders { * uid: "one-dollar-off", * name: "Sale - $1.00 off", * amountMoney: { - * amount: 100, + * amount: BigInt("100"), * currency: "USD" * }, * scope: "LINE_ITEM" @@ -112,29 +117,33 @@ export class Orders { * idempotencyKey: "8193148c-9586-11e6-99f9-28cfe92138cf" * }) */ - public async create( + public create( request: Square.CreateOrderRequest, requestOptions?: Orders.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( + request: Square.CreateOrderRequest, + requestOptions?: Orders.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/orders", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CreateOrderRequest.jsonOrThrow(request, { @@ -146,19 +155,23 @@ export class Orders { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateOrderResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateOrderResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -167,12 +180,14 @@ export class Orders { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/orders."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -191,29 +206,33 @@ export class Orders { * orderIds: ["CAISEM82RcpmcFBM0TfOyiHV3es", "CAISENgvlJ6jLWAzERDzjyHVybY"] * }) */ - public async batchGet( + public batchGet( request: Square.BatchGetOrdersRequest, requestOptions?: Orders.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchGet(request, requestOptions)); + } + + private async __batchGet( + request: Square.BatchGetOrdersRequest, + requestOptions?: Orders.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/orders/batch-retrieve", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BatchGetOrdersRequest.jsonOrThrow(request, { @@ -225,19 +244,23 @@ export class Orders { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BatchGetOrdersResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BatchGetOrdersResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -246,12 +269,14 @@ export class Orders { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/orders/batch-retrieve."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -270,14 +295,14 @@ export class Orders { * name: "Item 1", * quantity: "1", * basePriceMoney: { - * amount: 500, + * amount: BigInt("500"), * currency: "USD" * } * }, { * name: "Item 2", * quantity: "2", * basePriceMoney: { - * amount: 300, + * amount: BigInt("300"), * currency: "USD" * } * }], @@ -289,29 +314,33 @@ export class Orders { * } * }) */ - public async calculate( + public calculate( request: Square.CalculateOrderRequest, requestOptions?: Orders.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__calculate(request, requestOptions)); + } + + private async __calculate( + request: Square.CalculateOrderRequest, + requestOptions?: Orders.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/orders/calculate", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CalculateOrderRequest.jsonOrThrow(request, { @@ -323,19 +352,23 @@ export class Orders { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CalculateOrderResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CalculateOrderResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -344,12 +377,14 @@ export class Orders { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/orders/calculate."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -368,29 +403,33 @@ export class Orders { * idempotencyKey: "UNIQUE_STRING" * }) */ - public async clone( + public clone( request: Square.CloneOrderRequest, requestOptions?: Orders.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__clone(request, requestOptions)); + } + + private async __clone( + request: Square.CloneOrderRequest, + requestOptions?: Orders.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/orders/clone", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CloneOrderRequest.jsonOrThrow(request, { @@ -402,19 +441,23 @@ export class Orders { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CloneOrderResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CloneOrderResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -423,12 +466,14 @@ export class Orders { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/orders/clone."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -479,29 +524,33 @@ export class Orders { * returnEntries: true * }) */ - public async search( + public search( request: Square.SearchOrdersRequest = {}, requestOptions?: Orders.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__search(request, requestOptions)); + } + + private async __search( + request: Square.SearchOrdersRequest = {}, + requestOptions?: Orders.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/orders/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.SearchOrdersRequest.jsonOrThrow(request, { @@ -513,19 +562,23 @@ export class Orders { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchOrdersResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchOrdersResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -534,12 +587,14 @@ export class Orders { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/orders/search."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -555,50 +610,56 @@ export class Orders { * orderId: "order_id" * }) */ - public async get( + public get( request: Square.GetOrdersRequest, requestOptions?: Orders.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.GetOrdersRequest, + requestOptions?: Orders.RequestOptions, + ): Promise> { const { orderId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/orders/${encodeURIComponent(orderId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetOrderResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetOrderResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -607,12 +668,14 @@ export class Orders { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/orders/{order_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -647,7 +710,7 @@ export class Orders { * name: "COOKIE", * quantity: "2", * basePriceMoney: { - * amount: 200, + * amount: BigInt("200"), * currency: "USD" * } * }], @@ -657,30 +720,34 @@ export class Orders { * idempotencyKey: "UNIQUE_STRING" * }) */ - public async update( + public update( request: Square.UpdateOrderRequest, requestOptions?: Orders.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( + request: Square.UpdateOrderRequest, + requestOptions?: Orders.RequestOptions, + ): Promise> { const { orderId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/orders/${encodeURIComponent(orderId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.UpdateOrderRequest.jsonOrThrow(_body, { @@ -692,19 +759,23 @@ export class Orders { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateOrderResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateOrderResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -713,12 +784,14 @@ export class Orders { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling PUT /v2/orders/{order_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -749,30 +822,34 @@ export class Orders { * paymentIds: ["EnZdNAlWCmfh6Mt5FMNST1o7taB", "0LRiVlbXVwe8ozu4KbZxd12mvaB"] * }) */ - public async pay( + public pay( request: Square.PayOrderRequest, requestOptions?: Orders.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__pay(request, requestOptions)); + } + + private async __pay( + request: Square.PayOrderRequest, + requestOptions?: Orders.RequestOptions, + ): Promise> { const { orderId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/orders/${encodeURIComponent(orderId)}/pay`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.PayOrderRequest.jsonOrThrow(_body, { @@ -784,19 +861,23 @@ export class Orders { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.PayOrderResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.PayOrderResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -805,12 +886,14 @@ export class Orders { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/orders/{order_id}/pay."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/orders/client/index.ts b/src/api/resources/orders/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/orders/client/index.ts +++ b/src/api/resources/orders/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/orders/client/requests/CalculateOrderRequest.ts b/src/api/resources/orders/client/requests/CalculateOrderRequest.ts index 416893d0b..419083fa9 100644 --- a/src/api/resources/orders/client/requests/CalculateOrderRequest.ts +++ b/src/api/resources/orders/client/requests/CalculateOrderRequest.ts @@ -13,14 +13,14 @@ import * as Square from "../../../../index"; * name: "Item 1", * quantity: "1", * basePriceMoney: { - * amount: 500, + * amount: BigInt("500"), * currency: "USD" * } * }, { * name: "Item 2", * quantity: "2", * basePriceMoney: { - * amount: 300, + * amount: BigInt("300"), * currency: "USD" * } * }], diff --git a/src/api/resources/orders/client/requests/UpdateOrderRequest.ts b/src/api/resources/orders/client/requests/UpdateOrderRequest.ts index ae35505ad..effc16634 100644 --- a/src/api/resources/orders/client/requests/UpdateOrderRequest.ts +++ b/src/api/resources/orders/client/requests/UpdateOrderRequest.ts @@ -15,7 +15,7 @@ import * as Square from "../../../../index"; * name: "COOKIE", * quantity: "2", * basePriceMoney: { - * amount: 200, + * amount: BigInt("200"), * currency: "USD" * } * }], diff --git a/src/api/resources/orders/resources/customAttributeDefinitions/client/Client.ts b/src/api/resources/orders/resources/customAttributeDefinitions/client/Client.ts index 37644f68d..8d45dbe07 100644 --- a/src/api/resources/orders/resources/customAttributeDefinitions/client/Client.ts +++ b/src/api/resources/orders/resources/customAttributeDefinitions/client/Client.ts @@ -6,7 +6,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as errors from "../../../../../../errors/index"; export declare namespace CustomAttributeDefinitions { @@ -17,6 +17,8 @@ export declare namespace CustomAttributeDefinitions { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace CustomAttributeDefinitions { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class CustomAttributeDefinitions { - constructor(protected readonly _options: CustomAttributeDefinitions.Options = {}) {} + protected readonly _options: CustomAttributeDefinitions.Options; + + constructor(_options: CustomAttributeDefinitions.Options = {}) { + this._options = _options; + } /** * Lists the order-related [custom attribute definitions](entity:CustomAttributeDefinition) that belong to a Square seller account. @@ -55,83 +61,90 @@ export class CustomAttributeDefinitions { request: Square.orders.ListCustomAttributeDefinitionsRequest = {}, requestOptions?: CustomAttributeDefinitions.RequestOptions, ): Promise> { - const list = async ( - request: Square.orders.ListCustomAttributeDefinitionsRequest, - ): Promise => { - const { visibilityFilter, cursor, limit } = request; - const _queryParams: Record = {}; - if (visibilityFilter !== undefined) { - _queryParams["visibility_filter"] = serializers.VisibilityFilter.jsonOrThrow(visibilityFilter, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/orders/custom-attribute-definitions", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListOrderCustomAttributeDefinitionsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.orders.ListCustomAttributeDefinitionsRequest, + ): Promise> => { + const { visibilityFilter, cursor, limit } = request; + const _queryParams: Record = {}; + if (visibilityFilter !== undefined) { + _queryParams["visibility_filter"] = serializers.VisibilityFilter.jsonOrThrow(visibilityFilter, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/orders/custom-attribute-definitions", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListOrderCustomAttributeDefinitionsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/orders/custom-attribute-definitions.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, - }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/orders/custom-attribute-definitions.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.customAttributeDefinitions ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -163,29 +176,33 @@ export class CustomAttributeDefinitions { * idempotencyKey: "IDEMPOTENCY_KEY" * }) */ - public async create( + public create( request: Square.orders.CreateOrderCustomAttributeDefinitionRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( + request: Square.orders.CreateOrderCustomAttributeDefinitionRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/orders/custom-attribute-definitions", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.orders.CreateOrderCustomAttributeDefinitionRequest.jsonOrThrow(request, { @@ -197,19 +214,23 @@ export class CustomAttributeDefinitions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateOrderCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateOrderCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -218,6 +239,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -226,6 +248,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -245,10 +268,17 @@ export class CustomAttributeDefinitions { * key: "key" * }) */ - public async get( + public get( request: Square.orders.GetCustomAttributeDefinitionsRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.orders.GetCustomAttributeDefinitionsRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): Promise> { const { key, version } = request; const _queryParams: Record = {}; if (version !== undefined) { @@ -256,45 +286,44 @@ export class CustomAttributeDefinitions { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/orders/custom-attribute-definitions/${encodeURIComponent(key)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RetrieveOrderCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RetrieveOrderCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -303,6 +332,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -311,6 +341,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -334,30 +365,34 @@ export class CustomAttributeDefinitions { * idempotencyKey: "IDEMPOTENCY_KEY" * }) */ - public async update( + public update( + request: Square.orders.UpdateOrderCustomAttributeDefinitionRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( request: Square.orders.UpdateOrderCustomAttributeDefinitionRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): Promise> { const { key, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/orders/custom-attribute-definitions/${encodeURIComponent(key)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.orders.UpdateOrderCustomAttributeDefinitionRequest.jsonOrThrow(_body, { @@ -369,19 +404,23 @@ export class CustomAttributeDefinitions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateOrderCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateOrderCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -390,6 +429,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -398,6 +438,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -415,50 +456,56 @@ export class CustomAttributeDefinitions { * key: "key" * }) */ - public async delete( + public delete( request: Square.orders.DeleteCustomAttributeDefinitionsRequest, requestOptions?: CustomAttributeDefinitions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( + request: Square.orders.DeleteCustomAttributeDefinitionsRequest, + requestOptions?: CustomAttributeDefinitions.RequestOptions, + ): Promise> { const { key } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/orders/custom-attribute-definitions/${encodeURIComponent(key)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteOrderCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteOrderCustomAttributeDefinitionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -467,6 +514,7 @@ export class CustomAttributeDefinitions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -475,6 +523,7 @@ export class CustomAttributeDefinitions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/orders/resources/customAttributeDefinitions/client/index.ts b/src/api/resources/orders/resources/customAttributeDefinitions/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/orders/resources/customAttributeDefinitions/client/index.ts +++ b/src/api/resources/orders/resources/customAttributeDefinitions/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/orders/resources/customAttributes/client/Client.ts b/src/api/resources/orders/resources/customAttributes/client/Client.ts index 2a1e2885a..64db52cec 100644 --- a/src/api/resources/orders/resources/customAttributes/client/Client.ts +++ b/src/api/resources/orders/resources/customAttributes/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../../../errors/index"; export declare namespace CustomAttributes { @@ -17,6 +17,8 @@ export declare namespace CustomAttributes { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace CustomAttributes { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class CustomAttributes { - constructor(protected readonly _options: CustomAttributes.Options = {}) {} + protected readonly _options: CustomAttributes.Options; + + constructor(_options: CustomAttributes.Options = {}) { + this._options = _options; + } /** * Deletes order [custom attributes](entity:CustomAttribute) as a bulk operation. @@ -70,29 +76,33 @@ export class CustomAttributes { * } * }) */ - public async batchDelete( + public batchDelete( + request: Square.orders.BulkDeleteOrderCustomAttributesRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchDelete(request, requestOptions)); + } + + private async __batchDelete( request: Square.orders.BulkDeleteOrderCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/orders/custom-attributes/bulk-delete", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.orders.BulkDeleteOrderCustomAttributesRequest.jsonOrThrow(request, { @@ -104,19 +114,23 @@ export class CustomAttributes { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BulkDeleteOrderCustomAttributesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BulkDeleteOrderCustomAttributesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -125,6 +139,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -133,6 +148,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -178,29 +194,33 @@ export class CustomAttributes { * } * }) */ - public async batchUpsert( + public batchUpsert( request: Square.orders.BulkUpsertOrderCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchUpsert(request, requestOptions)); + } + + private async __batchUpsert( + request: Square.orders.BulkUpsertOrderCustomAttributesRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/orders/custom-attributes/bulk-upsert", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.orders.BulkUpsertOrderCustomAttributesRequest.jsonOrThrow(request, { @@ -212,19 +232,23 @@ export class CustomAttributes { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BulkUpsertOrderCustomAttributesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BulkUpsertOrderCustomAttributesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -233,6 +257,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -241,6 +266,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -267,86 +293,93 @@ export class CustomAttributes { request: Square.orders.ListCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, ): Promise> { - const list = async ( - request: Square.orders.ListCustomAttributesRequest, - ): Promise => { - const { orderId, visibilityFilter, cursor, limit, withDefinitions } = request; - const _queryParams: Record = {}; - if (visibilityFilter !== undefined) { - _queryParams["visibility_filter"] = serializers.VisibilityFilter.jsonOrThrow(visibilityFilter, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (withDefinitions !== undefined) { - _queryParams["with_definitions"] = withDefinitions?.toString() ?? null; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - `v2/orders/${encodeURIComponent(orderId)}/custom-attributes`, - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListOrderCustomAttributesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.orders.ListCustomAttributesRequest, + ): Promise> => { + const { orderId, visibilityFilter, cursor, limit, withDefinitions } = request; + const _queryParams: Record = {}; + if (visibilityFilter !== undefined) { + _queryParams["visibility_filter"] = serializers.VisibilityFilter.jsonOrThrow(visibilityFilter, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (withDefinitions !== undefined) { + _queryParams["with_definitions"] = withDefinitions?.toString() ?? null; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + `v2/orders/${encodeURIComponent(orderId)}/custom-attributes`, + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListOrderCustomAttributesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/orders/{order_id}/custom-attributes.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, - }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/orders/{order_id}/custom-attributes.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.customAttributes ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -373,10 +406,17 @@ export class CustomAttributes { * customAttributeKey: "custom_attribute_key" * }) */ - public async get( + public get( request: Square.orders.GetCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.orders.GetCustomAttributesRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): Promise> { const { orderId, customAttributeKey, version, withDefinition } = request; const _queryParams: Record = {}; if (version !== undefined) { @@ -388,45 +428,44 @@ export class CustomAttributes { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/orders/${encodeURIComponent(orderId)}/custom-attributes/${encodeURIComponent(customAttributeKey)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RetrieveOrderCustomAttributeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RetrieveOrderCustomAttributeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -435,6 +474,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -443,6 +483,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -472,30 +513,34 @@ export class CustomAttributes { * } * }) */ - public async upsert( + public upsert( request: Square.orders.UpsertOrderCustomAttributeRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__upsert(request, requestOptions)); + } + + private async __upsert( + request: Square.orders.UpsertOrderCustomAttributeRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): Promise> { const { orderId, customAttributeKey, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/orders/${encodeURIComponent(orderId)}/custom-attributes/${encodeURIComponent(customAttributeKey)}`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.orders.UpsertOrderCustomAttributeRequest.jsonOrThrow(_body, { @@ -507,19 +552,23 @@ export class CustomAttributes { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpsertOrderCustomAttributeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpsertOrderCustomAttributeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -528,6 +577,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -536,6 +586,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -556,50 +607,56 @@ export class CustomAttributes { * customAttributeKey: "custom_attribute_key" * }) */ - public async delete( + public delete( request: Square.orders.DeleteCustomAttributesRequest, requestOptions?: CustomAttributes.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( + request: Square.orders.DeleteCustomAttributesRequest, + requestOptions?: CustomAttributes.RequestOptions, + ): Promise> { const { orderId, customAttributeKey } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/orders/${encodeURIComponent(orderId)}/custom-attributes/${encodeURIComponent(customAttributeKey)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteOrderCustomAttributeResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteOrderCustomAttributeResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -608,6 +665,7 @@ export class CustomAttributes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -616,6 +674,7 @@ export class CustomAttributes { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/orders/resources/customAttributes/client/index.ts b/src/api/resources/orders/resources/customAttributes/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/orders/resources/customAttributes/client/index.ts +++ b/src/api/resources/orders/resources/customAttributes/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/payments/client/Client.ts b/src/api/resources/payments/client/Client.ts index dc078c622..59a822800 100644 --- a/src/api/resources/payments/client/Client.ts +++ b/src/api/resources/payments/client/Client.ts @@ -6,7 +6,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as errors from "../../../../errors/index"; export declare namespace Payments { @@ -17,6 +17,8 @@ export declare namespace Payments { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Payments { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Payments { - constructor(protected readonly _options: Payments.Options = {}) {} + protected readonly _options: Payments.Options; + + constructor(_options: Payments.Options = {}) { + this._options = _options; + } /** * Retrieves a list of payments taken by the account making the request. @@ -55,131 +61,138 @@ export class Payments { request: Square.ListPaymentsRequest = {}, requestOptions?: Payments.RequestOptions, ): Promise> { - const list = async (request: Square.ListPaymentsRequest): Promise => { - const { - beginTime, - endTime, - sortOrder, - cursor, - locationId, - total, - last4, - cardBrand, - limit, - isOfflinePayment, - offlineBeginTime, - offlineEndTime, - updatedAtBeginTime, - updatedAtEndTime, - sortField, - } = request; - const _queryParams: Record = {}; - if (beginTime !== undefined) { - _queryParams["begin_time"] = beginTime; - } - if (endTime !== undefined) { - _queryParams["end_time"] = endTime; - } - if (sortOrder !== undefined) { - _queryParams["sort_order"] = sortOrder; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (locationId !== undefined) { - _queryParams["location_id"] = locationId; - } - if (total !== undefined) { - _queryParams["total"] = total?.toString() ?? null; - } - if (last4 !== undefined) { - _queryParams["last_4"] = last4; - } - if (cardBrand !== undefined) { - _queryParams["card_brand"] = cardBrand; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (isOfflinePayment !== undefined) { - _queryParams["is_offline_payment"] = isOfflinePayment?.toString() ?? null; - } - if (offlineBeginTime !== undefined) { - _queryParams["offline_begin_time"] = offlineBeginTime; - } - if (offlineEndTime !== undefined) { - _queryParams["offline_end_time"] = offlineEndTime; - } - if (updatedAtBeginTime !== undefined) { - _queryParams["updated_at_begin_time"] = updatedAtBeginTime; - } - if (updatedAtEndTime !== undefined) { - _queryParams["updated_at_end_time"] = updatedAtEndTime; - } - if (sortField !== undefined) { - _queryParams["sort_field"] = serializers.ListPaymentsRequestSortField.jsonOrThrow(sortField, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/payments", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListPaymentsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async (request: Square.ListPaymentsRequest): Promise> => { + const { + beginTime, + endTime, + sortOrder, + cursor, + locationId, + total, + last4, + cardBrand, + limit, + isOfflinePayment, + offlineBeginTime, + offlineEndTime, + updatedAtBeginTime, + updatedAtEndTime, + sortField, + } = request; + const _queryParams: Record = {}; + if (beginTime !== undefined) { + _queryParams["begin_time"] = beginTime; + } + if (endTime !== undefined) { + _queryParams["end_time"] = endTime; + } + if (sortOrder !== undefined) { + _queryParams["sort_order"] = sortOrder; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (locationId !== undefined) { + _queryParams["location_id"] = locationId; + } + if (total !== undefined) { + _queryParams["total"] = total?.toString() ?? null; + } + if (last4 !== undefined) { + _queryParams["last_4"] = last4; + } + if (cardBrand !== undefined) { + _queryParams["card_brand"] = cardBrand; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (isOfflinePayment !== undefined) { + _queryParams["is_offline_payment"] = isOfflinePayment?.toString() ?? null; + } + if (offlineBeginTime !== undefined) { + _queryParams["offline_begin_time"] = offlineBeginTime; + } + if (offlineEndTime !== undefined) { + _queryParams["offline_end_time"] = offlineEndTime; + } + if (updatedAtBeginTime !== undefined) { + _queryParams["updated_at_begin_time"] = updatedAtBeginTime; + } + if (updatedAtEndTime !== undefined) { + _queryParams["updated_at_end_time"] = updatedAtEndTime; + } + if (sortField !== undefined) { + _queryParams["sort_field"] = serializers.ListPaymentsRequestSortField.jsonOrThrow(sortField, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/payments", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListPaymentsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/payments."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/payments."); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.payments ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -205,11 +218,11 @@ export class Payments { * sourceId: "ccof:GaJGNaZa8x4OgDJn4GB", * idempotencyKey: "7b0f3ec5-086a-4871-8f13-3c81b3875218", * amountMoney: { - * amount: 1000, + * amount: BigInt("1000"), * currency: "USD" * }, * appFeeMoney: { - * amount: 10, + * amount: BigInt("10"), * currency: "USD" * }, * autocomplete: true, @@ -219,29 +232,33 @@ export class Payments { * note: "Brief description" * }) */ - public async create( + public create( + request: Square.CreatePaymentRequest, + requestOptions?: Payments.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( request: Square.CreatePaymentRequest, requestOptions?: Payments.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/payments", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CreatePaymentRequest.jsonOrThrow(request, { @@ -253,19 +270,23 @@ export class Payments { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreatePaymentResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreatePaymentResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -274,12 +295,14 @@ export class Payments { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/payments."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -305,29 +328,33 @@ export class Payments { * idempotencyKey: "a7e36d40-d24b-11e8-b568-0800200c9a66" * }) */ - public async cancelByIdempotencyKey( + public cancelByIdempotencyKey( request: Square.CancelPaymentByIdempotencyKeyRequest, requestOptions?: Payments.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__cancelByIdempotencyKey(request, requestOptions)); + } + + private async __cancelByIdempotencyKey( + request: Square.CancelPaymentByIdempotencyKeyRequest, + requestOptions?: Payments.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/payments/cancel", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CancelPaymentByIdempotencyKeyRequest.jsonOrThrow(request, { @@ -339,19 +366,23 @@ export class Payments { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CancelPaymentByIdempotencyKeyResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CancelPaymentByIdempotencyKeyResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -360,12 +391,14 @@ export class Payments { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/payments/cancel."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -381,50 +414,56 @@ export class Payments { * paymentId: "payment_id" * }) */ - public async get( + public get( + request: Square.GetPaymentsRequest, + requestOptions?: Payments.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.GetPaymentsRequest, requestOptions?: Payments.RequestOptions, - ): Promise { + ): Promise> { const { paymentId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/payments/${encodeURIComponent(paymentId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetPaymentResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetPaymentResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -433,12 +472,14 @@ export class Payments { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/payments/{payment_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -455,11 +496,11 @@ export class Payments { * paymentId: "payment_id", * payment: { * amountMoney: { - * amount: 1000, + * amount: BigInt("1000"), * currency: "USD" * }, * tipMoney: { - * amount: 100, + * amount: BigInt("100"), * currency: "USD" * }, * versionToken: "ODhwVQ35xwlzRuoZEwKXucfu7583sPTzK48c5zoGd0g6o" @@ -467,30 +508,34 @@ export class Payments { * idempotencyKey: "956f8b13-e4ec-45d6-85e8-d1d95ef0c5de" * }) */ - public async update( + public update( + request: Square.UpdatePaymentRequest, + requestOptions?: Payments.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( request: Square.UpdatePaymentRequest, requestOptions?: Payments.RequestOptions, - ): Promise { + ): Promise> { const { paymentId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/payments/${encodeURIComponent(paymentId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.UpdatePaymentRequest.jsonOrThrow(_body, { @@ -502,19 +547,23 @@ export class Payments { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdatePaymentResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdatePaymentResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -523,12 +572,14 @@ export class Payments { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling PUT /v2/payments/{payment_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -545,50 +596,56 @@ export class Payments { * paymentId: "payment_id" * }) */ - public async cancel( + public cancel( + request: Square.CancelPaymentsRequest, + requestOptions?: Payments.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__cancel(request, requestOptions)); + } + + private async __cancel( request: Square.CancelPaymentsRequest, requestOptions?: Payments.RequestOptions, - ): Promise { + ): Promise> { const { paymentId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/payments/${encodeURIComponent(paymentId)}/cancel`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CancelPaymentResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CancelPaymentResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -597,6 +654,7 @@ export class Payments { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -605,6 +663,7 @@ export class Payments { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -623,30 +682,34 @@ export class Payments { * paymentId: "payment_id" * }) */ - public async complete( + public complete( + request: Square.CompletePaymentRequest, + requestOptions?: Payments.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__complete(request, requestOptions)); + } + + private async __complete( request: Square.CompletePaymentRequest, requestOptions?: Payments.RequestOptions, - ): Promise { + ): Promise> { const { paymentId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/payments/${encodeURIComponent(paymentId)}/complete`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CompletePaymentRequest.jsonOrThrow(_body, { @@ -658,19 +721,23 @@ export class Payments { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CompletePaymentResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CompletePaymentResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -679,6 +746,7 @@ export class Payments { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -687,6 +755,7 @@ export class Payments { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/payments/client/index.ts b/src/api/resources/payments/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/payments/client/index.ts +++ b/src/api/resources/payments/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/payments/client/requests/CreatePaymentRequest.ts b/src/api/resources/payments/client/requests/CreatePaymentRequest.ts index 8c7756897..b9a1ae46a 100644 --- a/src/api/resources/payments/client/requests/CreatePaymentRequest.ts +++ b/src/api/resources/payments/client/requests/CreatePaymentRequest.ts @@ -10,11 +10,11 @@ import * as Square from "../../../../index"; * sourceId: "ccof:GaJGNaZa8x4OgDJn4GB", * idempotencyKey: "7b0f3ec5-086a-4871-8f13-3c81b3875218", * amountMoney: { - * amount: 1000, + * amount: BigInt("1000"), * currency: "USD" * }, * appFeeMoney: { - * amount: 10, + * amount: BigInt("10"), * currency: "USD" * }, * autocomplete: true, diff --git a/src/api/resources/payments/client/requests/UpdatePaymentRequest.ts b/src/api/resources/payments/client/requests/UpdatePaymentRequest.ts index 62e6078ab..d6f7f9ba9 100644 --- a/src/api/resources/payments/client/requests/UpdatePaymentRequest.ts +++ b/src/api/resources/payments/client/requests/UpdatePaymentRequest.ts @@ -10,11 +10,11 @@ import * as Square from "../../../../index"; * paymentId: "payment_id", * payment: { * amountMoney: { - * amount: 1000, + * amount: BigInt("1000"), * currency: "USD" * }, * tipMoney: { - * amount: 100, + * amount: BigInt("100"), * currency: "USD" * }, * versionToken: "ODhwVQ35xwlzRuoZEwKXucfu7583sPTzK48c5zoGd0g6o" diff --git a/src/api/resources/payouts/client/Client.ts b/src/api/resources/payouts/client/Client.ts index 3c93d7455..b7218ad9e 100644 --- a/src/api/resources/payouts/client/Client.ts +++ b/src/api/resources/payouts/client/Client.ts @@ -6,7 +6,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as errors from "../../../../errors/index"; export declare namespace Payouts { @@ -17,6 +17,8 @@ export declare namespace Payouts { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Payouts { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Payouts { - constructor(protected readonly _options: Payouts.Options = {}) {} + protected readonly _options: Payouts.Options; + + constructor(_options: Payouts.Options = {}) { + this._options = _options; + } /** * Retrieves a list of all payouts for the default location. @@ -52,94 +58,101 @@ export class Payouts { request: Square.ListPayoutsRequest = {}, requestOptions?: Payouts.RequestOptions, ): Promise> { - const list = async (request: Square.ListPayoutsRequest): Promise => { - const { locationId, status, beginTime, endTime, sortOrder, cursor, limit } = request; - const _queryParams: Record = {}; - if (locationId !== undefined) { - _queryParams["location_id"] = locationId; - } - if (status !== undefined) { - _queryParams["status"] = serializers.PayoutStatus.jsonOrThrow(status, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - if (beginTime !== undefined) { - _queryParams["begin_time"] = beginTime; - } - if (endTime !== undefined) { - _queryParams["end_time"] = endTime; - } - if (sortOrder !== undefined) { - _queryParams["sort_order"] = serializers.SortOrder.jsonOrThrow(sortOrder, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/payouts", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListPayoutsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async (request: Square.ListPayoutsRequest): Promise> => { + const { locationId, status, beginTime, endTime, sortOrder, cursor, limit } = request; + const _queryParams: Record = {}; + if (locationId !== undefined) { + _queryParams["location_id"] = locationId; + } + if (status !== undefined) { + _queryParams["status"] = serializers.PayoutStatus.jsonOrThrow(status, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + if (beginTime !== undefined) { + _queryParams["begin_time"] = beginTime; + } + if (endTime !== undefined) { + _queryParams["end_time"] = endTime; + } + if (sortOrder !== undefined) { + _queryParams["sort_order"] = serializers.SortOrder.jsonOrThrow(sortOrder, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/payouts", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListPayoutsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/payouts."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/payouts."); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.payouts ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -159,50 +172,56 @@ export class Payouts { * payoutId: "payout_id" * }) */ - public async get( + public get( + request: Square.GetPayoutsRequest, + requestOptions?: Payouts.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.GetPayoutsRequest, requestOptions?: Payouts.RequestOptions, - ): Promise { + ): Promise> { const { payoutId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/payouts/${encodeURIComponent(payoutId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetPayoutResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetPayoutResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -211,12 +230,14 @@ export class Payouts { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/payouts/{payout_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -237,81 +258,90 @@ export class Payouts { request: Square.ListEntriesPayoutsRequest, requestOptions?: Payouts.RequestOptions, ): Promise> { - const list = async (request: Square.ListEntriesPayoutsRequest): Promise => { - const { payoutId, sortOrder, cursor, limit } = request; - const _queryParams: Record = {}; - if (sortOrder !== undefined) { - _queryParams["sort_order"] = serializers.SortOrder.jsonOrThrow(sortOrder, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - `v2/payouts/${encodeURIComponent(payoutId)}/payout-entries`, - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListPayoutEntriesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.ListEntriesPayoutsRequest, + ): Promise> => { + const { payoutId, sortOrder, cursor, limit } = request; + const _queryParams: Record = {}; + if (sortOrder !== undefined) { + _queryParams["sort_order"] = serializers.SortOrder.jsonOrThrow(sortOrder, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + `v2/payouts/${encodeURIComponent(payoutId)}/payout-entries`, + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListPayoutEntriesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/payouts/{payout_id}/payout-entries.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, - }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/payouts/{payout_id}/payout-entries.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.payoutEntries ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); diff --git a/src/api/resources/payouts/client/index.ts b/src/api/resources/payouts/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/payouts/client/index.ts +++ b/src/api/resources/payouts/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/refunds/client/Client.ts b/src/api/resources/refunds/client/Client.ts index 6e3a3c843..3fdccf8be 100644 --- a/src/api/resources/refunds/client/Client.ts +++ b/src/api/resources/refunds/client/Client.ts @@ -6,7 +6,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as errors from "../../../../errors/index"; export declare namespace Refunds { @@ -17,6 +17,8 @@ export declare namespace Refunds { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Refunds { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Refunds { - constructor(protected readonly _options: Refunds.Options = {}) {} + protected readonly _options: Refunds.Options; + + constructor(_options: Refunds.Options = {}) { + this._options = _options; + } /** * Retrieves a list of refunds for the account making the request. @@ -55,115 +61,124 @@ export class Refunds { request: Square.ListRefundsRequest = {}, requestOptions?: Refunds.RequestOptions, ): Promise> { - const list = async (request: Square.ListRefundsRequest): Promise => { - const { - beginTime, - endTime, - sortOrder, - cursor, - locationId, - status, - sourceType, - limit, - updatedAtBeginTime, - updatedAtEndTime, - sortField, - } = request; - const _queryParams: Record = {}; - if (beginTime !== undefined) { - _queryParams["begin_time"] = beginTime; - } - if (endTime !== undefined) { - _queryParams["end_time"] = endTime; - } - if (sortOrder !== undefined) { - _queryParams["sort_order"] = sortOrder; - } - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (locationId !== undefined) { - _queryParams["location_id"] = locationId; - } - if (status !== undefined) { - _queryParams["status"] = status; - } - if (sourceType !== undefined) { - _queryParams["source_type"] = sourceType; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - if (updatedAtBeginTime !== undefined) { - _queryParams["updated_at_begin_time"] = updatedAtBeginTime; - } - if (updatedAtEndTime !== undefined) { - _queryParams["updated_at_end_time"] = updatedAtEndTime; - } - if (sortField !== undefined) { - _queryParams["sort_field"] = serializers.ListPaymentRefundsRequestSortField.jsonOrThrow(sortField, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/refunds", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListPaymentRefundsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.ListRefundsRequest, + ): Promise> => { + const { + beginTime, + endTime, + sortOrder, + cursor, + locationId, + status, + sourceType, + limit, + updatedAtBeginTime, + updatedAtEndTime, + sortField, + } = request; + const _queryParams: Record = {}; + if (beginTime !== undefined) { + _queryParams["begin_time"] = beginTime; + } + if (endTime !== undefined) { + _queryParams["end_time"] = endTime; + } + if (sortOrder !== undefined) { + _queryParams["sort_order"] = sortOrder; + } + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (locationId !== undefined) { + _queryParams["location_id"] = locationId; + } + if (status !== undefined) { + _queryParams["status"] = status; + } + if (sourceType !== undefined) { + _queryParams["source_type"] = sourceType; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + if (updatedAtBeginTime !== undefined) { + _queryParams["updated_at_begin_time"] = updatedAtBeginTime; + } + if (updatedAtEndTime !== undefined) { + _queryParams["updated_at_end_time"] = updatedAtEndTime; + } + if (sortField !== undefined) { + _queryParams["sort_field"] = serializers.ListPaymentRefundsRequestSortField.jsonOrThrow(sortField, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/refunds", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListPaymentRefundsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/refunds."); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/refunds."); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.refunds ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -184,40 +199,44 @@ export class Refunds { * await client.refunds.refundPayment({ * idempotencyKey: "9b7f2dcf-49da-4411-b23e-a2d6af21333a", * amountMoney: { - * amount: 1000, + * amount: BigInt("1000"), * currency: "USD" * }, * appFeeMoney: { - * amount: 10, + * amount: BigInt("10"), * currency: "USD" * }, * paymentId: "R2B3Z8WMVt3EAmzYWLZvz7Y69EbZY", * reason: "Example" * }) */ - public async refundPayment( + public refundPayment( request: Square.RefundPaymentRequest, requestOptions?: Refunds.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__refundPayment(request, requestOptions)); + } + + private async __refundPayment( + request: Square.RefundPaymentRequest, + requestOptions?: Refunds.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/refunds", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.RefundPaymentRequest.jsonOrThrow(request, { @@ -229,19 +248,23 @@ export class Refunds { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RefundPaymentResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RefundPaymentResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -250,12 +273,14 @@ export class Refunds { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/refunds."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -271,50 +296,56 @@ export class Refunds { * refundId: "refund_id" * }) */ - public async get( + public get( + request: Square.GetRefundsRequest, + requestOptions?: Refunds.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.GetRefundsRequest, requestOptions?: Refunds.RequestOptions, - ): Promise { + ): Promise> { const { refundId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/refunds/${encodeURIComponent(refundId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetPaymentRefundResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetPaymentRefundResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -323,12 +354,14 @@ export class Refunds { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/refunds/{refund_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/refunds/client/index.ts b/src/api/resources/refunds/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/refunds/client/index.ts +++ b/src/api/resources/refunds/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/refunds/client/requests/RefundPaymentRequest.ts b/src/api/resources/refunds/client/requests/RefundPaymentRequest.ts index bc21d1716..9d700e817 100644 --- a/src/api/resources/refunds/client/requests/RefundPaymentRequest.ts +++ b/src/api/resources/refunds/client/requests/RefundPaymentRequest.ts @@ -9,11 +9,11 @@ import * as Square from "../../../../index"; * { * idempotencyKey: "9b7f2dcf-49da-4411-b23e-a2d6af21333a", * amountMoney: { - * amount: 1000, + * amount: BigInt("1000"), * currency: "USD" * }, * appFeeMoney: { - * amount: 10, + * amount: BigInt("10"), * currency: "USD" * }, * paymentId: "R2B3Z8WMVt3EAmzYWLZvz7Y69EbZY", diff --git a/src/api/resources/sites/client/Client.ts b/src/api/resources/sites/client/Client.ts index 0ee7341e5..f31ffdf7d 100644 --- a/src/api/resources/sites/client/Client.ts +++ b/src/api/resources/sites/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; import * as errors from "../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace Sites { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Sites { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Sites { - constructor(protected readonly _options: Sites.Options = {}) {} + protected readonly _options: Sites.Options; + + constructor(_options: Sites.Options = {}) { + this._options = _options; + } /** * Lists the Square Online sites that belong to a seller. Sites are listed in descending order by the `created_at` date. @@ -48,46 +54,51 @@ export class Sites { * @example * await client.sites.list() */ - public async list(requestOptions?: Sites.RequestOptions): Promise { + public list(requestOptions?: Sites.RequestOptions): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__list(requestOptions)); + } + + private async __list( + requestOptions?: Sites.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/sites", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.ListSitesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.ListSitesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -96,12 +107,14 @@ export class Sites { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/sites."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/snippets/client/Client.ts b/src/api/resources/snippets/client/Client.ts index 04ef500f3..307a4bbe8 100644 --- a/src/api/resources/snippets/client/Client.ts +++ b/src/api/resources/snippets/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; import * as errors from "../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace Snippets { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Snippets { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Snippets { - constructor(protected readonly _options: Snippets.Options = {}) {} + protected readonly _options: Snippets.Options; + + constructor(_options: Snippets.Options = {}) { + this._options = _options; + } /** * Retrieves your snippet from a Square Online site. A site can contain snippets from multiple snippet applications, but you can retrieve only the snippet that was added by your application. @@ -53,50 +59,56 @@ export class Snippets { * siteId: "site_id" * }) */ - public async get( + public get( + request: Square.GetSnippetsRequest, + requestOptions?: Snippets.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.GetSnippetsRequest, requestOptions?: Snippets.RequestOptions, - ): Promise { + ): Promise> { const { siteId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/sites/${encodeURIComponent(siteId)}/snippet`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetSnippetResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetSnippetResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -105,12 +117,14 @@ export class Snippets { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/sites/{site_id}/snippet."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -135,30 +149,34 @@ export class Snippets { * } * }) */ - public async upsert( + public upsert( + request: Square.UpsertSnippetRequest, + requestOptions?: Snippets.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__upsert(request, requestOptions)); + } + + private async __upsert( request: Square.UpsertSnippetRequest, requestOptions?: Snippets.RequestOptions, - ): Promise { + ): Promise> { const { siteId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/sites/${encodeURIComponent(siteId)}/snippet`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.UpsertSnippetRequest.jsonOrThrow(_body, { @@ -170,19 +188,23 @@ export class Snippets { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpsertSnippetResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpsertSnippetResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -191,12 +213,14 @@ export class Snippets { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/sites/{site_id}/snippet."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -217,50 +241,56 @@ export class Snippets { * siteId: "site_id" * }) */ - public async delete( + public delete( + request: Square.DeleteSnippetsRequest, + requestOptions?: Snippets.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( request: Square.DeleteSnippetsRequest, requestOptions?: Snippets.RequestOptions, - ): Promise { + ): Promise> { const { siteId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/sites/${encodeURIComponent(siteId)}/snippet`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteSnippetResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteSnippetResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -269,6 +299,7 @@ export class Snippets { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -277,6 +308,7 @@ export class Snippets { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/snippets/client/index.ts b/src/api/resources/snippets/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/snippets/client/index.ts +++ b/src/api/resources/snippets/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/subscriptions/client/Client.ts b/src/api/resources/subscriptions/client/Client.ts index 24b43ad53..bf1b13f10 100644 --- a/src/api/resources/subscriptions/client/Client.ts +++ b/src/api/resources/subscriptions/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../errors/index"; export declare namespace Subscriptions { @@ -17,6 +17,8 @@ export declare namespace Subscriptions { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Subscriptions { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Subscriptions { - constructor(protected readonly _options: Subscriptions.Options = {}) {} + protected readonly _options: Subscriptions.Options; + + constructor(_options: Subscriptions.Options = {}) { + this._options = _options; + } /** * Enrolls a customer in a subscription. @@ -63,34 +69,38 @@ export class Subscriptions { * name: "My Application" * }, * phases: [{ - * ordinal: 0, + * ordinal: BigInt("0"), * orderTemplateId: "U2NaowWxzXwpsZU697x7ZHOAnCNZY" * }] * }) */ - public async create( + public create( + request: Square.CreateSubscriptionRequest, + requestOptions?: Subscriptions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( request: Square.CreateSubscriptionRequest, requestOptions?: Subscriptions.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/subscriptions", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CreateSubscriptionRequest.jsonOrThrow(request, { @@ -102,19 +112,23 @@ export class Subscriptions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateSubscriptionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateSubscriptionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -123,12 +137,14 @@ export class Subscriptions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/subscriptions."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -147,29 +163,33 @@ export class Subscriptions { * locationId: "S8GWD5R9QB376" * }) */ - public async bulkSwapPlan( + public bulkSwapPlan( + request: Square.BulkSwapPlanRequest, + requestOptions?: Subscriptions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__bulkSwapPlan(request, requestOptions)); + } + + private async __bulkSwapPlan( request: Square.BulkSwapPlanRequest, requestOptions?: Subscriptions.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/subscriptions/bulk-swap-plan", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BulkSwapPlanRequest.jsonOrThrow(request, { @@ -181,19 +201,23 @@ export class Subscriptions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BulkSwapPlanResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BulkSwapPlanResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -202,6 +226,7 @@ export class Subscriptions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -210,6 +235,7 @@ export class Subscriptions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -244,29 +270,33 @@ export class Subscriptions { * } * }) */ - public async search( + public search( + request: Square.SearchSubscriptionsRequest = {}, + requestOptions?: Subscriptions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__search(request, requestOptions)); + } + + private async __search( request: Square.SearchSubscriptionsRequest = {}, requestOptions?: Subscriptions.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/subscriptions/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.SearchSubscriptionsRequest.jsonOrThrow(request, { @@ -278,19 +308,23 @@ export class Subscriptions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchSubscriptionsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchSubscriptionsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -299,12 +333,14 @@ export class Subscriptions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/subscriptions/search."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -320,10 +356,17 @@ export class Subscriptions { * subscriptionId: "subscription_id" * }) */ - public async get( + public get( request: Square.GetSubscriptionsRequest, requestOptions?: Subscriptions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.GetSubscriptionsRequest, + requestOptions?: Subscriptions.RequestOptions, + ): Promise> { const { subscriptionId, include } = request; const _queryParams: Record = {}; if (include !== undefined) { @@ -331,45 +374,44 @@ export class Subscriptions { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/subscriptions/${encodeURIComponent(subscriptionId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetSubscriptionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetSubscriptionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -378,6 +420,7 @@ export class Subscriptions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -386,6 +429,7 @@ export class Subscriptions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -405,30 +449,34 @@ export class Subscriptions { * } * }) */ - public async update( + public update( + request: Square.UpdateSubscriptionRequest, + requestOptions?: Subscriptions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( request: Square.UpdateSubscriptionRequest, requestOptions?: Subscriptions.RequestOptions, - ): Promise { + ): Promise> { const { subscriptionId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/subscriptions/${encodeURIComponent(subscriptionId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.UpdateSubscriptionRequest.jsonOrThrow(_body, { @@ -440,19 +488,23 @@ export class Subscriptions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateSubscriptionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateSubscriptionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -461,6 +513,7 @@ export class Subscriptions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -469,6 +522,7 @@ export class Subscriptions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -485,50 +539,56 @@ export class Subscriptions { * actionId: "action_id" * }) */ - public async deleteAction( + public deleteAction( + request: Square.DeleteActionSubscriptionsRequest, + requestOptions?: Subscriptions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__deleteAction(request, requestOptions)); + } + + private async __deleteAction( request: Square.DeleteActionSubscriptionsRequest, requestOptions?: Subscriptions.RequestOptions, - ): Promise { + ): Promise> { const { subscriptionId, actionId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/subscriptions/${encodeURIComponent(subscriptionId)}/actions/${encodeURIComponent(actionId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteSubscriptionActionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteSubscriptionActionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -537,6 +597,7 @@ export class Subscriptions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -545,6 +606,7 @@ export class Subscriptions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -562,30 +624,34 @@ export class Subscriptions { * monthlyBillingAnchorDate: 1 * }) */ - public async changeBillingAnchorDate( + public changeBillingAnchorDate( + request: Square.ChangeBillingAnchorDateRequest, + requestOptions?: Subscriptions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__changeBillingAnchorDate(request, requestOptions)); + } + + private async __changeBillingAnchorDate( request: Square.ChangeBillingAnchorDateRequest, requestOptions?: Subscriptions.RequestOptions, - ): Promise { + ): Promise> { const { subscriptionId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/subscriptions/${encodeURIComponent(subscriptionId)}/billing-anchor`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.ChangeBillingAnchorDateRequest.jsonOrThrow(_body, { @@ -597,19 +663,23 @@ export class Subscriptions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.ChangeBillingAnchorDateResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.ChangeBillingAnchorDateResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -618,6 +688,7 @@ export class Subscriptions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -626,6 +697,7 @@ export class Subscriptions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -643,50 +715,56 @@ export class Subscriptions { * subscriptionId: "subscription_id" * }) */ - public async cancel( + public cancel( + request: Square.CancelSubscriptionsRequest, + requestOptions?: Subscriptions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__cancel(request, requestOptions)); + } + + private async __cancel( request: Square.CancelSubscriptionsRequest, requestOptions?: Subscriptions.RequestOptions, - ): Promise { + ): Promise> { const { subscriptionId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/subscriptions/${encodeURIComponent(subscriptionId)}/cancel`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CancelSubscriptionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CancelSubscriptionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -695,6 +773,7 @@ export class Subscriptions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -703,6 +782,7 @@ export class Subscriptions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -722,77 +802,84 @@ export class Subscriptions { request: Square.ListEventsSubscriptionsRequest, requestOptions?: Subscriptions.RequestOptions, ): Promise> { - const list = async ( - request: Square.ListEventsSubscriptionsRequest, - ): Promise => { - const { subscriptionId, cursor, limit } = request; - const _queryParams: Record = {}; - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - `v2/subscriptions/${encodeURIComponent(subscriptionId)}/events`, - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListSubscriptionEventsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.ListEventsSubscriptionsRequest, + ): Promise> => { + const { subscriptionId, cursor, limit } = request; + const _queryParams: Record = {}; + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + `v2/subscriptions/${encodeURIComponent(subscriptionId)}/events`, + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, - }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListSubscriptionEventsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/subscriptions/{subscription_id}/events.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/subscriptions/{subscription_id}/events.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.subscriptionEvents ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -811,30 +898,34 @@ export class Subscriptions { * subscriptionId: "subscription_id" * }) */ - public async pause( + public pause( + request: Square.PauseSubscriptionRequest, + requestOptions?: Subscriptions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__pause(request, requestOptions)); + } + + private async __pause( request: Square.PauseSubscriptionRequest, requestOptions?: Subscriptions.RequestOptions, - ): Promise { + ): Promise> { const { subscriptionId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/subscriptions/${encodeURIComponent(subscriptionId)}/pause`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.PauseSubscriptionRequest.jsonOrThrow(_body, { @@ -846,19 +937,23 @@ export class Subscriptions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.PauseSubscriptionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.PauseSubscriptionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -867,6 +962,7 @@ export class Subscriptions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -875,6 +971,7 @@ export class Subscriptions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -890,30 +987,34 @@ export class Subscriptions { * subscriptionId: "subscription_id" * }) */ - public async resume( + public resume( + request: Square.ResumeSubscriptionRequest, + requestOptions?: Subscriptions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__resume(request, requestOptions)); + } + + private async __resume( request: Square.ResumeSubscriptionRequest, requestOptions?: Subscriptions.RequestOptions, - ): Promise { + ): Promise> { const { subscriptionId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/subscriptions/${encodeURIComponent(subscriptionId)}/resume`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.ResumeSubscriptionRequest.jsonOrThrow(_body, { @@ -925,19 +1026,23 @@ export class Subscriptions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.ResumeSubscriptionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.ResumeSubscriptionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -946,6 +1051,7 @@ export class Subscriptions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -954,6 +1060,7 @@ export class Subscriptions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -970,35 +1077,39 @@ export class Subscriptions { * subscriptionId: "subscription_id", * newPlanVariationId: "FQ7CDXXWSLUJRPM3GFJSJGZ7", * phases: [{ - * ordinal: 0, + * ordinal: BigInt("0"), * orderTemplateId: "uhhnjH9osVv3shUADwaC0b3hNxQZY" * }] * }) */ - public async swapPlan( + public swapPlan( + request: Square.SwapPlanRequest, + requestOptions?: Subscriptions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__swapPlan(request, requestOptions)); + } + + private async __swapPlan( request: Square.SwapPlanRequest, requestOptions?: Subscriptions.RequestOptions, - ): Promise { + ): Promise> { const { subscriptionId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/subscriptions/${encodeURIComponent(subscriptionId)}/swap-plan`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.SwapPlanRequest.jsonOrThrow(_body, { @@ -1010,19 +1121,23 @@ export class Subscriptions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SwapPlanResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SwapPlanResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -1031,6 +1146,7 @@ export class Subscriptions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -1039,6 +1155,7 @@ export class Subscriptions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/subscriptions/client/index.ts b/src/api/resources/subscriptions/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/subscriptions/client/index.ts +++ b/src/api/resources/subscriptions/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/subscriptions/client/requests/CreateSubscriptionRequest.ts b/src/api/resources/subscriptions/client/requests/CreateSubscriptionRequest.ts index 027cf2e8c..0c9cffa77 100644 --- a/src/api/resources/subscriptions/client/requests/CreateSubscriptionRequest.ts +++ b/src/api/resources/subscriptions/client/requests/CreateSubscriptionRequest.ts @@ -18,7 +18,7 @@ import * as Square from "../../../../index"; * name: "My Application" * }, * phases: [{ - * ordinal: 0, + * ordinal: BigInt("0"), * orderTemplateId: "U2NaowWxzXwpsZU697x7ZHOAnCNZY" * }] * } diff --git a/src/api/resources/subscriptions/client/requests/SwapPlanRequest.ts b/src/api/resources/subscriptions/client/requests/SwapPlanRequest.ts index 56fede5b6..0b09db27f 100644 --- a/src/api/resources/subscriptions/client/requests/SwapPlanRequest.ts +++ b/src/api/resources/subscriptions/client/requests/SwapPlanRequest.ts @@ -10,7 +10,7 @@ import * as Square from "../../../../index"; * subscriptionId: "subscription_id", * newPlanVariationId: "FQ7CDXXWSLUJRPM3GFJSJGZ7", * phases: [{ - * ordinal: 0, + * ordinal: BigInt("0"), * orderTemplateId: "uhhnjH9osVv3shUADwaC0b3hNxQZY" * }] * } diff --git a/src/api/resources/team/client/Client.ts b/src/api/resources/team/client/Client.ts index c93e3937c..1868d491d 100644 --- a/src/api/resources/team/client/Client.ts +++ b/src/api/resources/team/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; import * as errors from "../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace Team { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Team { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Team { - constructor(protected readonly _options: Team.Options = {}) {} + protected readonly _options: Team.Options; + + constructor(_options: Team.Options = {}) { + this._options = _options; + } /** * Lists jobs in a seller account. Results are sorted by title in ascending order. @@ -46,10 +52,17 @@ export class Team { * @example * await client.team.listJobs() */ - public async listJobs( + public listJobs( + request: Square.ListJobsRequest = {}, + requestOptions?: Team.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__listJobs(request, requestOptions)); + } + + private async __listJobs( request: Square.ListJobsRequest = {}, requestOptions?: Team.RequestOptions, - ): Promise { + ): Promise> { const { cursor } = request; const _queryParams: Record = {}; if (cursor !== undefined) { @@ -57,45 +70,44 @@ export class Team { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/team-members/jobs", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.ListJobsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.ListJobsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -104,12 +116,14 @@ export class Team { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/team-members/jobs."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -130,29 +144,33 @@ export class Team { * idempotencyKey: "idempotency-key-0" * }) */ - public async createJob( + public createJob( request: Square.CreateJobRequest, requestOptions?: Team.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__createJob(request, requestOptions)); + } + + private async __createJob( + request: Square.CreateJobRequest, + requestOptions?: Team.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/team-members/jobs", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CreateJobRequest.jsonOrThrow(request, { @@ -164,19 +182,23 @@ export class Team { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateJobResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateJobResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -185,12 +207,14 @@ export class Team { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/team-members/jobs."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -206,50 +230,56 @@ export class Team { * jobId: "job_id" * }) */ - public async retrieveJob( + public retrieveJob( + request: Square.RetrieveJobRequest, + requestOptions?: Team.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__retrieveJob(request, requestOptions)); + } + + private async __retrieveJob( request: Square.RetrieveJobRequest, requestOptions?: Team.RequestOptions, - ): Promise { + ): Promise> { const { jobId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/team-members/jobs/${encodeURIComponent(jobId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.RetrieveJobResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.RetrieveJobResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -258,6 +288,7 @@ export class Team { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -266,6 +297,7 @@ export class Team { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -287,30 +319,34 @@ export class Team { * } * }) */ - public async updateJob( + public updateJob( request: Square.UpdateJobRequest, requestOptions?: Team.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__updateJob(request, requestOptions)); + } + + private async __updateJob( + request: Square.UpdateJobRequest, + requestOptions?: Team.RequestOptions, + ): Promise> { const { jobId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/team-members/jobs/${encodeURIComponent(jobId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.UpdateJobRequest.jsonOrThrow(_body, { @@ -322,19 +358,23 @@ export class Team { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateJobResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateJobResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -343,6 +383,7 @@ export class Team { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -351,6 +392,7 @@ export class Team { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/team/client/index.ts b/src/api/resources/team/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/team/client/index.ts +++ b/src/api/resources/team/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/teamMembers/client/Client.ts b/src/api/resources/teamMembers/client/Client.ts index ab0aef909..ec4a7de87 100644 --- a/src/api/resources/teamMembers/client/Client.ts +++ b/src/api/resources/teamMembers/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../errors/index"; import { WageSetting } from "../resources/wageSetting/client/Client"; @@ -18,6 +18,8 @@ export declare namespace TeamMembers { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -31,14 +33,17 @@ export declare namespace TeamMembers { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class TeamMembers { + protected readonly _options: TeamMembers.Options; protected _wageSetting: WageSetting | undefined; - constructor(protected readonly _options: TeamMembers.Options = {}) {} + constructor(_options: TeamMembers.Options = {}) { + this._options = _options; + } public get wageSetting(): WageSetting { return (this._wageSetting ??= new WageSetting(this._options)); @@ -73,7 +78,7 @@ export class TeamMembers { * jobAssignments: [{ * payType: "SALARY", * annualRate: { - * amount: 3000000, + * amount: BigInt("3000000"), * currency: "USD" * }, * weeklyHours: 40, @@ -81,7 +86,7 @@ export class TeamMembers { * }, { * payType: "HOURLY", * hourlyRate: { - * amount: 2000, + * amount: BigInt("2000"), * currency: "USD" * }, * jobId: "VDNpRv8da51NU8qZFC5zDWpF" @@ -91,29 +96,33 @@ export class TeamMembers { * } * }) */ - public async create( + public create( + request: Square.CreateTeamMemberRequest, + requestOptions?: TeamMembers.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( request: Square.CreateTeamMemberRequest, requestOptions?: TeamMembers.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/team-members", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CreateTeamMemberRequest.jsonOrThrow(request, { @@ -125,19 +134,23 @@ export class TeamMembers { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateTeamMemberResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateTeamMemberResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -146,12 +159,14 @@ export class TeamMembers { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/team-members."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -198,29 +213,33 @@ export class TeamMembers { * } * }) */ - public async batchCreate( + public batchCreate( + request: Square.BatchCreateTeamMembersRequest, + requestOptions?: TeamMembers.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchCreate(request, requestOptions)); + } + + private async __batchCreate( request: Square.BatchCreateTeamMembersRequest, requestOptions?: TeamMembers.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/team-members/bulk-create", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BatchCreateTeamMembersRequest.jsonOrThrow(request, { @@ -232,19 +251,23 @@ export class TeamMembers { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BatchCreateTeamMembersResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BatchCreateTeamMembersResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -253,12 +276,14 @@ export class TeamMembers { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/team-members/bulk-create."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -308,29 +333,33 @@ export class TeamMembers { * } * }) */ - public async batchUpdate( + public batchUpdate( + request: Square.BatchUpdateTeamMembersRequest, + requestOptions?: TeamMembers.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchUpdate(request, requestOptions)); + } + + private async __batchUpdate( request: Square.BatchUpdateTeamMembersRequest, requestOptions?: TeamMembers.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/team-members/bulk-update", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BatchUpdateTeamMembersRequest.jsonOrThrow(request, { @@ -342,19 +371,23 @@ export class TeamMembers { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BatchUpdateTeamMembersResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BatchUpdateTeamMembersResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -363,12 +396,14 @@ export class TeamMembers { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/team-members/bulk-update."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -392,29 +427,33 @@ export class TeamMembers { * limit: 10 * }) */ - public async search( + public search( request: Square.SearchTeamMembersRequest = {}, requestOptions?: TeamMembers.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__search(request, requestOptions)); + } + + private async __search( + request: Square.SearchTeamMembersRequest = {}, + requestOptions?: TeamMembers.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/team-members/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.SearchTeamMembersRequest.jsonOrThrow(request, { @@ -426,19 +465,23 @@ export class TeamMembers { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchTeamMembersResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchTeamMembersResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -447,12 +490,14 @@ export class TeamMembers { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/team-members/search."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -469,50 +514,56 @@ export class TeamMembers { * teamMemberId: "team_member_id" * }) */ - public async get( + public get( request: Square.GetTeamMembersRequest, requestOptions?: TeamMembers.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.GetTeamMembersRequest, + requestOptions?: TeamMembers.RequestOptions, + ): Promise> { const { teamMemberId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/team-members/${encodeURIComponent(teamMemberId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetTeamMemberResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetTeamMemberResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -521,6 +572,7 @@ export class TeamMembers { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -529,6 +581,7 @@ export class TeamMembers { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -559,7 +612,7 @@ export class TeamMembers { * jobAssignments: [{ * payType: "SALARY", * annualRate: { - * amount: 3000000, + * amount: BigInt("3000000"), * currency: "USD" * }, * weeklyHours: 40, @@ -567,7 +620,7 @@ export class TeamMembers { * }, { * payType: "HOURLY", * hourlyRate: { - * amount: 1200, + * amount: BigInt("1200"), * currency: "USD" * }, * jobId: "VDNpRv8da51NU8qZFC5zDWpF" @@ -578,30 +631,34 @@ export class TeamMembers { * } * }) */ - public async update( + public update( request: Square.UpdateTeamMembersRequest, requestOptions?: TeamMembers.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( + request: Square.UpdateTeamMembersRequest, + requestOptions?: TeamMembers.RequestOptions, + ): Promise> { const { teamMemberId, body: _body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/team-members/${encodeURIComponent(teamMemberId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.UpdateTeamMemberRequest.jsonOrThrow(_body, { @@ -613,19 +670,23 @@ export class TeamMembers { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateTeamMemberResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateTeamMemberResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -634,6 +695,7 @@ export class TeamMembers { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -642,6 +704,7 @@ export class TeamMembers { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/teamMembers/client/index.ts b/src/api/resources/teamMembers/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/teamMembers/client/index.ts +++ b/src/api/resources/teamMembers/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/teamMembers/client/requests/UpdateTeamMembersRequest.ts b/src/api/resources/teamMembers/client/requests/UpdateTeamMembersRequest.ts index 65c4da3d9..7c8339675 100644 --- a/src/api/resources/teamMembers/client/requests/UpdateTeamMembersRequest.ts +++ b/src/api/resources/teamMembers/client/requests/UpdateTeamMembersRequest.ts @@ -24,7 +24,7 @@ import * as Square from "../../../../index"; * jobAssignments: [{ * payType: "SALARY", * annualRate: { - * amount: 3000000, + * amount: BigInt("3000000"), * currency: "USD" * }, * weeklyHours: 40, @@ -32,7 +32,7 @@ import * as Square from "../../../../index"; * }, { * payType: "HOURLY", * hourlyRate: { - * amount: 1200, + * amount: BigInt("1200"), * currency: "USD" * }, * jobId: "VDNpRv8da51NU8qZFC5zDWpF" diff --git a/src/api/resources/teamMembers/resources/wageSetting/client/Client.ts b/src/api/resources/teamMembers/resources/wageSetting/client/Client.ts index bcfc8f5cb..8ccbbd410 100644 --- a/src/api/resources/teamMembers/resources/wageSetting/client/Client.ts +++ b/src/api/resources/teamMembers/resources/wageSetting/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; import * as errors from "../../../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace WageSetting { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace WageSetting { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class WageSetting { - constructor(protected readonly _options: WageSetting.Options = {}) {} + protected readonly _options: WageSetting.Options; + + constructor(_options: WageSetting.Options = {}) { + this._options = _options; + } /** * Retrieves a `WageSetting` object for a team member specified @@ -53,50 +59,56 @@ export class WageSetting { * teamMemberId: "team_member_id" * }) */ - public async get( + public get( + request: Square.teamMembers.GetWageSettingRequest, + requestOptions?: WageSetting.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.teamMembers.GetWageSettingRequest, requestOptions?: WageSetting.RequestOptions, - ): Promise { + ): Promise> { const { teamMemberId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/team-members/${encodeURIComponent(teamMemberId)}/wage-setting`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetWageSettingResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetWageSettingResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -105,6 +117,7 @@ export class WageSetting { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -113,6 +126,7 @@ export class WageSetting { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -138,7 +152,7 @@ export class WageSetting { * jobTitle: "Manager", * payType: "SALARY", * annualRate: { - * amount: 3000000, + * amount: BigInt("3000000"), * currency: "USD" * }, * weeklyHours: 40 @@ -146,7 +160,7 @@ export class WageSetting { * jobTitle: "Cashier", * payType: "HOURLY", * hourlyRate: { - * amount: 2000, + * amount: BigInt("2000"), * currency: "USD" * } * }], @@ -154,30 +168,34 @@ export class WageSetting { * } * }) */ - public async update( + public update( + request: Square.teamMembers.UpdateWageSettingRequest, + requestOptions?: WageSetting.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( request: Square.teamMembers.UpdateWageSettingRequest, requestOptions?: WageSetting.RequestOptions, - ): Promise { + ): Promise> { const { teamMemberId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/team-members/${encodeURIComponent(teamMemberId)}/wage-setting`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.teamMembers.UpdateWageSettingRequest.jsonOrThrow(_body, { @@ -189,19 +207,23 @@ export class WageSetting { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateWageSettingResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateWageSettingResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -210,6 +232,7 @@ export class WageSetting { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -218,6 +241,7 @@ export class WageSetting { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/teamMembers/resources/wageSetting/client/index.ts b/src/api/resources/teamMembers/resources/wageSetting/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/teamMembers/resources/wageSetting/client/index.ts +++ b/src/api/resources/teamMembers/resources/wageSetting/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/teamMembers/resources/wageSetting/client/requests/UpdateWageSettingRequest.ts b/src/api/resources/teamMembers/resources/wageSetting/client/requests/UpdateWageSettingRequest.ts index 2714623e6..b352121a3 100644 --- a/src/api/resources/teamMembers/resources/wageSetting/client/requests/UpdateWageSettingRequest.ts +++ b/src/api/resources/teamMembers/resources/wageSetting/client/requests/UpdateWageSettingRequest.ts @@ -13,7 +13,7 @@ import * as Square from "../../../../../../index"; * jobTitle: "Manager", * payType: "SALARY", * annualRate: { - * amount: 3000000, + * amount: BigInt("3000000"), * currency: "USD" * }, * weeklyHours: 40 @@ -21,7 +21,7 @@ import * as Square from "../../../../../../index"; * jobTitle: "Cashier", * payType: "HOURLY", * hourlyRate: { - * amount: 2000, + * amount: BigInt("2000"), * currency: "USD" * } * }], diff --git a/src/api/resources/terminal/client/Client.ts b/src/api/resources/terminal/client/Client.ts index cee4c37ad..83250f89e 100644 --- a/src/api/resources/terminal/client/Client.ts +++ b/src/api/resources/terminal/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; import * as errors from "../../../../errors/index"; import { Actions } from "../resources/actions/client/Client"; @@ -20,6 +20,8 @@ export declare namespace Terminal { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -33,16 +35,19 @@ export declare namespace Terminal { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Terminal { + protected readonly _options: Terminal.Options; protected _actions: Actions | undefined; protected _checkouts: Checkouts | undefined; protected _refunds: Refunds | undefined; - constructor(protected readonly _options: Terminal.Options = {}) {} + constructor(_options: Terminal.Options = {}) { + this._options = _options; + } public get actions(): Actions { return (this._actions ??= new Actions(this._options)); @@ -69,50 +74,56 @@ export class Terminal { * actionId: "action_id" * }) */ - public async dismissTerminalAction( + public dismissTerminalAction( + request: Square.DismissTerminalActionRequest, + requestOptions?: Terminal.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__dismissTerminalAction(request, requestOptions)); + } + + private async __dismissTerminalAction( request: Square.DismissTerminalActionRequest, requestOptions?: Terminal.RequestOptions, - ): Promise { + ): Promise> { const { actionId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/terminals/actions/${encodeURIComponent(actionId)}/dismiss`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DismissTerminalActionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DismissTerminalActionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -121,6 +132,7 @@ export class Terminal { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -129,6 +141,7 @@ export class Terminal { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -144,50 +157,56 @@ export class Terminal { * checkoutId: "checkout_id" * }) */ - public async dismissTerminalCheckout( + public dismissTerminalCheckout( request: Square.DismissTerminalCheckoutRequest, requestOptions?: Terminal.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__dismissTerminalCheckout(request, requestOptions)); + } + + private async __dismissTerminalCheckout( + request: Square.DismissTerminalCheckoutRequest, + requestOptions?: Terminal.RequestOptions, + ): Promise> { const { checkoutId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/terminals/checkouts/${encodeURIComponent(checkoutId)}/dismiss`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DismissTerminalCheckoutResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DismissTerminalCheckoutResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -196,6 +215,7 @@ export class Terminal { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -204,6 +224,7 @@ export class Terminal { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -219,50 +240,56 @@ export class Terminal { * terminalRefundId: "terminal_refund_id" * }) */ - public async dismissTerminalRefund( + public dismissTerminalRefund( request: Square.DismissTerminalRefundRequest, requestOptions?: Terminal.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__dismissTerminalRefund(request, requestOptions)); + } + + private async __dismissTerminalRefund( + request: Square.DismissTerminalRefundRequest, + requestOptions?: Terminal.RequestOptions, + ): Promise> { const { terminalRefundId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/terminals/refunds/${encodeURIComponent(terminalRefundId)}/dismiss`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DismissTerminalRefundResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DismissTerminalRefundResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -271,6 +298,7 @@ export class Terminal { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -279,6 +307,7 @@ export class Terminal { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/terminal/client/index.ts b/src/api/resources/terminal/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/terminal/client/index.ts +++ b/src/api/resources/terminal/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/terminal/resources/actions/client/Client.ts b/src/api/resources/terminal/resources/actions/client/Client.ts index ae4217c5e..f0b223613 100644 --- a/src/api/resources/terminal/resources/actions/client/Client.ts +++ b/src/api/resources/terminal/resources/actions/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../../../errors/index"; export declare namespace Actions { @@ -17,6 +17,8 @@ export declare namespace Actions { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Actions { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Actions { - constructor(protected readonly _options: Actions.Options = {}) {} + protected readonly _options: Actions.Options; + + constructor(_options: Actions.Options = {}) { + this._options = _options; + } /** * Creates a Terminal action request and sends it to the specified device. @@ -57,29 +63,33 @@ export class Actions { * } * }) */ - public async create( + public create( + request: Square.terminal.CreateTerminalActionRequest, + requestOptions?: Actions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( request: Square.terminal.CreateTerminalActionRequest, requestOptions?: Actions.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/terminals/actions", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.terminal.CreateTerminalActionRequest.jsonOrThrow(request, { @@ -91,19 +101,23 @@ export class Actions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateTerminalActionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateTerminalActionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -112,12 +126,14 @@ export class Actions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/terminals/actions."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -143,29 +159,33 @@ export class Actions { * limit: 2 * }) */ - public async search( + public search( request: Square.terminal.SearchTerminalActionsRequest = {}, requestOptions?: Actions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__search(request, requestOptions)); + } + + private async __search( + request: Square.terminal.SearchTerminalActionsRequest = {}, + requestOptions?: Actions.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/terminals/actions/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.terminal.SearchTerminalActionsRequest.jsonOrThrow(request, { @@ -177,19 +197,23 @@ export class Actions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchTerminalActionsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchTerminalActionsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -198,12 +222,14 @@ export class Actions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/terminals/actions/search."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -219,50 +245,56 @@ export class Actions { * actionId: "action_id" * }) */ - public async get( + public get( + request: Square.terminal.GetActionsRequest, + requestOptions?: Actions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.terminal.GetActionsRequest, requestOptions?: Actions.RequestOptions, - ): Promise { + ): Promise> { const { actionId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/terminals/actions/${encodeURIComponent(actionId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetTerminalActionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetTerminalActionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -271,6 +303,7 @@ export class Actions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -279,6 +312,7 @@ export class Actions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -294,50 +328,56 @@ export class Actions { * actionId: "action_id" * }) */ - public async cancel( + public cancel( request: Square.terminal.CancelActionsRequest, requestOptions?: Actions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__cancel(request, requestOptions)); + } + + private async __cancel( + request: Square.terminal.CancelActionsRequest, + requestOptions?: Actions.RequestOptions, + ): Promise> { const { actionId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/terminals/actions/${encodeURIComponent(actionId)}/cancel`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CancelTerminalActionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CancelTerminalActionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -346,6 +386,7 @@ export class Actions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -354,6 +395,7 @@ export class Actions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/terminal/resources/actions/client/index.ts b/src/api/resources/terminal/resources/actions/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/terminal/resources/actions/client/index.ts +++ b/src/api/resources/terminal/resources/actions/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/terminal/resources/checkouts/client/Client.ts b/src/api/resources/terminal/resources/checkouts/client/Client.ts index 9885ba5ea..26a594743 100644 --- a/src/api/resources/terminal/resources/checkouts/client/Client.ts +++ b/src/api/resources/terminal/resources/checkouts/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../../../errors/index"; export declare namespace Checkouts { @@ -17,6 +17,8 @@ export declare namespace Checkouts { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Checkouts { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Checkouts { - constructor(protected readonly _options: Checkouts.Options = {}) {} + protected readonly _options: Checkouts.Options; + + constructor(_options: Checkouts.Options = {}) { + this._options = _options; + } /** * Creates a Terminal checkout request and sends it to the specified device to take a payment @@ -49,7 +55,7 @@ export class Checkouts { * idempotencyKey: "28a0c3bc-7839-11ea-bc55-0242ac130003", * checkout: { * amountMoney: { - * amount: 2610, + * amount: BigInt("2610"), * currency: "USD" * }, * referenceId: "id11572", @@ -60,29 +66,33 @@ export class Checkouts { * } * }) */ - public async create( + public create( + request: Square.terminal.CreateTerminalCheckoutRequest, + requestOptions?: Checkouts.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( request: Square.terminal.CreateTerminalCheckoutRequest, requestOptions?: Checkouts.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/terminals/checkouts", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.terminal.CreateTerminalCheckoutRequest.jsonOrThrow(request, { @@ -94,19 +104,23 @@ export class Checkouts { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateTerminalCheckoutResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateTerminalCheckoutResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -115,12 +129,14 @@ export class Checkouts { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/terminals/checkouts."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -141,29 +157,33 @@ export class Checkouts { * limit: 2 * }) */ - public async search( + public search( request: Square.terminal.SearchTerminalCheckoutsRequest = {}, requestOptions?: Checkouts.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__search(request, requestOptions)); + } + + private async __search( + request: Square.terminal.SearchTerminalCheckoutsRequest = {}, + requestOptions?: Checkouts.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/terminals/checkouts/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.terminal.SearchTerminalCheckoutsRequest.jsonOrThrow(request, { @@ -175,19 +195,23 @@ export class Checkouts { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchTerminalCheckoutsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchTerminalCheckoutsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -196,6 +220,7 @@ export class Checkouts { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -204,6 +229,7 @@ export class Checkouts { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -219,50 +245,56 @@ export class Checkouts { * checkoutId: "checkout_id" * }) */ - public async get( + public get( + request: Square.terminal.GetCheckoutsRequest, + requestOptions?: Checkouts.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.terminal.GetCheckoutsRequest, requestOptions?: Checkouts.RequestOptions, - ): Promise { + ): Promise> { const { checkoutId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/terminals/checkouts/${encodeURIComponent(checkoutId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetTerminalCheckoutResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetTerminalCheckoutResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -271,6 +303,7 @@ export class Checkouts { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -279,6 +312,7 @@ export class Checkouts { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -294,50 +328,56 @@ export class Checkouts { * checkoutId: "checkout_id" * }) */ - public async cancel( + public cancel( request: Square.terminal.CancelCheckoutsRequest, requestOptions?: Checkouts.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__cancel(request, requestOptions)); + } + + private async __cancel( + request: Square.terminal.CancelCheckoutsRequest, + requestOptions?: Checkouts.RequestOptions, + ): Promise> { const { checkoutId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/terminals/checkouts/${encodeURIComponent(checkoutId)}/cancel`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CancelTerminalCheckoutResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CancelTerminalCheckoutResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -346,6 +386,7 @@ export class Checkouts { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -354,6 +395,7 @@ export class Checkouts { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/terminal/resources/checkouts/client/index.ts b/src/api/resources/terminal/resources/checkouts/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/terminal/resources/checkouts/client/index.ts +++ b/src/api/resources/terminal/resources/checkouts/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/terminal/resources/checkouts/client/requests/CreateTerminalCheckoutRequest.ts b/src/api/resources/terminal/resources/checkouts/client/requests/CreateTerminalCheckoutRequest.ts index 7cf248165..a07279878 100644 --- a/src/api/resources/terminal/resources/checkouts/client/requests/CreateTerminalCheckoutRequest.ts +++ b/src/api/resources/terminal/resources/checkouts/client/requests/CreateTerminalCheckoutRequest.ts @@ -10,7 +10,7 @@ import * as Square from "../../../../../../index"; * idempotencyKey: "28a0c3bc-7839-11ea-bc55-0242ac130003", * checkout: { * amountMoney: { - * amount: 2610, + * amount: BigInt("2610"), * currency: "USD" * }, * referenceId: "id11572", diff --git a/src/api/resources/terminal/resources/refunds/client/Client.ts b/src/api/resources/terminal/resources/refunds/client/Client.ts index 3e989c6b0..ee04835f6 100644 --- a/src/api/resources/terminal/resources/refunds/client/Client.ts +++ b/src/api/resources/terminal/resources/refunds/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../../../errors/index"; export declare namespace Refunds { @@ -17,6 +17,8 @@ export declare namespace Refunds { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Refunds { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Refunds { - constructor(protected readonly _options: Refunds.Options = {}) {} + protected readonly _options: Refunds.Options; + + constructor(_options: Refunds.Options = {}) { + this._options = _options; + } /** * Creates a request to refund an Interac payment completed on a Square Terminal. Refunds for Interac payments on a Square Terminal are supported only for Interac debit cards in Canada. Other refunds for Terminal payments should use the Refunds API. For more information, see [Refunds API](api:Refunds). @@ -49,7 +55,7 @@ export class Refunds { * refund: { * paymentId: "5O5OvgkcNUhl7JBuINflcjKqUzXZY", * amountMoney: { - * amount: 111, + * amount: BigInt("111"), * currency: "CAD" * }, * reason: "Returning items", @@ -57,29 +63,33 @@ export class Refunds { * } * }) */ - public async create( + public create( + request: Square.terminal.CreateTerminalRefundRequest, + requestOptions?: Refunds.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( request: Square.terminal.CreateTerminalRefundRequest, requestOptions?: Refunds.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/terminals/refunds", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.terminal.CreateTerminalRefundRequest.jsonOrThrow(request, { @@ -91,19 +101,23 @@ export class Refunds { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateTerminalRefundResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateTerminalRefundResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -112,12 +126,14 @@ export class Refunds { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/terminals/refunds."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -138,29 +154,33 @@ export class Refunds { * limit: 1 * }) */ - public async search( + public search( request: Square.terminal.SearchTerminalRefundsRequest = {}, requestOptions?: Refunds.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__search(request, requestOptions)); + } + + private async __search( + request: Square.terminal.SearchTerminalRefundsRequest = {}, + requestOptions?: Refunds.RequestOptions, + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/terminals/refunds/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.terminal.SearchTerminalRefundsRequest.jsonOrThrow(request, { @@ -172,19 +192,23 @@ export class Refunds { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchTerminalRefundsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchTerminalRefundsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -193,12 +217,14 @@ export class Refunds { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/terminals/refunds/search."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -214,50 +240,56 @@ export class Refunds { * terminalRefundId: "terminal_refund_id" * }) */ - public async get( + public get( + request: Square.terminal.GetRefundsRequest, + requestOptions?: Refunds.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( request: Square.terminal.GetRefundsRequest, requestOptions?: Refunds.RequestOptions, - ): Promise { + ): Promise> { const { terminalRefundId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/terminals/refunds/${encodeURIComponent(terminalRefundId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetTerminalRefundResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetTerminalRefundResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -266,6 +298,7 @@ export class Refunds { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -274,6 +307,7 @@ export class Refunds { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -289,50 +323,56 @@ export class Refunds { * terminalRefundId: "terminal_refund_id" * }) */ - public async cancel( + public cancel( request: Square.terminal.CancelRefundsRequest, requestOptions?: Refunds.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__cancel(request, requestOptions)); + } + + private async __cancel( + request: Square.terminal.CancelRefundsRequest, + requestOptions?: Refunds.RequestOptions, + ): Promise> { const { terminalRefundId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/terminals/refunds/${encodeURIComponent(terminalRefundId)}/cancel`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CancelTerminalRefundResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CancelTerminalRefundResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -341,6 +381,7 @@ export class Refunds { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -349,6 +390,7 @@ export class Refunds { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/terminal/resources/refunds/client/index.ts b/src/api/resources/terminal/resources/refunds/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/terminal/resources/refunds/client/index.ts +++ b/src/api/resources/terminal/resources/refunds/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/terminal/resources/refunds/client/requests/CreateTerminalRefundRequest.ts b/src/api/resources/terminal/resources/refunds/client/requests/CreateTerminalRefundRequest.ts index 624a728ea..c6389887c 100644 --- a/src/api/resources/terminal/resources/refunds/client/requests/CreateTerminalRefundRequest.ts +++ b/src/api/resources/terminal/resources/refunds/client/requests/CreateTerminalRefundRequest.ts @@ -11,7 +11,7 @@ import * as Square from "../../../../../../index"; * refund: { * paymentId: "5O5OvgkcNUhl7JBuINflcjKqUzXZY", * amountMoney: { - * amount: 111, + * amount: BigInt("111"), * currency: "CAD" * }, * reason: "Returning items", diff --git a/src/api/resources/v1Transactions/client/Client.ts b/src/api/resources/v1Transactions/client/Client.ts index f90a5c547..e3491684d 100644 --- a/src/api/resources/v1Transactions/client/Client.ts +++ b/src/api/resources/v1Transactions/client/Client.ts @@ -6,7 +6,7 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as errors from "../../../../errors/index"; export declare namespace V1Transactions { @@ -17,6 +17,8 @@ export declare namespace V1Transactions { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace V1Transactions { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class V1Transactions { - constructor(protected readonly _options: V1Transactions.Options = {}) {} + protected readonly _options: V1Transactions.Options; + + constructor(_options: V1Transactions.Options = {}) { + this._options = _options; + } /** * Provides summary information for a merchant's online store orders. @@ -48,10 +54,17 @@ export class V1Transactions { * locationId: "location_id" * }) */ - public async v1ListOrders( + public v1ListOrders( + request: Square.V1ListOrdersRequest, + requestOptions?: V1Transactions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__v1ListOrders(request, requestOptions)); + } + + private async __v1ListOrders( request: Square.V1ListOrdersRequest, requestOptions?: V1Transactions.RequestOptions, - ): Promise { + ): Promise> { const { locationId, order, limit, batchToken } = request; const _queryParams: Record = {}; if (order !== undefined) { @@ -70,45 +83,44 @@ export class V1Transactions { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v1/${encodeURIComponent(locationId)}/orders`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.v1Transactions.v1ListOrders.Response.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.v1Transactions.v1ListOrders.Response.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -117,12 +129,14 @@ export class V1Transactions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v1/{location_id}/orders."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -139,50 +153,56 @@ export class V1Transactions { * orderId: "order_id" * }) */ - public async v1RetrieveOrder( + public v1RetrieveOrder( + request: Square.V1RetrieveOrderRequest, + requestOptions?: V1Transactions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__v1RetrieveOrder(request, requestOptions)); + } + + private async __v1RetrieveOrder( request: Square.V1RetrieveOrderRequest, requestOptions?: V1Transactions.RequestOptions, - ): Promise { + ): Promise> { const { locationId, orderId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v1/${encodeURIComponent(locationId)}/orders/${encodeURIComponent(orderId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.V1Order.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.V1Order.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -191,6 +211,7 @@ export class V1Transactions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -199,6 +220,7 @@ export class V1Transactions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -216,30 +238,34 @@ export class V1Transactions { * action: "COMPLETE" * }) */ - public async v1UpdateOrder( + public v1UpdateOrder( request: Square.V1UpdateOrderRequest, requestOptions?: V1Transactions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__v1UpdateOrder(request, requestOptions)); + } + + private async __v1UpdateOrder( + request: Square.V1UpdateOrderRequest, + requestOptions?: V1Transactions.RequestOptions, + ): Promise> { const { locationId, orderId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v1/${encodeURIComponent(locationId)}/orders/${encodeURIComponent(orderId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.V1UpdateOrderRequest.jsonOrThrow(_body, { @@ -251,19 +277,23 @@ export class V1Transactions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.V1Order.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.V1Order.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -272,6 +302,7 @@ export class V1Transactions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -280,6 +311,7 @@ export class V1Transactions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/v1Transactions/client/index.ts b/src/api/resources/v1Transactions/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/v1Transactions/client/index.ts +++ b/src/api/resources/v1Transactions/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/vendors/client/Client.ts b/src/api/resources/vendors/client/Client.ts index a2507a1bb..1d3e4516c 100644 --- a/src/api/resources/vendors/client/Client.ts +++ b/src/api/resources/vendors/client/Client.ts @@ -5,8 +5,8 @@ import * as environments from "../../../../environments"; import * as core from "../../../../core"; import * as Square from "../../../index"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../core/headers"; import * as serializers from "../../../../serialization/index"; -import urlJoin from "url-join"; import * as errors from "../../../../errors/index"; export declare namespace Vendors { @@ -17,6 +17,8 @@ export declare namespace Vendors { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Vendors { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Vendors { - constructor(protected readonly _options: Vendors.Options = {}) {} + protected readonly _options: Vendors.Options; + + constructor(_options: Vendors.Options = {}) { + this._options = _options; + } /** * Creates one or more [Vendor](entity:Vendor) objects to represent suppliers to a seller. @@ -68,29 +74,33 @@ export class Vendors { * } * }) */ - public async batchCreate( + public batchCreate( + request: Square.BatchCreateVendorsRequest, + requestOptions?: Vendors.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchCreate(request, requestOptions)); + } + + private async __batchCreate( request: Square.BatchCreateVendorsRequest, requestOptions?: Vendors.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/vendors/bulk-create", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BatchCreateVendorsRequest.jsonOrThrow(request, { @@ -102,19 +112,23 @@ export class Vendors { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BatchCreateVendorsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BatchCreateVendorsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -123,12 +137,14 @@ export class Vendors { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/vendors/bulk-create."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -144,29 +160,33 @@ export class Vendors { * vendorIds: ["INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4"] * }) */ - public async batchGet( + public batchGet( + request: Square.BatchGetVendorsRequest = {}, + requestOptions?: Vendors.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchGet(request, requestOptions)); + } + + private async __batchGet( request: Square.BatchGetVendorsRequest = {}, requestOptions?: Vendors.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/vendors/bulk-retrieve", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BatchGetVendorsRequest.jsonOrThrow(request, { @@ -178,19 +198,23 @@ export class Vendors { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BatchGetVendorsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BatchGetVendorsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -199,12 +223,14 @@ export class Vendors { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/vendors/bulk-retrieve."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -227,29 +253,33 @@ export class Vendors { * } * }) */ - public async batchUpdate( + public batchUpdate( + request: Square.BatchUpdateVendorsRequest, + requestOptions?: Vendors.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__batchUpdate(request, requestOptions)); + } + + private async __batchUpdate( request: Square.BatchUpdateVendorsRequest, requestOptions?: Vendors.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/vendors/bulk-update", ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.BatchUpdateVendorsRequest.jsonOrThrow(request, { @@ -261,19 +291,23 @@ export class Vendors { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.BatchUpdateVendorsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.BatchUpdateVendorsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -282,12 +316,14 @@ export class Vendors { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling PUT /v2/vendors/bulk-update."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -322,29 +358,33 @@ export class Vendors { * } * }) */ - public async create( + public create( + request: Square.CreateVendorRequest, + requestOptions?: Vendors.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( request: Square.CreateVendorRequest, requestOptions?: Vendors.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/vendors/create", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.CreateVendorRequest.jsonOrThrow(request, { @@ -356,19 +396,23 @@ export class Vendors { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateVendorResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateVendorResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -377,12 +421,14 @@ export class Vendors { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/vendors/create."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -396,29 +442,33 @@ export class Vendors { * @example * await client.vendors.search() */ - public async search( + public search( + request: Square.SearchVendorsRequest = {}, + requestOptions?: Vendors.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__search(request, requestOptions)); + } + + private async __search( request: Square.SearchVendorsRequest = {}, requestOptions?: Vendors.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/vendors/search", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.SearchVendorsRequest.jsonOrThrow(request, { @@ -430,19 +480,23 @@ export class Vendors { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.SearchVendorsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.SearchVendorsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -451,12 +505,14 @@ export class Vendors { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/vendors/search."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -472,50 +528,56 @@ export class Vendors { * vendorId: "vendor_id" * }) */ - public async get( + public get( request: Square.GetVendorsRequest, requestOptions?: Vendors.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.GetVendorsRequest, + requestOptions?: Vendors.RequestOptions, + ): Promise> { const { vendorId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/vendors/${encodeURIComponent(vendorId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetVendorResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetVendorResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -524,12 +586,14 @@ export class Vendors { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/vendors/{vendor_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -554,30 +618,34 @@ export class Vendors { * } * }) */ - public async update( + public update( request: Square.UpdateVendorsRequest, requestOptions?: Vendors.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( + request: Square.UpdateVendorsRequest, + requestOptions?: Vendors.RequestOptions, + ): Promise> { const { vendorId, body: _body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/vendors/${encodeURIComponent(vendorId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.UpdateVendorRequest.jsonOrThrow(_body, { @@ -589,19 +657,23 @@ export class Vendors { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateVendorResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateVendorResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -610,12 +682,14 @@ export class Vendors { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling PUT /v2/vendors/{vendor_id}."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/vendors/client/index.ts b/src/api/resources/vendors/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/vendors/client/index.ts +++ b/src/api/resources/vendors/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/webhooks/client/Client.ts b/src/api/resources/webhooks/client/Client.ts index cb72fb95b..d9fb560cd 100644 --- a/src/api/resources/webhooks/client/Client.ts +++ b/src/api/resources/webhooks/client/Client.ts @@ -15,28 +15,20 @@ export declare namespace Webhooks { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } - - export interface RequestOptions { - /** The maximum time to wait for a response in seconds. */ - timeoutInSeconds?: number; - /** The number of times to retry the request. Defaults to 2. */ - maxRetries?: number; - /** A hook to abort the request. */ - abortSignal?: AbortSignal; - /** Override the Square-Version header */ - version?: "2025-07-16"; - /** Additional headers to include in the request. */ - headers?: Record; - } } export class Webhooks { + protected readonly _options: Webhooks.Options; protected _eventTypes: EventTypes | undefined; protected _subscriptions: Subscriptions | undefined; - constructor(protected readonly _options: Webhooks.Options = {}) {} + constructor(_options: Webhooks.Options = {}) { + this._options = _options; + } public get eventTypes(): EventTypes { return (this._eventTypes ??= new EventTypes(this._options)); diff --git a/src/api/resources/webhooks/resources/eventTypes/client/Client.ts b/src/api/resources/webhooks/resources/eventTypes/client/Client.ts index 138be8fd5..83d50ecb0 100644 --- a/src/api/resources/webhooks/resources/eventTypes/client/Client.ts +++ b/src/api/resources/webhooks/resources/eventTypes/client/Client.ts @@ -5,7 +5,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as serializers from "../../../../../../serialization/index"; import * as errors from "../../../../../../errors/index"; @@ -17,6 +17,8 @@ export declare namespace EventTypes { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace EventTypes { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class EventTypes { - constructor(protected readonly _options: EventTypes.Options = {}) {} + protected readonly _options: EventTypes.Options; + + constructor(_options: EventTypes.Options = {}) { + this._options = _options; + } /** * Lists all webhook event types that can be subscribed to. @@ -46,10 +52,17 @@ export class EventTypes { * @example * await client.webhooks.eventTypes.list() */ - public async list( + public list( + request: Square.webhooks.ListEventTypesRequest = {}, + requestOptions?: EventTypes.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__list(request, requestOptions)); + } + + private async __list( request: Square.webhooks.ListEventTypesRequest = {}, requestOptions?: EventTypes.RequestOptions, - ): Promise { + ): Promise> { const { apiVersion } = request; const _queryParams: Record = {}; if (apiVersion !== undefined) { @@ -57,45 +70,44 @@ export class EventTypes { } const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/webhooks/event-types", ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), queryParameters: _queryParams, - requestType: "json", timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.ListWebhookEventTypesResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.ListWebhookEventTypesResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -104,12 +116,14 @@ export class EventTypes { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling GET /v2/webhooks/event-types."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/webhooks/resources/eventTypes/client/index.ts b/src/api/resources/webhooks/resources/eventTypes/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/webhooks/resources/eventTypes/client/index.ts +++ b/src/api/resources/webhooks/resources/eventTypes/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/api/resources/webhooks/resources/subscriptions/client/Client.ts b/src/api/resources/webhooks/resources/subscriptions/client/Client.ts index afb5ce3ee..f36f5ec15 100644 --- a/src/api/resources/webhooks/resources/subscriptions/client/Client.ts +++ b/src/api/resources/webhooks/resources/subscriptions/client/Client.ts @@ -6,7 +6,7 @@ import * as environments from "../../../../../../environments"; import * as core from "../../../../../../core"; import * as Square from "../../../../../index"; import * as serializers from "../../../../../../serialization/index"; -import urlJoin from "url-join"; +import { mergeHeaders, mergeOnlyDefinedHeaders } from "../../../../../../core/headers"; import * as errors from "../../../../../../errors/index"; export declare namespace Subscriptions { @@ -17,6 +17,8 @@ export declare namespace Subscriptions { token?: core.Supplier; /** Override the Square-Version header */ version?: "2025-07-16"; + /** Additional headers to include in requests. */ + headers?: Record | undefined>; fetcher?: core.FetchFunction; } @@ -30,12 +32,16 @@ export declare namespace Subscriptions { /** Override the Square-Version header */ version?: "2025-07-16"; /** Additional headers to include in the request. */ - headers?: Record; + headers?: Record | undefined>; } } export class Subscriptions { - constructor(protected readonly _options: Subscriptions.Options = {}) {} + protected readonly _options: Subscriptions.Options; + + constructor(_options: Subscriptions.Options = {}) { + this._options = _options; + } /** * Lists all webhook subscriptions owned by your application. @@ -50,86 +56,93 @@ export class Subscriptions { request: Square.webhooks.ListSubscriptionsRequest = {}, requestOptions?: Subscriptions.RequestOptions, ): Promise> { - const list = async ( - request: Square.webhooks.ListSubscriptionsRequest, - ): Promise => { - const { cursor, includeDisabled, sortOrder, limit } = request; - const _queryParams: Record = {}; - if (cursor !== undefined) { - _queryParams["cursor"] = cursor; - } - if (includeDisabled !== undefined) { - _queryParams["include_disabled"] = includeDisabled?.toString() ?? null; - } - if (sortOrder !== undefined) { - _queryParams["sort_order"] = serializers.SortOrder.jsonOrThrow(sortOrder, { - unrecognizedObjectKeys: "strip", - omitUndefined: true, - }); - } - if (limit !== undefined) { - _queryParams["limit"] = limit?.toString() ?? null; - } - const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( - (await core.Supplier.get(this._options.baseUrl)) ?? - (await core.Supplier.get(this._options.environment)) ?? - environments.SquareEnvironment.Production, - "v2/webhooks/subscriptions", - ), - method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - queryParameters: _queryParams, - requestType: "json", - timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, - maxRetries: requestOptions?.maxRetries, - abortSignal: requestOptions?.abortSignal, - }); - if (_response.ok) { - return serializers.ListWebhookSubscriptionsResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); - } - if (_response.error.reason === "status-code") { - throw new errors.SquareError({ - statusCode: _response.error.statusCode, - body: _response.error.body, + const list = core.HttpResponsePromise.interceptFunction( + async ( + request: Square.webhooks.ListSubscriptionsRequest, + ): Promise> => { + const { cursor, includeDisabled, sortOrder, limit } = request; + const _queryParams: Record = {}; + if (cursor !== undefined) { + _queryParams["cursor"] = cursor; + } + if (includeDisabled !== undefined) { + _queryParams["include_disabled"] = includeDisabled?.toString() ?? null; + } + if (sortOrder !== undefined) { + _queryParams["sort_order"] = serializers.SortOrder.jsonOrThrow(sortOrder, { + unrecognizedObjectKeys: "strip", + omitUndefined: true, + }); + } + if (limit !== undefined) { + _queryParams["limit"] = limit?.toString() ?? null; + } + const _response = await (this._options.fetcher ?? core.fetcher)({ + url: core.url.join( + (await core.Supplier.get(this._options.baseUrl)) ?? + (await core.Supplier.get(this._options.environment)) ?? + environments.SquareEnvironment.Production, + "v2/webhooks/subscriptions", + ), + method: "GET", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), + queryParameters: _queryParams, + timeoutMs: + requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, + maxRetries: requestOptions?.maxRetries, + abortSignal: requestOptions?.abortSignal, }); - } - switch (_response.error.reason) { - case "non-json": + if (_response.ok) { + return { + data: serializers.ListWebhookSubscriptionsResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; + } + if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, - body: _response.error.rawBody, - }); - case "timeout": - throw new errors.SquareTimeoutError( - "Timeout exceeded when calling GET /v2/webhooks/subscriptions.", - ); - case "unknown": - throw new errors.SquareError({ - message: _response.error.errorMessage, + body: _response.error.body, + rawResponse: _response.rawResponse, }); - } - }; + } + switch (_response.error.reason) { + case "non-json": + throw new errors.SquareError({ + statusCode: _response.error.statusCode, + body: _response.error.rawBody, + rawResponse: _response.rawResponse, + }); + case "timeout": + throw new errors.SquareTimeoutError( + "Timeout exceeded when calling GET /v2/webhooks/subscriptions.", + ); + case "unknown": + throw new errors.SquareError({ + message: _response.error.errorMessage, + rawResponse: _response.rawResponse, + }); + } + }, + ); + const dataWithRawResponse = await list(request).withRawResponse(); return new core.Pageable({ - response: await list(request), - hasNextPage: (response) => response?.cursor != null, + response: dataWithRawResponse.data, + rawResponse: dataWithRawResponse.rawResponse, + hasNextPage: (response) => + response?.cursor != null && !(typeof response?.cursor === "string" && response?.cursor === ""), getItems: (response) => response?.subscriptions ?? [], loadPage: (response) => { return list(core.setObjectProperty(request, "cursor", response?.cursor)); @@ -154,29 +167,33 @@ export class Subscriptions { * } * }) */ - public async create( + public create( + request: Square.webhooks.CreateWebhookSubscriptionRequest, + requestOptions?: Subscriptions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__create(request, requestOptions)); + } + + private async __create( request: Square.webhooks.CreateWebhookSubscriptionRequest, requestOptions?: Subscriptions.RequestOptions, - ): Promise { + ): Promise> { const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, "v2/webhooks/subscriptions", ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.webhooks.CreateWebhookSubscriptionRequest.jsonOrThrow(request, { @@ -188,19 +205,23 @@ export class Subscriptions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.CreateWebhookSubscriptionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.CreateWebhookSubscriptionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -209,12 +230,14 @@ export class Subscriptions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError("Timeout exceeded when calling POST /v2/webhooks/subscriptions."); case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -230,50 +253,56 @@ export class Subscriptions { * subscriptionId: "subscription_id" * }) */ - public async get( + public get( request: Square.webhooks.GetSubscriptionsRequest, requestOptions?: Subscriptions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__get(request, requestOptions)); + } + + private async __get( + request: Square.webhooks.GetSubscriptionsRequest, + requestOptions?: Subscriptions.RequestOptions, + ): Promise> { const { subscriptionId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/webhooks/subscriptions/${encodeURIComponent(subscriptionId)}`, ), method: "GET", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.GetWebhookSubscriptionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.GetWebhookSubscriptionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -282,6 +311,7 @@ export class Subscriptions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -290,6 +320,7 @@ export class Subscriptions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -309,30 +340,34 @@ export class Subscriptions { * } * }) */ - public async update( + public update( + request: Square.webhooks.UpdateWebhookSubscriptionRequest, + requestOptions?: Subscriptions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__update(request, requestOptions)); + } + + private async __update( request: Square.webhooks.UpdateWebhookSubscriptionRequest, requestOptions?: Subscriptions.RequestOptions, - ): Promise { + ): Promise> { const { subscriptionId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/webhooks/subscriptions/${encodeURIComponent(subscriptionId)}`, ), method: "PUT", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.webhooks.UpdateWebhookSubscriptionRequest.jsonOrThrow(_body, { @@ -344,19 +379,23 @@ export class Subscriptions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateWebhookSubscriptionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateWebhookSubscriptionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -365,6 +404,7 @@ export class Subscriptions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -373,6 +413,7 @@ export class Subscriptions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -388,50 +429,56 @@ export class Subscriptions { * subscriptionId: "subscription_id" * }) */ - public async delete( + public delete( + request: Square.webhooks.DeleteSubscriptionsRequest, + requestOptions?: Subscriptions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__delete(request, requestOptions)); + } + + private async __delete( request: Square.webhooks.DeleteSubscriptionsRequest, requestOptions?: Subscriptions.RequestOptions, - ): Promise { + ): Promise> { const { subscriptionId } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/webhooks/subscriptions/${encodeURIComponent(subscriptionId)}`, ), method: "DELETE", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.1", - "User-Agent": "square/43.0.1", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, - contentType: "application/json", - requestType: "json", + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), timeoutMs: requestOptions?.timeoutInSeconds != null ? requestOptions.timeoutInSeconds * 1000 : 60000, maxRetries: requestOptions?.maxRetries, abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.DeleteWebhookSubscriptionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.DeleteWebhookSubscriptionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -440,6 +487,7 @@ export class Subscriptions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -448,6 +496,7 @@ export class Subscriptions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -464,30 +513,34 @@ export class Subscriptions { * idempotencyKey: "ed80ae6b-0654-473b-bbab-a39aee89a60d" * }) */ - public async updateSignatureKey( + public updateSignatureKey( request: Square.webhooks.UpdateWebhookSubscriptionSignatureKeyRequest, requestOptions?: Subscriptions.RequestOptions, - ): Promise { + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__updateSignatureKey(request, requestOptions)); + } + + private async __updateSignatureKey( + request: Square.webhooks.UpdateWebhookSubscriptionSignatureKeyRequest, + requestOptions?: Subscriptions.RequestOptions, + ): Promise> { const { subscriptionId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/webhooks/subscriptions/${encodeURIComponent(subscriptionId)}/signature-key`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.webhooks.UpdateWebhookSubscriptionSignatureKeyRequest.jsonOrThrow(_body, { @@ -499,19 +552,23 @@ export class Subscriptions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.UpdateWebhookSubscriptionSignatureKeyResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.UpdateWebhookSubscriptionSignatureKeyResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -520,6 +577,7 @@ export class Subscriptions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -528,6 +586,7 @@ export class Subscriptions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } @@ -544,30 +603,34 @@ export class Subscriptions { * eventType: "payment.created" * }) */ - public async test( + public test( + request: Square.webhooks.TestWebhookSubscriptionRequest, + requestOptions?: Subscriptions.RequestOptions, + ): core.HttpResponsePromise { + return core.HttpResponsePromise.fromPromise(this.__test(request, requestOptions)); + } + + private async __test( request: Square.webhooks.TestWebhookSubscriptionRequest, requestOptions?: Subscriptions.RequestOptions, - ): Promise { + ): Promise> { const { subscriptionId, ..._body } = request; const _response = await (this._options.fetcher ?? core.fetcher)({ - url: urlJoin( + url: core.url.join( (await core.Supplier.get(this._options.baseUrl)) ?? (await core.Supplier.get(this._options.environment)) ?? environments.SquareEnvironment.Production, `v2/webhooks/subscriptions/${encodeURIComponent(subscriptionId)}/test`, ), method: "POST", - headers: { - Authorization: await this._getAuthorizationHeader(), - "Square-Version": requestOptions?.version ?? this._options?.version ?? "2025-07-16", - "X-Fern-Language": "JavaScript", - "X-Fern-SDK-Name": "square", - "X-Fern-SDK-Version": "43.0.0", - "User-Agent": "square/43.0.0", - "X-Fern-Runtime": core.RUNTIME.type, - "X-Fern-Runtime-Version": core.RUNTIME.version, - ...requestOptions?.headers, - }, + headers: mergeHeaders( + this._options?.headers, + mergeOnlyDefinedHeaders({ + Authorization: await this._getAuthorizationHeader(), + "Square-Version": requestOptions?.version ?? "2025-07-16", + }), + requestOptions?.headers, + ), contentType: "application/json", requestType: "json", body: serializers.webhooks.TestWebhookSubscriptionRequest.jsonOrThrow(_body, { @@ -579,19 +642,23 @@ export class Subscriptions { abortSignal: requestOptions?.abortSignal, }); if (_response.ok) { - return serializers.TestWebhookSubscriptionResponse.parseOrThrow(_response.body, { - unrecognizedObjectKeys: "passthrough", - allowUnrecognizedUnionMembers: true, - allowUnrecognizedEnumValues: true, - skipValidation: true, - breadcrumbsPrefix: ["response"], - }); + return { + data: serializers.TestWebhookSubscriptionResponse.parseOrThrow(_response.body, { + unrecognizedObjectKeys: "passthrough", + allowUnrecognizedUnionMembers: true, + allowUnrecognizedEnumValues: true, + skipValidation: true, + breadcrumbsPrefix: ["response"], + }), + rawResponse: _response.rawResponse, + }; } if (_response.error.reason === "status-code") { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.body, + rawResponse: _response.rawResponse, }); } @@ -600,6 +667,7 @@ export class Subscriptions { throw new errors.SquareError({ statusCode: _response.error.statusCode, body: _response.error.rawBody, + rawResponse: _response.rawResponse, }); case "timeout": throw new errors.SquareTimeoutError( @@ -608,6 +676,7 @@ export class Subscriptions { case "unknown": throw new errors.SquareError({ message: _response.error.errorMessage, + rawResponse: _response.rawResponse, }); } } diff --git a/src/api/resources/webhooks/resources/subscriptions/client/index.ts b/src/api/resources/webhooks/resources/subscriptions/client/index.ts index 415726b7f..f33205a0f 100644 --- a/src/api/resources/webhooks/resources/subscriptions/client/index.ts +++ b/src/api/resources/webhooks/resources/subscriptions/client/index.ts @@ -1 +1,2 @@ +export {}; export * from "./requests"; diff --git a/src/core/auth/BasicAuth.ts b/src/core/auth/BasicAuth.ts index 146df2150..89a3dadae 100644 --- a/src/core/auth/BasicAuth.ts +++ b/src/core/auth/BasicAuth.ts @@ -1,4 +1,4 @@ -import { Base64 } from "js-base64"; +import { base64Decode, base64Encode } from "../base64"; export interface BasicAuth { username: string; @@ -12,12 +12,12 @@ export const BasicAuth = { if (basicAuth == null) { return undefined; } - const token = Base64.encode(`${basicAuth.username}:${basicAuth.password}`); + const token = base64Encode(`${basicAuth.username}:${basicAuth.password}`); return `Basic ${token}`; }, fromAuthorizationHeader: (header: string): BasicAuth => { const credentials = header.replace(BASIC_AUTH_HEADER_PREFIX, ""); - const decoded = Base64.decode(credentials); + const decoded = base64Decode(credentials); const [username, password] = decoded.split(":", 2); if (username == null || password == null) { diff --git a/src/core/base64.ts b/src/core/base64.ts new file mode 100644 index 000000000..448a0db63 --- /dev/null +++ b/src/core/base64.ts @@ -0,0 +1,27 @@ +function base64ToBytes(base64: string): Uint8Array { + const binString = atob(base64); + return Uint8Array.from(binString, (m) => m.codePointAt(0)!); +} + +function bytesToBase64(bytes: Uint8Array): string { + const binString = String.fromCodePoint(...bytes); + return btoa(binString); +} + +export function base64Encode(input: string): string { + if (typeof Buffer !== "undefined") { + return Buffer.from(input, "utf8").toString("base64"); + } + + const bytes = new TextEncoder().encode(input); + return bytesToBase64(bytes); +} + +export function base64Decode(input: string): string { + if (typeof Buffer !== "undefined") { + return Buffer.from(input, "base64").toString("utf8"); + } + + const bytes = base64ToBytes(input); + return new TextDecoder().decode(bytes); +} diff --git a/src/core/fetcher/APIResponse.ts b/src/core/fetcher/APIResponse.ts index 3664d09e1..6335291bb 100644 --- a/src/core/fetcher/APIResponse.ts +++ b/src/core/fetcher/APIResponse.ts @@ -1,12 +1,23 @@ +import { RawResponse } from "./RawResponse"; + +/** + * The response of an API call. + * It is a successful response or a failed response. + */ export type APIResponse = SuccessfulResponse | FailedResponse; export interface SuccessfulResponse { ok: true; body: T; + /** + * @deprecated Use `rawResponse` instead + */ headers?: Record; + rawResponse: RawResponse; } export interface FailedResponse { ok: false; error: T; + rawResponse: RawResponse; } diff --git a/src/core/fetcher/BinaryResponse.ts b/src/core/fetcher/BinaryResponse.ts new file mode 100644 index 000000000..614cb59b1 --- /dev/null +++ b/src/core/fetcher/BinaryResponse.ts @@ -0,0 +1,36 @@ +import { ResponseWithBody } from "./ResponseWithBody.js"; + +export type BinaryResponse = { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bodyUsed) */ + bodyUsed: boolean; + /** + * Returns a ReadableStream of the response body. + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/body) + */ + stream: () => ReadableStream; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/arrayBuffer) */ + arrayBuffer: () => Promise; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/blob) */ + blob: () => Promise; + /** + * [MDN Reference](https://developer.mozilla.org/docs/Web/API/Request/bytes) + * Some versions of the Fetch API may not support this method. + */ + bytes?(): Promise; +}; + +export function getBinaryResponse(response: ResponseWithBody): BinaryResponse { + const binaryResponse: BinaryResponse = { + get bodyUsed() { + return response.bodyUsed; + }, + stream: () => response.body, + arrayBuffer: response.arrayBuffer.bind(response), + blob: response.blob.bind(response), + }; + if ("bytes" in response && typeof response.bytes === "function") { + binaryResponse.bytes = response.bytes.bind(response); + } + + return binaryResponse; +} diff --git a/src/core/fetcher/Fetcher.ts b/src/core/fetcher/Fetcher.ts index f3ee18ee8..88347cfbd 100644 --- a/src/core/fetcher/Fetcher.ts +++ b/src/core/fetcher/Fetcher.ts @@ -1,6 +1,9 @@ import { toJson } from "../json"; import { APIResponse } from "./APIResponse"; +import { abortRawResponse, toRawResponse, unknownRawResponse } from "./RawResponse"; +import { Supplier } from "./Supplier"; import { createRequestUrl } from "./createRequestUrl"; +import { getErrorResponseBody } from "./getErrorResponseBody"; import { getFetchFn } from "./getFetchFn"; import { getRequestBody } from "./getRequestBody"; import { getResponseBody } from "./getResponseBody"; @@ -14,7 +17,7 @@ export declare namespace Fetcher { url: string; method: string; contentType?: string; - headers?: Record; + headers?: Record | undefined>; queryParameters?: Record; body?: unknown; timeoutMs?: number; @@ -22,7 +25,7 @@ export declare namespace Fetcher { withCredentials?: boolean; abortSignal?: AbortSignal; requestType?: "json" | "file" | "bytes"; - responseType?: "json" | "blob" | "sse" | "streaming" | "text" | "arrayBuffer"; + responseType?: "json" | "blob" | "sse" | "streaming" | "text" | "arrayBuffer" | "binary-response"; duplex?: "half"; } @@ -50,20 +53,31 @@ export declare namespace Fetcher { } } -export async function fetcherImpl(args: Fetcher.Args): Promise> { - const headers: Record = {}; +async function getHeaders(args: Fetcher.Args): Promise> { + const newHeaders: Record = {}; if (args.body !== undefined && args.contentType != null) { - headers["Content-Type"] = args.contentType; + newHeaders["Content-Type"] = args.contentType; + } + + if (args.headers == null) { + return newHeaders; } - if (args.headers != null) { - for (const [key, value] of Object.entries(args.headers)) { - if (value != null) { - headers[key] = value; - } + for (const [key, value] of Object.entries(args.headers)) { + const result = await Supplier.get(value); + if (typeof result === "string") { + newHeaders[key] = result; + continue; } + if (result == null) { + continue; + } + newHeaders[key] = `${result}`; } + return newHeaders; +} +export async function fetcherImpl(args: Fetcher.Args): Promise> { const url = createRequestUrl(args.url, args.queryParameters); const requestBody: BodyInit | undefined = await getRequestBody({ body: args.body, @@ -78,7 +92,7 @@ export async function fetcherImpl(args: Fetcher.Args): Promise(args: Fetcher.Args): Promise= 200 && response.status < 400) { return { ok: true, - body: responseBody as R, + body: (await getResponseBody(response, args.responseType)) as R, headers: response.headers, + rawResponse: toRawResponse(response), }; } else { return { @@ -101,8 +115,9 @@ export async function fetcherImpl(args: Fetcher.Args): Promise(args: Fetcher.Args): Promise(args: Fetcher.Args): Promise(args: Fetcher.Args): Promise(args: Fetcher.Args): Promise; + + constructor(init?: HeadersInit) { + this.headers = new Map(); + + if (init) { + if (init instanceof Headers) { + init.forEach((value, key) => this.append(key, value)); + } else if (Array.isArray(init)) { + for (const [key, value] of init) { + if (typeof key === "string" && typeof value === "string") { + this.append(key, value); + } else { + throw new TypeError("Each header entry must be a [string, string] tuple"); + } + } + } else { + for (const [key, value] of Object.entries(init)) { + if (typeof value === "string") { + this.append(key, value); + } else { + throw new TypeError("Header values must be strings"); + } + } + } + } + } + + append(name: string, value: string): void { + const key = name.toLowerCase(); + const existing = this.headers.get(key) || []; + this.headers.set(key, [...existing, value]); + } + + delete(name: string): void { + const key = name.toLowerCase(); + this.headers.delete(key); + } + + get(name: string): string | null { + const key = name.toLowerCase(); + const values = this.headers.get(key); + return values ? values.join(", ") : null; + } + + has(name: string): boolean { + const key = name.toLowerCase(); + return this.headers.has(key); + } + + set(name: string, value: string): void { + const key = name.toLowerCase(); + this.headers.set(key, [value]); + } + + forEach(callbackfn: (value: string, key: string, parent: Headers) => void, thisArg?: unknown): void { + const boundCallback = thisArg ? callbackfn.bind(thisArg) : callbackfn; + this.headers.forEach((values, key) => boundCallback(values.join(", "), key, this)); + } + + getSetCookie(): string[] { + return this.headers.get("set-cookie") || []; + } + + *entries(): HeadersIterator<[string, string]> { + for (const [key, values] of this.headers.entries()) { + yield [key, values.join(", ")]; + } + } + + *keys(): HeadersIterator { + yield* this.headers.keys(); + } + + *values(): HeadersIterator { + for (const values of this.headers.values()) { + yield values.join(", "); + } + } + + [Symbol.iterator](): HeadersIterator<[string, string]> { + return this.entries(); + } + }; +} + +export { Headers }; diff --git a/src/core/fetcher/HttpResponsePromise.ts b/src/core/fetcher/HttpResponsePromise.ts new file mode 100644 index 000000000..6b0bc4fce --- /dev/null +++ b/src/core/fetcher/HttpResponsePromise.ts @@ -0,0 +1,116 @@ +import { WithRawResponse } from "./RawResponse"; + +/** + * A promise that returns the parsed response and lets you retrieve the raw response too. + */ +export class HttpResponsePromise extends Promise { + private innerPromise: Promise>; + private unwrappedPromise: Promise | undefined; + + private constructor(promise: Promise>) { + // Initialize with a no-op to avoid premature parsing + super((resolve) => { + resolve(undefined as unknown as T); + }); + this.innerPromise = promise; + } + + /** + * Creates an `HttpResponsePromise` from a function that returns a promise. + * + * @param fn - A function that returns a promise resolving to a `WithRawResponse` object. + * @param args - Arguments to pass to the function. + * @returns An `HttpResponsePromise` instance. + */ + public static fromFunction Promise>, T>( + fn: F, + ...args: Parameters + ): HttpResponsePromise { + return new HttpResponsePromise(fn(...args)); + } + + /** + * Creates a function that returns an `HttpResponsePromise` from a function that returns a promise. + * + * @param fn - A function that returns a promise resolving to a `WithRawResponse` object. + * @returns A function that returns an `HttpResponsePromise` instance. + */ + public static interceptFunction< + F extends (...args: never[]) => Promise>, + T = Awaited>["data"], + >(fn: F): (...args: Parameters) => HttpResponsePromise { + return (...args: Parameters): HttpResponsePromise => { + return HttpResponsePromise.fromPromise(fn(...args)); + }; + } + + /** + * Creates an `HttpResponsePromise` from an existing promise. + * + * @param promise - A promise resolving to a `WithRawResponse` object. + * @returns An `HttpResponsePromise` instance. + */ + public static fromPromise(promise: Promise>): HttpResponsePromise { + return new HttpResponsePromise(promise); + } + + /** + * Creates an `HttpResponsePromise` from an executor function. + * + * @param executor - A function that takes resolve and reject callbacks to create a promise. + * @returns An `HttpResponsePromise` instance. + */ + public static fromExecutor( + executor: (resolve: (value: WithRawResponse) => void, reject: (reason?: unknown) => void) => void, + ): HttpResponsePromise { + const promise = new Promise>(executor); + return new HttpResponsePromise(promise); + } + + /** + * Creates an `HttpResponsePromise` from a resolved result. + * + * @param result - A `WithRawResponse` object to resolve immediately. + * @returns An `HttpResponsePromise` instance. + */ + public static fromResult(result: WithRawResponse): HttpResponsePromise { + const promise = Promise.resolve(result); + return new HttpResponsePromise(promise); + } + + private unwrap(): Promise { + if (!this.unwrappedPromise) { + this.unwrappedPromise = this.innerPromise.then(({ data }) => data); + } + return this.unwrappedPromise; + } + + /** @inheritdoc */ + public override then( + onfulfilled?: ((value: T) => TResult1 | PromiseLike) | null, + onrejected?: ((reason: unknown) => TResult2 | PromiseLike) | null, + ): Promise { + return this.unwrap().then(onfulfilled, onrejected); + } + + /** @inheritdoc */ + public override catch( + onrejected?: ((reason: unknown) => TResult | PromiseLike) | null, + ): Promise { + return this.unwrap().catch(onrejected); + } + + /** @inheritdoc */ + public override finally(onfinally?: (() => void) | null): Promise { + return this.unwrap().finally(onfinally); + } + + /** + * Retrieves the data and raw response. + * + * @returns A promise resolving to a `WithRawResponse` object. + */ + public async withRawResponse(): Promise> { + return await this.innerPromise; + } +} diff --git a/src/core/fetcher/RawResponse.ts b/src/core/fetcher/RawResponse.ts new file mode 100644 index 000000000..bdaa614a3 --- /dev/null +++ b/src/core/fetcher/RawResponse.ts @@ -0,0 +1,61 @@ +import { Headers } from "./Headers"; + +/** + * The raw response from the fetch call excluding the body. + */ +export type RawResponse = Omit< + { + [K in keyof Response as Response[K] extends Function ? never : K]: Response[K]; // strips out functions + }, + "ok" | "body" | "bodyUsed" +>; // strips out body and bodyUsed + +/** + * A raw response indicating that the request was aborted. + */ +export const abortRawResponse: RawResponse = { + headers: new Headers(), + redirected: false, + status: 499, + statusText: "Client Closed Request", + type: "error", + url: "", +} as const; + +/** + * A raw response indicating an unknown error. + */ +export const unknownRawResponse: RawResponse = { + headers: new Headers(), + redirected: false, + status: 0, + statusText: "Unknown Error", + type: "error", + url: "", +} as const; + +/** + * Converts a `RawResponse` object into a `RawResponse` by extracting its properties, + * excluding the `body` and `bodyUsed` fields. + * + * @param response - The `RawResponse` object to convert. + * @returns A `RawResponse` object containing the extracted properties of the input response. + */ +export function toRawResponse(response: Response): RawResponse { + return { + headers: response.headers, + redirected: response.redirected, + status: response.status, + statusText: response.statusText, + type: response.type, + url: response.url, + }; +} + +/** + * Creates a `RawResponse` from a standard `Response` object. + */ +export interface WithRawResponse { + readonly data: T; + readonly rawResponse: RawResponse; +} diff --git a/src/core/fetcher/ResponseWithBody.ts b/src/core/fetcher/ResponseWithBody.ts new file mode 100644 index 000000000..445d40f87 --- /dev/null +++ b/src/core/fetcher/ResponseWithBody.ts @@ -0,0 +1,7 @@ +export type ResponseWithBody = Response & { + body: ReadableStream; +}; + +export function isResponseWithBody(response: Response): response is ResponseWithBody { + return (response as ResponseWithBody).body != null; +} diff --git a/src/core/fetcher/createRequestUrl.ts b/src/core/fetcher/createRequestUrl.ts index f1157ce72..4bcb19854 100644 --- a/src/core/fetcher/createRequestUrl.ts +++ b/src/core/fetcher/createRequestUrl.ts @@ -1,10 +1,6 @@ -import qs from "qs"; +import { toQueryString } from "../url/qs"; -export function createRequestUrl( - baseUrl: string, - queryParameters?: Record, -): string { - return Object.keys(queryParameters ?? {}).length > 0 - ? `${baseUrl}?${qs.stringify(queryParameters, { arrayFormat: "repeat" })}` - : baseUrl; +export function createRequestUrl(baseUrl: string, queryParameters?: Record): string { + const queryString = toQueryString(queryParameters, { arrayFormat: "repeat" }); + return queryString ? `${baseUrl}?${queryString}` : baseUrl; } diff --git a/src/core/fetcher/getErrorResponseBody.ts b/src/core/fetcher/getErrorResponseBody.ts new file mode 100644 index 000000000..cb7677214 --- /dev/null +++ b/src/core/fetcher/getErrorResponseBody.ts @@ -0,0 +1,32 @@ +import { fromJson } from "../json"; +import { getResponseBody } from "./getResponseBody"; + +export async function getErrorResponseBody(response: Response): Promise { + let contentType = response.headers.get("Content-Type")?.toLowerCase(); + if (contentType == null || contentType.length === 0) { + return getResponseBody(response); + } + + if (contentType.indexOf(";") !== -1) { + contentType = contentType.split(";")[0]?.trim() ?? ""; + } + switch (contentType) { + case "application/hal+json": + case "application/json": + case "application/ld+json": + case "application/problem+json": + case "application/vnd.api+json": + case "text/json": + const text = await response.text(); + return text.length > 0 ? fromJson(text) : undefined; + default: + if (contentType.startsWith("application/vnd.") && contentType.endsWith("+json")) { + const text = await response.text(); + return text.length > 0 ? fromJson(text) : undefined; + } + + // Fallback to plain text if content type is not recognized + // Even if no body is present, the response will be an empty string + return await response.text(); + } +} diff --git a/src/core/fetcher/getFetchFn.ts b/src/core/fetcher/getFetchFn.ts index 9fd9bfc42..8f4cf5e19 100644 --- a/src/core/fetcher/getFetchFn.ts +++ b/src/core/fetcher/getFetchFn.ts @@ -1,4 +1,4 @@ -import { RUNTIME } from "../runtime"; +import { RUNTIME } from "../runtime/index"; /** * Returns a fetch function based on the runtime diff --git a/src/core/fetcher/getResponseBody.ts b/src/core/fetcher/getResponseBody.ts index d046e6ea2..ba03f424a 100644 --- a/src/core/fetcher/getResponseBody.ts +++ b/src/core/fetcher/getResponseBody.ts @@ -1,34 +1,45 @@ +import { getBinaryResponse } from "./BinaryResponse"; +import { isResponseWithBody } from "./ResponseWithBody"; +import { fromJson } from "../json"; + import { chooseStreamWrapper } from "./stream-wrappers/chooseStreamWrapper"; export async function getResponseBody(response: Response, responseType?: string): Promise { - if (response.body != null && responseType === "blob") { - return await response.blob(); - } else if (response.body != null && responseType === "arrayBuffer") { - return await response.arrayBuffer(); - } else if (response.body != null && responseType === "sse") { - return response.body; - } else if (response.body != null && responseType === "streaming") { - return chooseStreamWrapper(response.body); - } else if (response.body != null && responseType === "text") { - return await response.text(); - } else { - const text = await response.text(); - if (text.length > 0) { - try { - let responseBody = JSON.parse(text); - return responseBody; - } catch (err) { - return { - ok: false, - error: { - reason: "non-json", - statusCode: response.status, - rawBody: text, - }, - }; - } - } else { - return undefined; + if (!isResponseWithBody(response)) { + return undefined; + } + switch (responseType) { + case "binary-response": + return getBinaryResponse(response); + case "blob": + return await response.blob(); + case "arrayBuffer": + return await response.arrayBuffer(); + case "sse": + return response.body; + case "streaming": + return chooseStreamWrapper(response.body); + + case "text": + return await response.text(); + } + + // if responseType is "json" or not specified, try to parse as JSON + const text = await response.text(); + if (text.length > 0) { + try { + let responseBody = fromJson(text); + return responseBody; + } catch (err) { + return { + ok: false, + error: { + reason: "non-json", + statusCode: response.status, + rawBody: text, + }, + }; } } + return undefined; } diff --git a/src/core/fetcher/index.ts b/src/core/fetcher/index.ts index 2d658ca48..9fffe7494 100644 --- a/src/core/fetcher/index.ts +++ b/src/core/fetcher/index.ts @@ -3,3 +3,7 @@ export { fetcher } from "./Fetcher"; export type { Fetcher, FetchFunction } from "./Fetcher"; export { getHeader } from "./getHeader"; export { Supplier } from "./Supplier"; +export { abortRawResponse, toRawResponse, unknownRawResponse } from "./RawResponse"; +export type { RawResponse, WithRawResponse } from "./RawResponse"; +export { HttpResponsePromise } from "./HttpResponsePromise"; +export { BinaryResponse } from "./BinaryResponse"; diff --git a/src/core/form-data-utils/FormDataWrapper.ts b/src/core/form-data-utils/FormDataWrapper.ts index ad0d90dc1..2becf2e56 100644 --- a/src/core/form-data-utils/FormDataWrapper.ts +++ b/src/core/form-data-utils/FormDataWrapper.ts @@ -1,4 +1,8 @@ -import { RUNTIME } from "../runtime"; +import { RUNTIME } from "../runtime/index"; + +export async function toReadableStream(encoder: import("form-data-encoder").FormDataEncoder) { + return (await import("readable-stream")).Readable.from(encoder); +} export type MaybePromise = Promise | T; @@ -11,6 +15,16 @@ interface FormDataRequest { function isNamedValue(value: unknown): value is { name: string } { return typeof value === "object" && value != null && "name" in value; } +function isPathedValue(value: unknown): value is { path: unknown } { + return typeof value === "object" && value != null && "path" in value; +} + +function getLastPathSegment(pathStr: string): string { + const lastForwardSlash = pathStr.lastIndexOf("/"); + const lastBackSlash = pathStr.lastIndexOf("\\"); + const lastSlashIndex = Math.max(lastForwardSlash, lastBackSlash); + return lastSlashIndex >= 0 ? pathStr.substring(lastSlashIndex + 1) : pathStr; +} export interface CrossPlatformFormData { setup(): Promise; @@ -55,10 +69,21 @@ export class Node18FormData implements CrossPlatformFormData { this.fd?.append(key, value); } - public async appendFile(key: string, value: unknown, fileName?: string): Promise { - if (fileName == null && isNamedValue(value)) { - fileName = value.name; + private getFileName(value: any, filename?: string): string | undefined { + if (filename != null) { + return filename; + } + if (isNamedValue(value)) { + return value.name; } + if (isPathedValue(value) && value.path) { + return getLastPathSegment(value.path.toString()); + } + return undefined; + } + + public async appendFile(key: string, value: unknown, fileName?: string): Promise { + fileName = this.getFileName(value, fileName); if (value instanceof Blob) { this.fd?.append(key, value, fileName); @@ -77,7 +102,7 @@ export class Node18FormData implements CrossPlatformFormData { public async getRequest(): Promise> { const encoder = new (await import("form-data-encoder")).FormDataEncoder(this.fd as any); return { - body: (await import("readable-stream")).Readable.from(encoder), + body: await toReadableStream(encoder), headers: encoder.headers, duplex: "half", }; @@ -118,10 +143,21 @@ export class Node16FormData implements CrossPlatformFormData { this.fd?.append(key, value); } - public async appendFile(key: string, value: unknown, fileName?: string): Promise { - if (fileName == null && isNamedValue(value)) { - fileName = value.name; + private getFileName(value: any, filename?: string): string | undefined { + if (filename != null) { + return filename; + } + if (isNamedValue(value)) { + return value.name; } + if (isPathedValue(value) && value.path) { + return getLastPathSegment(value.path.toString()); + } + return undefined; + } + + public async appendFile(key: string, value: unknown, fileName?: string): Promise { + fileName = this.getFileName(value, fileName); let bufferedValue; if (value instanceof Blob) { @@ -161,9 +197,25 @@ export class WebFormData implements CrossPlatformFormData { this.fd?.append(key, value); } + private getFileName(value: any, filename?: string): string | undefined { + if (filename != null) { + return filename; + } + if (isNamedValue(value)) { + return value.name; + } + if (isPathedValue(value) && value.path) { + return getLastPathSegment(value.path.toString()); + } + return undefined; + } + public async appendFile(key: string, value: any, fileName?: string): Promise { - if (fileName == null && isNamedValue(value)) { - fileName = value.name; + fileName = this.getFileName(value, fileName); + + if (value instanceof Blob) { + this.fd?.append(key, value, fileName); + return; } this.fd?.append(key, new Blob([value]), fileName); } diff --git a/src/core/form-data-utils/encodeAsFormParameter.ts b/src/core/form-data-utils/encodeAsFormParameter.ts new file mode 100644 index 000000000..fdb2d742e --- /dev/null +++ b/src/core/form-data-utils/encodeAsFormParameter.ts @@ -0,0 +1,12 @@ +import { toQueryString } from "../url/qs"; + +export function encodeAsFormParameter(value: unknown): Record { + const stringified = toQueryString(value, { encode: false }); + + const keyValuePairs = stringified.split("&").map((pair) => { + const [key, value] = pair.split("="); + return [key, value] as const; + }); + + return Object.fromEntries(keyValuePairs); +} diff --git a/src/core/form-data-utils/index.ts b/src/core/form-data-utils/index.ts index f210ac408..62121d587 100644 --- a/src/core/form-data-utils/index.ts +++ b/src/core/form-data-utils/index.ts @@ -1 +1,2 @@ +export { encodeAsFormParameter } from "./encodeAsFormParameter"; export * from "./FormDataWrapper"; diff --git a/src/core/headers.ts b/src/core/headers.ts new file mode 100644 index 000000000..1b4d3308d --- /dev/null +++ b/src/core/headers.ts @@ -0,0 +1,35 @@ +import * as core from "./index"; + +export function mergeHeaders( + ...headersArray: (Record | undefined> | undefined)[] +): Record> { + const result: Record> = {}; + + for (const [key, value] of headersArray + .filter((headers) => headers != null) + .flatMap((headers) => Object.entries(headers))) { + if (value != null) { + result[key] = value; + } else if (key in result) { + delete result[key]; + } + } + + return result; +} + +export function mergeOnlyDefinedHeaders( + ...headersArray: (Record | undefined> | undefined)[] +): Record> { + const result: Record> = {}; + + for (const [key, value] of headersArray + .filter((headers) => headers != null) + .flatMap((headers) => Object.entries(headers))) { + if (value != null) { + result[key] = value; + } + } + + return result; +} diff --git a/src/core/index.ts b/src/core/index.ts index 31520f7bd..c8bf52015 100644 --- a/src/core/index.ts +++ b/src/core/index.ts @@ -4,4 +4,5 @@ export * from "./runtime"; export * from "./utils"; export * from "./pagination"; export * from "./form-data-utils"; +export * as url from "./url"; export * as serialization from "./schemas"; diff --git a/src/core/json.ts b/src/core/json.ts index ddc9d2dc6..cca884d32 100644 --- a/src/core/json.ts +++ b/src/core/json.ts @@ -18,7 +18,10 @@ export const toJson = ( replacer?: (this: unknown, key: string, value: unknown) => unknown, space?: string | number, ): string => { - if (!data) { + if (typeof data === "bigint") { + return data.toString(); + } + if (typeof data !== "object") { return JSON.stringify(data, replacer, space); } diff --git a/src/core/pagination/Page.ts b/src/core/pagination/Page.ts index 07c6796ee..30df7280b 100644 --- a/src/core/pagination/Page.ts +++ b/src/core/pagination/Page.ts @@ -1,3 +1,5 @@ +import { HttpResponsePromise, RawResponse } from "../fetcher"; + /** * A page of results from a paginated API. * @@ -5,24 +7,28 @@ */ export class Page implements AsyncIterable { public data: T[]; + public rawResponse: RawResponse; private response: unknown; private _hasNextPage: (response: unknown) => boolean; private getItems: (response: unknown) => T[]; - private loadNextPage: (response: unknown) => Promise; + private loadNextPage: (response: unknown) => HttpResponsePromise; constructor({ response, + rawResponse, hasNextPage, getItems, loadPage, }: { response: unknown; + rawResponse: RawResponse; hasNextPage: (response: unknown) => boolean; getItems: (response: unknown) => T[]; - loadPage: (response: unknown) => Promise; + loadPage: (response: unknown) => HttpResponsePromise; }) { this.response = response; + this.rawResponse = rawResponse; this.data = getItems(response); this._hasNextPage = hasNextPage; this.getItems = getItems; @@ -34,7 +40,9 @@ export class Page implements AsyncIterable { * @returns this */ public async getNextPage(): Promise { - this.response = await this.loadNextPage(this.response); + const { data, rawResponse } = await this.loadNextPage(this.response).withRawResponse(); + this.response = data; + this.rawResponse = rawResponse; this.data = this.getItems(this.response); return this; } diff --git a/src/core/pagination/Pageable.ts b/src/core/pagination/Pageable.ts index befce6359..3a5220ebd 100644 --- a/src/core/pagination/Pageable.ts +++ b/src/core/pagination/Pageable.ts @@ -1,8 +1,10 @@ +import { RawResponse } from "../fetcher"; import { Page } from "./Page"; export declare namespace Pageable { interface Args { response: Response; + rawResponse: RawResponse; hasNextPage: (response: Response) => boolean; getItems: (response: Response) => Item[]; loadPage: (response: Response) => Promise; diff --git a/src/core/runtime/runtime.ts b/src/core/runtime/runtime.ts index a97501751..08fd2563f 100644 --- a/src/core/runtime/runtime.ts +++ b/src/core/runtime/runtime.ts @@ -11,6 +11,9 @@ interface BunGlobal { declare const Deno: DenoGlobal | undefined; declare const Bun: BunGlobal | undefined; declare const EdgeRuntime: string | undefined; +declare const self: typeof globalThis.self & { + importScripts?: unknown; +}; /** * A constant that indicates which environment and version the SDK is running in. @@ -62,7 +65,6 @@ function evaluateRuntime(): Runtime { */ const isWebWorker = typeof self === "object" && - // @ts-ignore typeof self?.importScripts === "function" && (self.constructor?.name === "DedicatedWorkerGlobalScope" || self.constructor?.name === "ServiceWorkerGlobalScope" || diff --git a/src/core/url/index.ts b/src/core/url/index.ts new file mode 100644 index 000000000..35ed375f6 --- /dev/null +++ b/src/core/url/index.ts @@ -0,0 +1,2 @@ +export { join } from "./join"; +export { toQueryString } from "./qs"; diff --git a/src/core/url/join.ts b/src/core/url/join.ts new file mode 100644 index 000000000..1dda77923 --- /dev/null +++ b/src/core/url/join.ts @@ -0,0 +1,55 @@ +export function join(base: string, ...segments: string[]): string { + if (!base) { + return ""; + } + + if (base.includes("://")) { + let url: URL; + try { + url = new URL(base); + } catch { + // Fallback to path joining if URL is malformed + return joinPath(base, ...segments); + } + + for (const segment of segments) { + const cleanSegment = trimSlashes(segment); + if (cleanSegment) { + url.pathname = joinPathSegments(url.pathname, cleanSegment); + } + } + + return url.toString(); + } + + return joinPath(base, ...segments); +} + +function joinPath(base: string, ...segments: string[]): string { + let result = base; + + for (const segment of segments) { + const cleanSegment = trimSlashes(segment); + if (cleanSegment) { + result = joinPathSegments(result, cleanSegment); + } + } + + return result; +} + +function joinPathSegments(left: string, right: string): string { + if (left.endsWith("/")) { + return left + right; + } + return left + "/" + right; +} + +function trimSlashes(str: string): string { + if (!str) return str; + + let start = str.startsWith("/") ? 1 : 0; + let end = str.endsWith("/") ? str.length - 1 : str.length; + + return str.slice(start, end); +} diff --git a/src/core/url/qs.ts b/src/core/url/qs.ts new file mode 100644 index 000000000..13e89be9d --- /dev/null +++ b/src/core/url/qs.ts @@ -0,0 +1,74 @@ +interface QueryStringOptions { + arrayFormat?: "indices" | "repeat"; + encode?: boolean; +} + +const defaultQsOptions: Required = { + arrayFormat: "indices", + encode: true, +} as const; + +function encodeValue(value: unknown, shouldEncode: boolean): string { + if (value === undefined) { + return ""; + } + if (value === null) { + return ""; + } + const stringValue = String(value); + return shouldEncode ? encodeURIComponent(stringValue) : stringValue; +} + +function stringifyObject(obj: Record, prefix = "", options: Required): string[] { + const parts: string[] = []; + + for (const [key, value] of Object.entries(obj)) { + const fullKey = prefix ? `${prefix}[${key}]` : key; + + if (value === undefined) { + continue; + } + + if (Array.isArray(value)) { + if (value.length === 0) { + continue; + } + for (let i = 0; i < value.length; i++) { + const item = value[i]; + if (item === undefined) { + continue; + } + if (typeof item === "object" && !Array.isArray(item) && item !== null) { + const arrayKey = options.arrayFormat === "indices" ? `${fullKey}[${i}]` : fullKey; + parts.push(...stringifyObject(item as Record, arrayKey, options)); + } else { + const arrayKey = options.arrayFormat === "indices" ? `${fullKey}[${i}]` : fullKey; + const encodedKey = options.encode ? encodeURIComponent(arrayKey) : arrayKey; + parts.push(`${encodedKey}=${encodeValue(item, options.encode)}`); + } + } + } else if (typeof value === "object" && value !== null) { + if (Object.keys(value as Record).length === 0) { + continue; + } + parts.push(...stringifyObject(value as Record, fullKey, options)); + } else { + const encodedKey = options.encode ? encodeURIComponent(fullKey) : fullKey; + parts.push(`${encodedKey}=${encodeValue(value, options.encode)}`); + } + } + + return parts; +} + +export function toQueryString(obj: unknown, options?: QueryStringOptions): string { + if (obj == null || typeof obj !== "object") { + return ""; + } + + const parts = stringifyObject(obj as Record, "", { + ...defaultQsOptions, + ...options, + }); + return parts.join("&"); +} diff --git a/src/errors/SquareError.ts b/src/errors/SquareError.ts index a6b576b64..e563a1e53 100644 --- a/src/errors/SquareError.ts +++ b/src/errors/SquareError.ts @@ -3,6 +3,7 @@ */ import { toJson } from "../core/json"; +import * as core from "../core"; import { Error_, ErrorCategory as GeneratedErrorCategory, ErrorCode as GeneratedErrorCode } from "../api"; const fallbackError = { @@ -14,20 +15,28 @@ export class SquareError extends Error { readonly statusCode?: number; readonly body?: unknown; readonly errors: SquareError.BodyError[]; + public readonly rawResponse?: core.RawResponse; - constructor({ message, statusCode, body }: { message?: string; statusCode?: number; body?: unknown }) { + constructor({ + message, + statusCode, + body, + rawResponse, + }: { + message?: string; + statusCode?: number; + body?: unknown; + rawResponse?: core.RawResponse; + }) { super(buildMessage({ message, statusCode, body })); Object.setPrototypeOf(this, SquareError.prototype); - if (statusCode != null) { - this.statusCode = statusCode; - } - + this.statusCode = statusCode; + this.rawResponse = rawResponse; this.body = body; if (body != null && typeof body === "object") { if ("errors" in body) { this.errors = (body as unknown as SquareErrorBody).errors ?? [fallbackError]; - } - else { + } else { const v1Error = body as V1Error; this.errors = [ { @@ -35,12 +44,11 @@ export class SquareError extends Error { code: v1Error.type ?? SquareError.ErrorCode.Unknown, detail: v1Error.message, field: v1Error.field, - } + }, ]; } - } - else{ - this.errors = [fallbackError] + } else { + this.errors = [fallbackError]; } } } diff --git a/tests/BrowserTestEnvironment.ts b/tests/BrowserTestEnvironment.ts new file mode 100644 index 000000000..0f32bf7b0 --- /dev/null +++ b/tests/BrowserTestEnvironment.ts @@ -0,0 +1,17 @@ +import { TestEnvironment } from "jest-environment-jsdom"; + +class BrowserTestEnvironment extends TestEnvironment { + async setup() { + await super.setup(); + this.global.Request = Request; + this.global.Response = Response; + this.global.ReadableStream = ReadableStream; + this.global.TextEncoder = TextEncoder; + this.global.TextDecoder = TextDecoder; + this.global.FormData = FormData; + this.global.File = File; + this.global.Blob = Blob; + } +} + +export default BrowserTestEnvironment; diff --git a/tests/bigint.setup.ts b/tests/bigint.setup.ts new file mode 100644 index 000000000..d03d34f21 --- /dev/null +++ b/tests/bigint.setup.ts @@ -0,0 +1,13 @@ +import { expect } from "@jest/globals"; + +expect.addEqualityTesters([ + (a: any, b: any) => { + if ((typeof a === "bigint" && typeof b === "number") || (typeof a === "number" && typeof b === "bigint")) { + return BigInt(a) === BigInt(b); + } + // Return undefined to let Jest handle other comparisons normally + return undefined; + }, +]); + +export {}; diff --git a/tests/mock-server/MockServer.ts b/tests/mock-server/MockServer.ts new file mode 100644 index 000000000..6e258f172 --- /dev/null +++ b/tests/mock-server/MockServer.ts @@ -0,0 +1,29 @@ +import { RequestHandlerOptions } from "msw"; +import type { SetupServer } from "msw/node"; + +import { mockEndpointBuilder } from "./mockEndpointBuilder"; + +export interface MockServerOptions { + baseUrl: string; + server: SetupServer; +} + +export class MockServer { + private readonly server: SetupServer; + public readonly baseUrl: string; + + constructor({ baseUrl, server }: MockServerOptions) { + this.baseUrl = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl; + this.server = server; + } + + public mockEndpoint(options?: RequestHandlerOptions): ReturnType { + const builder = mockEndpointBuilder({ + once: options?.once, + onBuild: (handler) => { + this.server.use(handler); + }, + }).baseUrl(this.baseUrl); + return builder; + } +} diff --git a/tests/mock-server/MockServerPool.ts b/tests/mock-server/MockServerPool.ts new file mode 100644 index 000000000..81608069e --- /dev/null +++ b/tests/mock-server/MockServerPool.ts @@ -0,0 +1,106 @@ +import { setupServer } from "msw/node"; + +import { fromJson, toJson } from "../../src/core/json"; +import { MockServer } from "./MockServer"; +import { randomBaseUrl } from "./randomBaseUrl"; + +const mswServer = setupServer(); +interface MockServerOptions { + baseUrl?: string; +} + +async function formatHttpRequest(request: Request, id?: string): Promise { + try { + const clone = request.clone(); + const headers = [...clone.headers.entries()].map(([k, v]) => `${k}: ${v}`).join("\n"); + + let body = ""; + try { + const contentType = clone.headers.get("content-type"); + if (contentType?.includes("application/json")) { + body = toJson(fromJson(await clone.text()), undefined, 2); + } else if (clone.body) { + body = await clone.text(); + } + } catch (e) { + body = "(unable to parse body)"; + } + + const title = id ? `### Request ${id} ###\n` : ""; + const firstLine = `${title}${request.method} ${request.url.toString()} HTTP/1.1`; + + return `\n${firstLine}\n${headers}\n\n${body || "(no body)"}\n`; + } catch (e) { + return `Error formatting request: ${e}`; + } +} + +async function formatHttpResponse(response: Response, id?: string): Promise { + try { + const clone = response.clone(); + const headers = [...clone.headers.entries()].map(([k, v]) => `${k}: ${v}`).join("\n"); + + let body = ""; + try { + const contentType = clone.headers.get("content-type"); + if (contentType?.includes("application/json")) { + body = toJson(fromJson(await clone.text()), undefined, 2); + } else if (clone.body) { + body = await clone.text(); + } + } catch (e) { + body = "(unable to parse body)"; + } + + const title = id ? `### Response for ${id} ###\n` : ""; + const firstLine = `${title}HTTP/1.1 ${response.status} ${response.statusText}`; + + return `\n${firstLine}\n${headers}\n\n${body || "(no body)"}\n`; + } catch (e) { + return `Error formatting response: ${e}`; + } +} + +class MockServerPool { + private servers: MockServer[] = []; + + public createServer(options?: Partial): MockServer { + const baseUrl = options?.baseUrl || randomBaseUrl(); + const server = new MockServer({ baseUrl, server: mswServer }); + this.servers.push(server); + return server; + } + + public getServers(): MockServer[] { + return [...this.servers]; + } + + public listen(): void { + const onUnhandledRequest = process.env.LOG_LEVEL === "debug" ? "warn" : "bypass"; + mswServer.listen({ onUnhandledRequest }); + + if (process.env.LOG_LEVEL === "debug") { + mswServer.events.on("request:start", async ({ request, requestId }) => { + const formattedRequest = await formatHttpRequest(request, requestId); + console.debug("request:start\n" + formattedRequest); + }); + + mswServer.events.on("request:unhandled", async ({ request, requestId }) => { + const formattedRequest = await formatHttpRequest(request, requestId); + console.debug("request:unhandled\n" + formattedRequest); + }); + + mswServer.events.on("response:mocked", async ({ request, response, requestId }) => { + const formattedResponse = await formatHttpResponse(response, requestId); + console.debug("response:mocked\n" + formattedResponse); + }); + } + } + + public close(): void { + this.servers = []; + mswServer.close(); + } +} + +export const mockServerPool = new MockServerPool(); diff --git a/tests/mock-server/mockEndpointBuilder.ts b/tests/mock-server/mockEndpointBuilder.ts new file mode 100644 index 000000000..390b22568 --- /dev/null +++ b/tests/mock-server/mockEndpointBuilder.ts @@ -0,0 +1,209 @@ +import { DefaultBodyType, HttpHandler, HttpResponse, HttpResponseResolver, http } from "msw"; + +import { toJson } from "../../src/core/json"; +import { withHeaders } from "./withHeaders"; +import { withJson } from "./withJson"; + +type HttpMethod = "all" | "get" | "post" | "put" | "delete" | "patch" | "options" | "head"; + +interface MethodStage { + baseUrl(baseUrl: string): MethodStage; + all(path: string): RequestHeadersStage; + get(path: string): RequestHeadersStage; + post(path: string): RequestHeadersStage; + put(path: string): RequestHeadersStage; + delete(path: string): RequestHeadersStage; + patch(path: string): RequestHeadersStage; + options(path: string): RequestHeadersStage; + head(path: string): RequestHeadersStage; +} + +interface RequestHeadersStage extends RequestBodyStage, ResponseStage { + header(name: string, value: string): RequestHeadersStage; + headers(headers: Record): RequestBodyStage; +} + +interface RequestBodyStage extends ResponseStage { + jsonBody(body: unknown): ResponseStage; +} + +interface ResponseStage { + respondWith(): ResponseStatusStage; +} +interface ResponseStatusStage { + statusCode(statusCode: number): ResponseHeaderStage; +} + +interface ResponseHeaderStage extends ResponseBodyStage, BuildStage { + header(name: string, value: string): ResponseHeaderStage; + headers(headers: Record): ResponseHeaderStage; +} + +interface ResponseBodyStage { + jsonBody(body: unknown): BuildStage; +} + +interface BuildStage { + build(): HttpHandler; +} + +export interface HttpHandlerBuilderOptions { + onBuild?: (handler: HttpHandler) => void; + once?: boolean; +} + +class RequestBuilder implements MethodStage, RequestHeadersStage, RequestBodyStage, ResponseStage { + private method: HttpMethod = "get"; + private _baseUrl: string = ""; + private path: string = "/"; + private readonly predicates: ((resolver: HttpResponseResolver) => HttpResponseResolver)[] = []; + private readonly handlerOptions?: HttpHandlerBuilderOptions; + + constructor(options?: HttpHandlerBuilderOptions) { + this.handlerOptions = options; + } + + baseUrl(baseUrl: string): MethodStage { + this._baseUrl = baseUrl; + return this; + } + + all(path: string): RequestHeadersStage { + this.method = "all"; + this.path = path; + return this; + } + + get(path: string): RequestHeadersStage { + this.method = "get"; + this.path = path; + return this; + } + + post(path: string): RequestHeadersStage { + this.method = "post"; + this.path = path; + return this; + } + + put(path: string): RequestHeadersStage { + this.method = "put"; + this.path = path; + return this; + } + + delete(path: string): RequestHeadersStage { + this.method = "delete"; + this.path = path; + return this; + } + + patch(path: string): RequestHeadersStage { + this.method = "patch"; + this.path = path; + return this; + } + + options(path: string): RequestHeadersStage { + this.method = "options"; + this.path = path; + return this; + } + + head(path: string): RequestHeadersStage { + this.method = "head"; + this.path = path; + return this; + } + + header(name: string, value: string): RequestHeadersStage { + this.predicates.push((resolver) => withHeaders({ [name]: value }, resolver)); + return this; + } + + headers(headers: Record): RequestBodyStage { + this.predicates.push((resolver) => withHeaders(headers, resolver)); + return this; + } + + jsonBody(body: unknown): ResponseStage { + this.predicates.push((resolver) => withJson(body, resolver)); + return this; + } + + respondWith(): ResponseStatusStage { + return new ResponseBuilder(this.method, this.buildPath(), this.predicates, this.handlerOptions); + } + + private buildPath(): string { + if (this._baseUrl.endsWith("/") && this.path.startsWith("/")) { + return this._baseUrl + this.path.slice(1); + } + if (!this._baseUrl.endsWith("/") && !this.path.startsWith("/")) { + return this._baseUrl + "/" + this.path; + } + return this._baseUrl + this.path; + } +} + +class ResponseBuilder implements ResponseStatusStage, ResponseHeaderStage, ResponseBodyStage, BuildStage { + private readonly method: HttpMethod; + private readonly path: string; + private readonly requestPredicates: ((resolver: HttpResponseResolver) => HttpResponseResolver)[]; + private readonly handlerOptions?: HttpHandlerBuilderOptions; + + private responseStatusCode: number = 200; + private responseHeaders: Record = {}; + private responseBody: DefaultBodyType = undefined; + + constructor( + method: HttpMethod, + path: string, + requestPredicates: ((resolver: HttpResponseResolver) => HttpResponseResolver)[], + options?: HttpHandlerBuilderOptions, + ) { + this.method = method; + this.path = path; + this.requestPredicates = requestPredicates; + this.handlerOptions = options; + } + + public statusCode(code: number): ResponseHeaderStage { + this.responseStatusCode = code; + return this; + } + + public header(name: string, value: string): ResponseHeaderStage { + this.responseHeaders[name] = value; + return this; + } + + public headers(headers: Record): ResponseHeaderStage { + this.responseHeaders = { ...this.responseHeaders, ...headers }; + return this; + } + + public jsonBody(body: unknown): BuildStage { + this.responseBody = toJson(body); + return this; + } + + public build(): HttpHandler { + const responseResolver: HttpResponseResolver = () => { + return new HttpResponse(this.responseBody, { + status: this.responseStatusCode, + headers: this.responseHeaders, + }); + }; + + const finalResolver = this.requestPredicates.reduceRight((acc, predicate) => predicate(acc), responseResolver); + + const handler = http[this.method](this.path, finalResolver, this.handlerOptions); + this.handlerOptions?.onBuild?.(handler); + return handler; + } +} + +export function mockEndpointBuilder(options?: HttpHandlerBuilderOptions): MethodStage { + return new RequestBuilder(options); +} diff --git a/tests/mock-server/randomBaseUrl.ts b/tests/mock-server/randomBaseUrl.ts new file mode 100644 index 000000000..031aa6408 --- /dev/null +++ b/tests/mock-server/randomBaseUrl.ts @@ -0,0 +1,4 @@ +export function randomBaseUrl(): string { + const randomString = Math.random().toString(36).substring(2, 15); + return `http://${randomString}.localhost`; +} diff --git a/tests/mock-server/setup.ts b/tests/mock-server/setup.ts new file mode 100644 index 000000000..c216d6074 --- /dev/null +++ b/tests/mock-server/setup.ts @@ -0,0 +1,10 @@ +import { afterAll, beforeAll } from "@jest/globals"; + +import { mockServerPool } from "./MockServerPool"; + +beforeAll(() => { + mockServerPool.listen(); +}); +afterAll(() => { + mockServerPool.close(); +}); diff --git a/tests/mock-server/withHeaders.ts b/tests/mock-server/withHeaders.ts new file mode 100644 index 000000000..e77c837d9 --- /dev/null +++ b/tests/mock-server/withHeaders.ts @@ -0,0 +1,70 @@ +import { HttpResponseResolver, passthrough } from "msw"; + +/** + * Creates a request matcher that validates if request headers match specified criteria + * @param expectedHeaders - Headers to match against + * @param resolver - Response resolver to execute if headers match + */ +export function withHeaders( + expectedHeaders: Record boolean)>, + resolver: HttpResponseResolver, +): HttpResponseResolver { + return (args) => { + const { request } = args; + const { headers } = request; + + const mismatches: Record< + string, + { actual: string | null; expected: string | RegExp | ((value: string) => boolean) } + > = {}; + + for (const [key, expectedValue] of Object.entries(expectedHeaders)) { + const actualValue = headers.get(key); + + if (actualValue === null) { + mismatches[key] = { actual: null, expected: expectedValue }; + continue; + } + + if (typeof expectedValue === "function") { + if (!expectedValue(actualValue)) { + mismatches[key] = { actual: actualValue, expected: expectedValue }; + } + } else if (expectedValue instanceof RegExp) { + if (!expectedValue.test(actualValue)) { + mismatches[key] = { actual: actualValue, expected: expectedValue }; + } + } else if (expectedValue !== actualValue) { + mismatches[key] = { actual: actualValue, expected: expectedValue }; + } + } + + if (Object.keys(mismatches).length > 0) { + const formattedMismatches = formatHeaderMismatches(mismatches); + console.error("Header mismatch:", formattedMismatches); + return passthrough(); + } + + return resolver(args); + }; +} + +function formatHeaderMismatches( + mismatches: Record boolean) }>, +): Record { + const formatted: Record = {}; + + for (const [key, { actual, expected }] of Object.entries(mismatches)) { + formatted[key] = { + actual, + expected: + expected instanceof RegExp + ? expected.toString() + : typeof expected === "function" + ? "[Function]" + : expected, + }; + } + + return formatted; +} diff --git a/tests/mock-server/withJson.ts b/tests/mock-server/withJson.ts new file mode 100644 index 000000000..44e3eb832 --- /dev/null +++ b/tests/mock-server/withJson.ts @@ -0,0 +1,152 @@ +import { HttpResponseResolver, passthrough } from "msw"; + +import { fromJson, toJson } from "../../src/core/json"; + +/** + * Creates a request matcher that validates if the request JSON body exactly matches the expected object + * @param expectedBody - The exact body object to match against + * @param resolver - Response resolver to execute if body matches + */ +export function withJson(expectedBody: unknown, resolver: HttpResponseResolver): HttpResponseResolver { + return async (args) => { + const { request } = args; + + let clonedRequest: Request; + let actualBody: unknown; + try { + clonedRequest = request.clone(); + actualBody = fromJson(await clonedRequest.text()); + } catch (error) { + console.error("Error processing request body:", error); + return passthrough(); + } + + const mismatches = findMismatches(actualBody, expectedBody); + if (Object.keys(mismatches).length > 0) { + console.error("JSON body mismatch:", toJson(mismatches, undefined, 2)); + return passthrough(); + } + + return resolver(args); + }; +} + +function findMismatches(actual: any, expected: any): Record { + const mismatches: Record = {}; + + if (typeof actual !== typeof expected) { + if (areEquivalent(actual, expected)) { + return {}; + } + return { value: { actual, expected } }; + } + + if (typeof actual !== "object" || actual === null || expected === null) { + if (actual !== expected) { + if (areEquivalent(actual, expected)) { + return {}; + } + return { value: { actual, expected } }; + } + return {}; + } + + if (Array.isArray(actual) && Array.isArray(expected)) { + if (actual.length !== expected.length) { + return { length: { actual: actual.length, expected: expected.length } }; + } + + const arrayMismatches: Record = {}; + for (let i = 0; i < actual.length; i++) { + const itemMismatches = findMismatches(actual[i], expected[i]); + if (Object.keys(itemMismatches).length > 0) { + for (const [mismatchKey, mismatchValue] of Object.entries(itemMismatches)) { + arrayMismatches[`[${i}]${mismatchKey === "value" ? "" : "." + mismatchKey}`] = mismatchValue; + } + } + } + return arrayMismatches; + } + + const actualKeys = Object.keys(actual); + const expectedKeys = Object.keys(expected); + + const allKeys = new Set([...actualKeys, ...expectedKeys]); + + for (const key of allKeys) { + if (!expectedKeys.includes(key)) { + if (actual[key] === undefined) { + continue; // Skip undefined values in actual + } + mismatches[key] = { actual: actual[key], expected: undefined }; + } else if (!actualKeys.includes(key)) { + if (expected[key] === undefined) { + continue; // Skip undefined values in expected + } + mismatches[key] = { actual: undefined, expected: expected[key] }; + } else if ( + typeof actual[key] === "object" && + actual[key] !== null && + typeof expected[key] === "object" && + expected[key] !== null + ) { + const nestedMismatches = findMismatches(actual[key], expected[key]); + if (Object.keys(nestedMismatches).length > 0) { + for (const [nestedKey, nestedValue] of Object.entries(nestedMismatches)) { + mismatches[`${key}${nestedKey === "value" ? "" : "." + nestedKey}`] = nestedValue; + } + } + } else if (actual[key] !== expected[key]) { + if (areEquivalent(actual[key], expected[key])) { + continue; + } + mismatches[key] = { actual: actual[key], expected: expected[key] }; + } + } + + return mismatches; +} + +function areEquivalent(actual: unknown, expected: unknown): boolean { + if (actual === expected) { + return true; + } + if (isEquivalentBigInt(actual, expected)) { + return true; + } + if (isEquivalentDatetime(actual, expected)) { + return true; + } + return false; +} + +function isEquivalentBigInt(actual: unknown, expected: unknown) { + if (typeof actual === "number") { + actual = BigInt(actual); + } + if (typeof expected === "number") { + expected = BigInt(expected); + } + if (typeof actual === "bigint" && typeof expected === "bigint") { + return actual === expected; + } + return false; +} + +function isEquivalentDatetime(str1: unknown, str2: unknown): boolean { + if (typeof str1 !== "string" || typeof str2 !== "string") { + return false; + } + const isoDatePattern = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{3})?Z$/; + if (!isoDatePattern.test(str1) || !isoDatePattern.test(str2)) { + return false; + } + + try { + const date1 = new Date(str1).getTime(); + const date2 = new Date(str2).getTime(); + return date1 === date2; + } catch { + return false; + } +} diff --git a/tests/tsconfig.json b/tests/tsconfig.json new file mode 100644 index 000000000..10185ed2e --- /dev/null +++ b/tests/tsconfig.json @@ -0,0 +1,10 @@ +{ + "extends": "../tsconfig.base.json", + "compilerOptions": { + "outDir": null, + "rootDir": "..", + "baseUrl": ".." + }, + "include": ["../src", "../tests"], + "exclude": [] +} diff --git a/tests/unit/base64.test.ts b/tests/unit/base64.test.ts new file mode 100644 index 000000000..939594ca2 --- /dev/null +++ b/tests/unit/base64.test.ts @@ -0,0 +1,53 @@ +import { base64Decode, base64Encode } from "../../src/core/base64"; + +describe("base64", () => { + describe("base64Encode", () => { + it("should encode ASCII strings", () => { + expect(base64Encode("hello")).toBe("aGVsbG8="); + expect(base64Encode("")).toBe(""); + }); + + it("should encode UTF-8 strings", () => { + expect(base64Encode("café")).toBe("Y2Fmw6k="); + expect(base64Encode("🎉")).toBe("8J+OiQ=="); + }); + + it("should handle basic auth credentials", () => { + expect(base64Encode("username:password")).toBe("dXNlcm5hbWU6cGFzc3dvcmQ="); + }); + }); + + describe("base64Decode", () => { + it("should decode ASCII strings", () => { + expect(base64Decode("aGVsbG8=")).toBe("hello"); + expect(base64Decode("")).toBe(""); + }); + + it("should decode UTF-8 strings", () => { + expect(base64Decode("Y2Fmw6k=")).toBe("café"); + expect(base64Decode("8J+OiQ==")).toBe("🎉"); + }); + + it("should handle basic auth credentials", () => { + expect(base64Decode("dXNlcm5hbWU6cGFzc3dvcmQ=")).toBe("username:password"); + }); + }); + + describe("round-trip encoding", () => { + const testStrings = [ + "hello world", + "test@example.com", + "café", + "username:password", + "user@domain.com:super$ecret123!", + ]; + + testStrings.forEach((testString) => { + it(`should round-trip encode/decode: "${testString}"`, () => { + const encoded = base64Encode(testString); + const decoded = base64Decode(encoded); + expect(decoded).toBe(testString); + }); + }); + }); +}); diff --git a/tests/unit/fetcher/Fetcher.test.ts b/tests/unit/fetcher/Fetcher.test.ts index a32945e94..847c018bc 100644 --- a/tests/unit/fetcher/Fetcher.test.ts +++ b/tests/unit/fetcher/Fetcher.test.ts @@ -1,7 +1,9 @@ import fs from "fs"; +import stream from "stream"; import { join } from "path"; import { Fetcher, fetcherImpl } from "../../../src/core/fetcher/Fetcher"; +import { BinaryResponse } from "../../../src/core"; describe("Test fetcherImpl", () => { it("should handle successful request", async () => { @@ -12,14 +14,15 @@ describe("Test fetcherImpl", () => { body: { data: "test" }, contentType: "application/json", requestType: "json", + responseType: "json", }; - global.fetch = jest.fn().mockResolvedValue({ - ok: true, - status: 200, - text: () => Promise.resolve(JSON.stringify({ data: "test" })), - json: () => ({ data: "test" }), - }); + global.fetch = jest.fn().mockResolvedValue( + new Response(JSON.stringify({ data: "test" }), { + status: 200, + statusText: "OK", + }), + ); const result = await fetcherImpl(mockArgs); expect(result.ok).toBe(true); @@ -45,16 +48,16 @@ describe("Test fetcherImpl", () => { headers: { "X-Test": "x-test-header" }, contentType: "application/octet-stream", requestType: "bytes", - duplex: "half", + responseType: "json", body: fs.createReadStream(join(__dirname, "test-file.txt")), }; - global.fetch = jest.fn().mockResolvedValue({ - ok: true, - status: 200, - text: () => Promise.resolve(JSON.stringify({ data: "test" })), - json: () => Promise.resolve({ data: "test" }), - }); + global.fetch = jest.fn().mockResolvedValue( + new Response(JSON.stringify({ data: "test" }), { + status: 200, + statusText: "OK", + }), + ); const result = await fetcherImpl(mockArgs); diff --git a/tests/unit/fetcher/HttpResponsePromise.test.ts b/tests/unit/fetcher/HttpResponsePromise.test.ts new file mode 100644 index 000000000..2216a33e1 --- /dev/null +++ b/tests/unit/fetcher/HttpResponsePromise.test.ts @@ -0,0 +1,143 @@ +import { beforeEach, describe, expect, it, jest } from "@jest/globals"; + +import { HttpResponsePromise } from "../../../src/core/fetcher/HttpResponsePromise"; +import { RawResponse, WithRawResponse } from "../../../src/core/fetcher/RawResponse"; + +describe("HttpResponsePromise", () => { + const mockRawResponse: RawResponse = { + headers: new Headers(), + redirected: false, + status: 200, + statusText: "OK", + type: "basic" as ResponseType, + url: "https://example.com", + }; + const mockData = { id: "123", name: "test" }; + const mockWithRawResponse: WithRawResponse = { + data: mockData, + rawResponse: mockRawResponse, + }; + + describe("fromFunction", () => { + it("should create an HttpResponsePromise from a function", async () => { + const mockFn = jest + .fn<(arg1: string, arg2: string) => Promise>>() + .mockResolvedValue(mockWithRawResponse); + + const responsePromise = HttpResponsePromise.fromFunction(mockFn, "arg1", "arg2"); + + const result = await responsePromise; + expect(result).toEqual(mockData); + expect(mockFn).toHaveBeenCalledWith("arg1", "arg2"); + + const resultWithRawResponse = await responsePromise.withRawResponse(); + expect(resultWithRawResponse).toEqual({ + data: mockData, + rawResponse: mockRawResponse, + }); + }); + }); + + describe("fromPromise", () => { + it("should create an HttpResponsePromise from a promise", async () => { + const promise = Promise.resolve(mockWithRawResponse); + + const responsePromise = HttpResponsePromise.fromPromise(promise); + + const result = await responsePromise; + expect(result).toEqual(mockData); + + const resultWithRawResponse = await responsePromise.withRawResponse(); + expect(resultWithRawResponse).toEqual({ + data: mockData, + rawResponse: mockRawResponse, + }); + }); + }); + + describe("fromExecutor", () => { + it("should create an HttpResponsePromise from an executor function", async () => { + const responsePromise = HttpResponsePromise.fromExecutor((resolve) => { + resolve(mockWithRawResponse); + }); + + const result = await responsePromise; + expect(result).toEqual(mockData); + + const resultWithRawResponse = await responsePromise.withRawResponse(); + expect(resultWithRawResponse).toEqual({ + data: mockData, + rawResponse: mockRawResponse, + }); + }); + }); + + describe("fromResult", () => { + it("should create an HttpResponsePromise from a result", async () => { + const responsePromise = HttpResponsePromise.fromResult(mockWithRawResponse); + + const result = await responsePromise; + expect(result).toEqual(mockData); + + const resultWithRawResponse = await responsePromise.withRawResponse(); + expect(resultWithRawResponse).toEqual({ + data: mockData, + rawResponse: mockRawResponse, + }); + }); + }); + + describe("Promise methods", () => { + let responsePromise: HttpResponsePromise; + + beforeEach(() => { + responsePromise = HttpResponsePromise.fromResult(mockWithRawResponse); + }); + + it("should support then() method", async () => { + const result = await responsePromise.then((data) => ({ + ...data, + modified: true, + })); + + expect(result).toEqual({ + ...mockData, + modified: true, + }); + }); + + it("should support catch() method", async () => { + const errorResponsePromise = HttpResponsePromise.fromExecutor((_, reject) => { + reject(new Error("Test error")); + }); + + const catchSpy = jest.fn(); + await errorResponsePromise.catch(catchSpy); + + expect(catchSpy).toHaveBeenCalled(); + const error = catchSpy.mock.calls[0]?.[0]; + expect(error).toBeInstanceOf(Error); + expect((error as Error).message).toBe("Test error"); + }); + + it("should support finally() method", async () => { + const finallySpy = jest.fn(); + await responsePromise.finally(finallySpy); + + expect(finallySpy).toHaveBeenCalled(); + }); + }); + + describe("withRawResponse", () => { + it("should return both data and raw response", async () => { + const responsePromise = HttpResponsePromise.fromResult(mockWithRawResponse); + + const result = await responsePromise.withRawResponse(); + + expect(result).toEqual({ + data: mockData, + rawResponse: mockRawResponse, + }); + }); + }); +}); diff --git a/tests/unit/fetcher/RawResponse.test.ts b/tests/unit/fetcher/RawResponse.test.ts new file mode 100644 index 000000000..9ccd5e1eb --- /dev/null +++ b/tests/unit/fetcher/RawResponse.test.ts @@ -0,0 +1,34 @@ +import { describe, expect, it } from "@jest/globals"; + +import { toRawResponse } from "../../../src/core/fetcher/RawResponse"; + +describe("RawResponse", () => { + describe("toRawResponse", () => { + it("should convert Response to RawResponse by removing body, bodyUsed, and ok properties", () => { + const mockHeaders = new Headers({ "content-type": "application/json" }); + const mockResponse = { + body: "test body", + bodyUsed: false, + ok: true, + headers: mockHeaders, + redirected: false, + status: 200, + statusText: "OK", + type: "basic" as ResponseType, + url: "https://example.com", + }; + + const result = toRawResponse(mockResponse as unknown as Response); + + expect("body" in result).toBe(false); + expect("bodyUsed" in result).toBe(false); + expect("ok" in result).toBe(false); + expect(result.headers).toBe(mockHeaders); + expect(result.redirected).toBe(false); + expect(result.status).toBe(200); + expect(result.statusText).toBe("OK"); + expect(result.type).toBe("basic"); + expect(result.url).toBe("https://example.com"); + }); + }); +}); diff --git a/tests/unit/fetcher/createRequestUrl.test.ts b/tests/unit/fetcher/createRequestUrl.test.ts index 486e1e614..06e03b2c6 100644 --- a/tests/unit/fetcher/createRequestUrl.test.ts +++ b/tests/unit/fetcher/createRequestUrl.test.ts @@ -48,4 +48,113 @@ describe("Test createRequestUrl", () => { const queryParams = { special: "a&b=c d" }; expect(createRequestUrl(baseUrl, queryParams)).toBe("https://api.example.com?special=a%26b%3Dc%20d"); }); + + // Additional tests for edge cases and different value types + it("should handle numeric values", () => { + const baseUrl = "https://api.example.com"; + const queryParams = { count: 42, price: 19.99, active: 1, inactive: 0 }; + expect(createRequestUrl(baseUrl, queryParams)).toBe( + "https://api.example.com?count=42&price=19.99&active=1&inactive=0", + ); + }); + + it("should handle boolean values", () => { + const baseUrl = "https://api.example.com"; + const queryParams = { enabled: true, disabled: false }; + expect(createRequestUrl(baseUrl, queryParams)).toBe("https://api.example.com?enabled=true&disabled=false"); + }); + + it("should handle null and undefined values", () => { + const baseUrl = "https://api.example.com"; + const queryParams = { + valid: "value", + nullValue: null, + undefinedValue: undefined, + emptyString: "", + }; + expect(createRequestUrl(baseUrl, queryParams)).toBe( + "https://api.example.com?valid=value&nullValue=&emptyString=", + ); + }); + + it("should handle deeply nested objects", () => { + const baseUrl = "https://api.example.com"; + const queryParams = { + user: { + profile: { + name: "John", + settings: { theme: "dark" }, + }, + }, + }; + expect(createRequestUrl(baseUrl, queryParams)).toBe( + "https://api.example.com?user%5Bprofile%5D%5Bname%5D=John&user%5Bprofile%5D%5Bsettings%5D%5Btheme%5D=dark", + ); + }); + + it("should handle arrays of objects", () => { + const baseUrl = "https://api.example.com"; + const queryParams = { + users: [ + { name: "John", age: 30 }, + { name: "Jane", age: 25 }, + ], + }; + expect(createRequestUrl(baseUrl, queryParams)).toBe( + "https://api.example.com?users%5Bname%5D=John&users%5Bage%5D=30&users%5Bname%5D=Jane&users%5Bage%5D=25", + ); + }); + + it("should handle mixed arrays", () => { + const baseUrl = "https://api.example.com"; + const queryParams = { + mixed: ["string", 42, true, { key: "value" }], + }; + expect(createRequestUrl(baseUrl, queryParams)).toBe( + "https://api.example.com?mixed=string&mixed=42&mixed=true&mixed%5Bkey%5D=value", + ); + }); + + it("should handle empty arrays", () => { + const baseUrl = "https://api.example.com"; + const queryParams = { emptyArray: [] }; + expect(createRequestUrl(baseUrl, queryParams)).toBe(baseUrl); + }); + + it("should handle empty objects", () => { + const baseUrl = "https://api.example.com"; + const queryParams = { emptyObject: {} }; + expect(createRequestUrl(baseUrl, queryParams)).toBe(baseUrl); + }); + + it("should handle special characters in keys", () => { + const baseUrl = "https://api.example.com"; + const queryParams = { "key with spaces": "value", "key[with]brackets": "value" }; + expect(createRequestUrl(baseUrl, queryParams)).toBe( + "https://api.example.com?key%20with%20spaces=value&key%5Bwith%5Dbrackets=value", + ); + }); + + it("should handle URL with existing query parameters", () => { + const baseUrl = "https://api.example.com?existing=param"; + const queryParams = { new: "value" }; + expect(createRequestUrl(baseUrl, queryParams)).toBe("https://api.example.com?existing=param?new=value"); + }); + + it("should handle complex nested structures", () => { + const baseUrl = "https://api.example.com"; + const queryParams = { + filters: { + status: ["active", "pending"], + category: { + type: "electronics", + subcategories: ["phones", "laptops"], + }, + }, + sort: { field: "name", direction: "asc" }, + }; + expect(createRequestUrl(baseUrl, queryParams)).toBe( + "https://api.example.com?filters%5Bstatus%5D=active&filters%5Bstatus%5D=pending&filters%5Bcategory%5D%5Btype%5D=electronics&filters%5Bcategory%5D%5Bsubcategories%5D=phones&filters%5Bcategory%5D%5Bsubcategories%5D=laptops&sort%5Bfield%5D=name&sort%5Bdirection%5D=asc", + ); + }); }); diff --git a/tests/unit/fetcher/getFetchFn.test.ts b/tests/unit/fetcher/getFetchFn.test.ts index 9b315ad09..b55dbbc35 100644 --- a/tests/unit/fetcher/getFetchFn.test.ts +++ b/tests/unit/fetcher/getFetchFn.test.ts @@ -1,5 +1,5 @@ -import { RUNTIME } from "../../../src/core/runtime"; import { getFetchFn } from "../../../src/core/fetcher/getFetchFn"; +import { RUNTIME } from "../../../src/core/runtime"; describe("Test for getFetchFn", () => { it("should get node-fetch function", async () => { diff --git a/tests/unit/fetcher/getRequestBody.test.ts b/tests/unit/fetcher/getRequestBody.test.ts index 919604c2e..e864c8b57 100644 --- a/tests/unit/fetcher/getRequestBody.test.ts +++ b/tests/unit/fetcher/getRequestBody.test.ts @@ -1,19 +1,7 @@ -import { RUNTIME } from "../../../src/core/runtime"; import { getRequestBody } from "../../../src/core/fetcher/getRequestBody"; +import { RUNTIME } from "../../../src/core/runtime"; describe("Test getRequestBody", () => { - it("should return FormData as is in Node environment", async () => { - if (RUNTIME.type === "node") { - const formData = new (await import("formdata-node")).FormData(); - formData.append("key", "value"); - const result = await getRequestBody({ - body: formData, - type: "file", - }); - expect(result).toBe(formData); - } - }); - it("should stringify body if not FormData in Node environment", async () => { if (RUNTIME.type === "node") { const body = { key: "value" }; @@ -27,7 +15,7 @@ describe("Test getRequestBody", () => { it("should return FormData in browser environment", async () => { if (RUNTIME.type === "browser") { - const formData = new (await import("form-data")).default(); + const formData = new FormData(); formData.append("key", "value"); const result = await getRequestBody({ body: formData, diff --git a/tests/unit/fetcher/getResponseBody.test.ts b/tests/unit/fetcher/getResponseBody.test.ts index 1030c517c..17ef223c1 100644 --- a/tests/unit/fetcher/getResponseBody.test.ts +++ b/tests/unit/fetcher/getResponseBody.test.ts @@ -1,5 +1,6 @@ import { RUNTIME } from "../../../src/core/runtime"; import { getResponseBody } from "../../../src/core/fetcher/getResponseBody"; + import { chooseStreamWrapper } from "../../../src/core/fetcher/stream-wrappers/chooseStreamWrapper"; describe("Test getResponseBody", () => { diff --git a/tests/unit/fetcher/stream-wrappers/Node18UniversalStreamWrapper.test.ts b/tests/unit/fetcher/stream-wrappers/Node18UniversalStreamWrapper.test.ts index 1dc9be0cc..172c1c26b 100644 --- a/tests/unit/fetcher/stream-wrappers/Node18UniversalStreamWrapper.test.ts +++ b/tests/unit/fetcher/stream-wrappers/Node18UniversalStreamWrapper.test.ts @@ -159,7 +159,7 @@ describe("Node18UniversalStreamWrapper", () => { expect(data).toEqual({ test: "test" }); }); - it("should allow use with async iteratable stream", async () => { + it("should allow use with async iterable stream", async () => { const rawStream = new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode("test")); diff --git a/tests/unit/fetcher/stream-wrappers/NodePre18StreamWrapper.test.ts b/tests/unit/fetcher/stream-wrappers/NodePre18StreamWrapper.test.ts index 0c99d3b26..19c26668e 100644 --- a/tests/unit/fetcher/stream-wrappers/NodePre18StreamWrapper.test.ts +++ b/tests/unit/fetcher/stream-wrappers/NodePre18StreamWrapper.test.ts @@ -111,7 +111,7 @@ describe("NodePre18StreamWrapper", () => { expect(data).toEqual({ test: "test" }); }); - it("should allow use with async iteratable stream", async () => { + it("should allow use with async iterable stream", async () => { const rawStream = (await import("readable-stream")).Readable.from(["test", "test"]); let data = ""; const stream = new NodePre18StreamWrapper(rawStream); diff --git a/tests/unit/fetcher/stream-wrappers/UndiciStreamWrapper.test.ts b/tests/unit/fetcher/stream-wrappers/UndiciStreamWrapper.test.ts index 1d171ce6c..0ea148350 100644 --- a/tests/unit/fetcher/stream-wrappers/UndiciStreamWrapper.test.ts +++ b/tests/unit/fetcher/stream-wrappers/UndiciStreamWrapper.test.ts @@ -134,7 +134,7 @@ describe("UndiciStreamWrapper", () => { expect(data).toEqual({ test: "test" }); }); - it("should allow use with async iteratable stream", async () => { + it("should allow use with async iterable stream", async () => { const rawStream = new ReadableStream({ start(controller) { controller.enqueue(new TextEncoder().encode("test")); diff --git a/tests/unit/fetcher/stream-wrappers/chooseStreamWrapper.test.ts b/tests/unit/fetcher/stream-wrappers/chooseStreamWrapper.test.ts index 8004e9abb..5752c8af5 100644 --- a/tests/unit/fetcher/stream-wrappers/chooseStreamWrapper.test.ts +++ b/tests/unit/fetcher/stream-wrappers/chooseStreamWrapper.test.ts @@ -1,8 +1,8 @@ -import { RUNTIME } from "../../../../src/core/runtime"; import { Node18UniversalStreamWrapper } from "../../../../src/core/fetcher/stream-wrappers/Node18UniversalStreamWrapper"; import { NodePre18StreamWrapper } from "../../../../src/core/fetcher/stream-wrappers/NodePre18StreamWrapper"; import { UndiciStreamWrapper } from "../../../../src/core/fetcher/stream-wrappers/UndiciStreamWrapper"; import { chooseStreamWrapper } from "../../../../src/core/fetcher/stream-wrappers/chooseStreamWrapper"; +import { RUNTIME } from "../../../../src/core/runtime"; describe("chooseStreamWrapper", () => { beforeEach(() => { diff --git a/tests/unit/form-data-utils/encodeAsFormParameter.test.ts b/tests/unit/form-data-utils/encodeAsFormParameter.test.ts new file mode 100644 index 000000000..d4b0c4503 --- /dev/null +++ b/tests/unit/form-data-utils/encodeAsFormParameter.test.ts @@ -0,0 +1,344 @@ +import { encodeAsFormParameter } from "../../../src/core/form-data-utils/encodeAsFormParameter"; + +describe("encodeAsFormParameter", () => { + describe("Basic functionality", () => { + it("should return empty object for null/undefined", () => { + expect(encodeAsFormParameter(null)).toEqual({}); + expect(encodeAsFormParameter(undefined)).toEqual({}); + }); + + it("should return empty object for primitive values", () => { + expect(encodeAsFormParameter("hello")).toEqual({}); + expect(encodeAsFormParameter(42)).toEqual({}); + expect(encodeAsFormParameter(true)).toEqual({}); + }); + + it("should handle simple key-value pairs", () => { + const obj = { name: "John", age: 30 }; + expect(encodeAsFormParameter(obj)).toEqual({ + name: "John", + age: "30", + }); + }); + + it("should handle empty objects", () => { + expect(encodeAsFormParameter({})).toEqual({}); + }); + }); + + describe("Array handling", () => { + it("should handle arrays with indices format (default)", () => { + const obj = { items: ["a", "b", "c"] }; + expect(encodeAsFormParameter(obj)).toEqual({ + "items[0]": "a", + "items[1]": "b", + "items[2]": "c", + }); + }); + + it("should handle empty arrays", () => { + const obj = { items: [] }; + expect(encodeAsFormParameter(obj)).toEqual({}); + }); + + it("should handle arrays with mixed types", () => { + const obj = { mixed: ["string", 42, true, false] }; + expect(encodeAsFormParameter(obj)).toEqual({ + "mixed[0]": "string", + "mixed[1]": "42", + "mixed[2]": "true", + "mixed[3]": "false", + }); + }); + + it("should handle arrays with objects", () => { + const obj = { users: [{ name: "John" }, { name: "Jane" }] }; + expect(encodeAsFormParameter(obj)).toEqual({ + "users[0][name]": "John", + "users[1][name]": "Jane", + }); + }); + + it("should handle arrays with null/undefined values", () => { + const obj = { items: ["a", null, "c", undefined, "e"] }; + expect(encodeAsFormParameter(obj)).toEqual({ + "items[0]": "a", + "items[1]": "", + "items[2]": "c", + "items[4]": "e", + }); + }); + }); + + describe("Nested objects", () => { + it("should handle nested objects", () => { + const obj = { user: { name: "John", age: 30 } }; + expect(encodeAsFormParameter(obj)).toEqual({ + "user[name]": "John", + "user[age]": "30", + }); + }); + + it("should handle deeply nested objects", () => { + const obj = { user: { profile: { name: "John", settings: { theme: "dark" } } } }; + expect(encodeAsFormParameter(obj)).toEqual({ + "user[profile][name]": "John", + "user[profile][settings][theme]": "dark", + }); + }); + + it("should handle empty nested objects", () => { + const obj = { user: {} }; + expect(encodeAsFormParameter(obj)).toEqual({}); + }); + }); + + describe("Special characters and encoding", () => { + it("should not encode values (encode: false is used)", () => { + const obj = { name: "John Doe", email: "john@example.com" }; + expect(encodeAsFormParameter(obj)).toEqual({ + name: "John Doe", + email: "john@example.com", + }); + }); + + it("should not encode special characters in keys", () => { + const obj = { "user name": "John", "email[primary]": "john@example.com" }; + expect(encodeAsFormParameter(obj)).toEqual({ + "user name": "John", + "email[primary]": "john@example.com", + }); + }); + + it("should handle values that contain special characters", () => { + const obj = { + query: "search term with spaces", + filter: "category:electronics", + }; + expect(encodeAsFormParameter(obj)).toEqual({ + query: "search term with spaces", + filter: "category:electronics", + }); + }); + + it("should handle ampersand and equals characters (edge case)", () => { + // Note: Values containing & and = may be problematic because + // encodeAsFormParameter splits on these characters when parsing the stringified result + const obj = { + message: "Hello & welcome", + equation: "x = y + z", + }; + // This demonstrates the limitation - ampersands and equals signs in values + // will cause the parameter to be split incorrectly + const result = encodeAsFormParameter(obj); + + // We expect this to be parsed incorrectly due to the implementation + expect(result.message).toBe("Hello "); + expect(result[" welcome"]).toBeUndefined(); + expect(result.equation).toBe("x "); + expect(result[" y + z"]).toBeUndefined(); + }); + }); + + describe("Form data specific scenarios", () => { + it("should handle file upload metadata", () => { + const metadata = { + file: { + name: "document.pdf", + size: 1024, + type: "application/pdf", + }, + options: { + compress: true, + quality: 0.8, + }, + }; + expect(encodeAsFormParameter(metadata)).toEqual({ + "file[name]": "document.pdf", + "file[size]": "1024", + "file[type]": "application/pdf", + "options[compress]": "true", + "options[quality]": "0.8", + }); + }); + + it("should handle form validation data", () => { + const formData = { + fields: ["name", "email", "phone"], + validation: { + required: ["name", "email"], + patterns: { + email: "^[^@]+@[^@]+\\.[^@]+$", + phone: "^\\+?[1-9]\\d{1,14}$", + }, + }, + }; + expect(encodeAsFormParameter(formData)).toEqual({ + "fields[0]": "name", + "fields[1]": "email", + "fields[2]": "phone", + "validation[required][0]": "name", + "validation[required][1]": "email", + "validation[patterns][email]": "^[^@]+@[^@]+\\.[^@]+$", + "validation[patterns][phone]": "^\\+?[1-9]\\d{1,14}$", + }); + }); + + it("should handle search/filter parameters", () => { + const searchParams = { + filters: { + status: ["active", "pending"], + category: { + type: "electronics", + subcategories: ["phones", "laptops"], + }, + }, + sort: { field: "name", direction: "asc" }, + pagination: { page: 1, limit: 20 }, + }; + expect(encodeAsFormParameter(searchParams)).toEqual({ + "filters[status][0]": "active", + "filters[status][1]": "pending", + "filters[category][type]": "electronics", + "filters[category][subcategories][0]": "phones", + "filters[category][subcategories][1]": "laptops", + "sort[field]": "name", + "sort[direction]": "asc", + "pagination[page]": "1", + "pagination[limit]": "20", + }); + }); + }); + + describe("Edge cases", () => { + it("should handle boolean values", () => { + const obj = { enabled: true, disabled: false }; + expect(encodeAsFormParameter(obj)).toEqual({ + enabled: "true", + disabled: "false", + }); + }); + + it("should handle empty strings", () => { + const obj = { name: "", description: "test" }; + expect(encodeAsFormParameter(obj)).toEqual({ + name: "", + description: "test", + }); + }); + + it("should handle zero values", () => { + const obj = { count: 0, price: 0.0 }; + expect(encodeAsFormParameter(obj)).toEqual({ + count: "0", + price: "0", + }); + }); + + it("should handle numeric keys", () => { + const obj = { "0": "zero", "1": "one" }; + expect(encodeAsFormParameter(obj)).toEqual({ + "0": "zero", + "1": "one", + }); + }); + + it("should handle objects with null/undefined values", () => { + const obj = { name: "John", age: null, email: undefined, active: true }; + expect(encodeAsFormParameter(obj)).toEqual({ + name: "John", + age: "", + active: "true", + }); + }); + }); + + describe("Integration with form submission", () => { + it("should produce form-compatible key-value pairs", () => { + const formObject = { + username: "john_doe", + preferences: { + theme: "dark", + notifications: ["email", "push"], + settings: { + autoSave: true, + timeout: 300, + }, + }, + }; + + const result = encodeAsFormParameter(formObject); + + // Verify all values are strings (as required for form data) + Object.values(result).forEach((value) => { + expect(typeof value).toBe("string"); + }); + + // Verify the structure can be reconstructed + expect(result).toEqual({ + username: "john_doe", + "preferences[theme]": "dark", + "preferences[notifications][0]": "email", + "preferences[notifications][1]": "push", + "preferences[settings][autoSave]": "true", + "preferences[settings][timeout]": "300", + }); + }); + + it("should handle complex nested arrays for API parameters", () => { + const apiParams = { + query: { + filters: [ + { field: "status", operator: "eq", value: "active" }, + { field: "created", operator: "gte", value: "2023-01-01" }, + ], + sort: [ + { field: "name", direction: "asc" }, + { field: "created", direction: "desc" }, + ], + }, + }; + + const result = encodeAsFormParameter(apiParams); + expect(result).toEqual({ + "query[filters][0][field]": "status", + "query[filters][0][operator]": "eq", + "query[filters][0][value]": "active", + "query[filters][1][field]": "created", + "query[filters][1][operator]": "gte", + "query[filters][1][value]": "2023-01-01", + "query[sort][0][field]": "name", + "query[sort][0][direction]": "asc", + "query[sort][1][field]": "created", + "query[sort][1][direction]": "desc", + }); + }); + }); + + describe("Error cases and malformed input", () => { + it("should handle circular references gracefully", () => { + const obj: any = { name: "test" }; + obj.self = obj; + + // This will throw a RangeError due to stack overflow - this is expected behavior + expect(() => encodeAsFormParameter(obj)).toThrow("Maximum call stack size exceeded"); + }); + + it("should handle very deeply nested objects", () => { + let deepObj: any = { value: "deep" }; + for (let i = 0; i < 100; i++) { + deepObj = { level: deepObj }; + } + + expect(() => encodeAsFormParameter(deepObj)).not.toThrow(); + const result = encodeAsFormParameter(deepObj); + expect(Object.keys(result).length).toBeGreaterThan(0); + }); + + it("should handle empty string splitting edge case", () => { + // Test what happens when qs returns an empty string + const result = encodeAsFormParameter({}); + expect(result).toEqual({}); + }); + }); +}); diff --git a/tests/unit/form-data-utils/formDataWrapper.test.ts b/tests/unit/form-data-utils/formDataWrapper.test.ts index 61fd5bfc1..095a1055b 100644 --- a/tests/unit/form-data-utils/formDataWrapper.test.ts +++ b/tests/unit/form-data-utils/formDataWrapper.test.ts @@ -11,7 +11,7 @@ describe("CrossPlatformFormData", () => { }); it("should append a Readable stream with a specified filename", async () => { - const value = (await import("readable-stream")).Readable.from(["file content"]); + const value = (await import("stream")).Readable.from(["file content"]); const filename = "testfile.txt"; await formData.appendFile("file", value, filename); @@ -69,6 +69,22 @@ describe("CrossPlatformFormData", () => { } expect(data).toContain("test.txt"); }); + + it("should append stream with path", async () => { + const expectedFileName = "testfile.txt"; + const filePath = "/test/testfile.txt"; + const stream = (await import("stream")).Readable.from(["file content"]); + (stream as any).path = filePath; + await formData.appendFile("file", stream); + + const request = await formData.getRequest(); + const decoder = new TextDecoder("utf-8"); + let data = ""; + for await (const chunk of request.body) { + data += decoder.decode(chunk); + } + expect(data).toContain('Content-Disposition: form-data; name="file"; filename="' + expectedFileName + '"'); + }); }); describe("WebFormData", () => { @@ -80,7 +96,7 @@ describe("CrossPlatformFormData", () => { }); it("should append a Readable stream with a specified filename", async () => { - const value = (await import("readable-stream")).Readable.from(["file content"]); + const value = (await import("stream")).Readable.from(["file content"]); const filename = "testfile.txt"; await formData.appendFile("file", value, filename); diff --git a/tests/unit/zurg/bigint/bigint.test.ts b/tests/unit/schemas/bigint/bigint.test.ts similarity index 100% rename from tests/unit/zurg/bigint/bigint.test.ts rename to tests/unit/schemas/bigint/bigint.test.ts diff --git a/tests/unit/zurg/date/date.test.ts b/tests/unit/schemas/date/date.test.ts similarity index 100% rename from tests/unit/zurg/date/date.test.ts rename to tests/unit/schemas/date/date.test.ts diff --git a/tests/unit/zurg/enum/enum.test.ts b/tests/unit/schemas/enum/enum.test.ts similarity index 100% rename from tests/unit/zurg/enum/enum.test.ts rename to tests/unit/schemas/enum/enum.test.ts diff --git a/tests/unit/zurg/lazy/lazy.test.ts b/tests/unit/schemas/lazy/lazy.test.ts similarity index 100% rename from tests/unit/zurg/lazy/lazy.test.ts rename to tests/unit/schemas/lazy/lazy.test.ts diff --git a/tests/unit/zurg/lazy/lazyObject.test.ts b/tests/unit/schemas/lazy/lazyObject.test.ts similarity index 100% rename from tests/unit/zurg/lazy/lazyObject.test.ts rename to tests/unit/schemas/lazy/lazyObject.test.ts diff --git a/tests/unit/zurg/lazy/recursive/a.ts b/tests/unit/schemas/lazy/recursive/a.ts similarity index 100% rename from tests/unit/zurg/lazy/recursive/a.ts rename to tests/unit/schemas/lazy/recursive/a.ts diff --git a/tests/unit/zurg/lazy/recursive/b.ts b/tests/unit/schemas/lazy/recursive/b.ts similarity index 100% rename from tests/unit/zurg/lazy/recursive/b.ts rename to tests/unit/schemas/lazy/recursive/b.ts diff --git a/tests/unit/zurg/list/list.test.ts b/tests/unit/schemas/list/list.test.ts similarity index 100% rename from tests/unit/zurg/list/list.test.ts rename to tests/unit/schemas/list/list.test.ts diff --git a/tests/unit/zurg/literals/stringLiteral.test.ts b/tests/unit/schemas/literals/stringLiteral.test.ts similarity index 100% rename from tests/unit/zurg/literals/stringLiteral.test.ts rename to tests/unit/schemas/literals/stringLiteral.test.ts diff --git a/tests/unit/zurg/object-like/withParsedProperties.test.ts b/tests/unit/schemas/object-like/withParsedProperties.test.ts similarity index 100% rename from tests/unit/zurg/object-like/withParsedProperties.test.ts rename to tests/unit/schemas/object-like/withParsedProperties.test.ts diff --git a/tests/unit/zurg/object/extend.test.ts b/tests/unit/schemas/object/extend.test.ts similarity index 100% rename from tests/unit/zurg/object/extend.test.ts rename to tests/unit/schemas/object/extend.test.ts diff --git a/tests/unit/zurg/object/object.test.ts b/tests/unit/schemas/object/object.test.ts similarity index 100% rename from tests/unit/zurg/object/object.test.ts rename to tests/unit/schemas/object/object.test.ts diff --git a/tests/unit/zurg/object/objectWithoutOptionalProperties.test.ts b/tests/unit/schemas/object/objectWithoutOptionalProperties.test.ts similarity index 100% rename from tests/unit/zurg/object/objectWithoutOptionalProperties.test.ts rename to tests/unit/schemas/object/objectWithoutOptionalProperties.test.ts diff --git a/tests/unit/zurg/object/passthrough.test.ts b/tests/unit/schemas/object/passthrough.test.ts similarity index 100% rename from tests/unit/zurg/object/passthrough.test.ts rename to tests/unit/schemas/object/passthrough.test.ts diff --git a/tests/unit/zurg/primitives/any.test.ts b/tests/unit/schemas/primitives/any.test.ts similarity index 100% rename from tests/unit/zurg/primitives/any.test.ts rename to tests/unit/schemas/primitives/any.test.ts diff --git a/tests/unit/zurg/primitives/boolean.test.ts b/tests/unit/schemas/primitives/boolean.test.ts similarity index 100% rename from tests/unit/zurg/primitives/boolean.test.ts rename to tests/unit/schemas/primitives/boolean.test.ts diff --git a/tests/unit/zurg/primitives/number.test.ts b/tests/unit/schemas/primitives/number.test.ts similarity index 100% rename from tests/unit/zurg/primitives/number.test.ts rename to tests/unit/schemas/primitives/number.test.ts diff --git a/tests/unit/zurg/primitives/string.test.ts b/tests/unit/schemas/primitives/string.test.ts similarity index 100% rename from tests/unit/zurg/primitives/string.test.ts rename to tests/unit/schemas/primitives/string.test.ts diff --git a/tests/unit/zurg/primitives/unknown.test.ts b/tests/unit/schemas/primitives/unknown.test.ts similarity index 100% rename from tests/unit/zurg/primitives/unknown.test.ts rename to tests/unit/schemas/primitives/unknown.test.ts diff --git a/tests/unit/zurg/record/record.test.ts b/tests/unit/schemas/record/record.test.ts similarity index 100% rename from tests/unit/zurg/record/record.test.ts rename to tests/unit/schemas/record/record.test.ts diff --git a/tests/unit/zurg/schema-utils/getSchemaUtils.test.ts b/tests/unit/schemas/schema-utils/getSchemaUtils.test.ts similarity index 97% rename from tests/unit/zurg/schema-utils/getSchemaUtils.test.ts rename to tests/unit/schemas/schema-utils/getSchemaUtils.test.ts index 2cd9b1251..09d594d07 100644 --- a/tests/unit/zurg/schema-utils/getSchemaUtils.test.ts +++ b/tests/unit/schemas/schema-utils/getSchemaUtils.test.ts @@ -16,7 +16,7 @@ describe("getSchemaUtils", () => { describe("transform()", () => { itSchema( - "transorm and untransform run correctly", + "transform and untransform run correctly", string().transform({ transform: (x) => x + "X", untransform: (x) => (x as string).slice(0, -1), diff --git a/tests/unit/zurg/schema.test.ts b/tests/unit/schemas/schema.test.ts similarity index 100% rename from tests/unit/zurg/schema.test.ts rename to tests/unit/schemas/schema.test.ts diff --git a/tests/unit/zurg/set/set.test.ts b/tests/unit/schemas/set/set.test.ts similarity index 100% rename from tests/unit/zurg/set/set.test.ts rename to tests/unit/schemas/set/set.test.ts diff --git a/tests/unit/zurg/skipValidation.test.ts b/tests/unit/schemas/skipValidation.test.ts similarity index 100% rename from tests/unit/zurg/skipValidation.test.ts rename to tests/unit/schemas/skipValidation.test.ts diff --git a/tests/unit/zurg/undiscriminated-union/undiscriminatedUnion.test.ts b/tests/unit/schemas/undiscriminated-union/undiscriminatedUnion.test.ts similarity index 100% rename from tests/unit/zurg/undiscriminated-union/undiscriminatedUnion.test.ts rename to tests/unit/schemas/undiscriminated-union/undiscriminatedUnion.test.ts diff --git a/tests/unit/zurg/union/union.test.ts b/tests/unit/schemas/union/union.test.ts similarity index 100% rename from tests/unit/zurg/union/union.test.ts rename to tests/unit/schemas/union/union.test.ts diff --git a/tests/unit/zurg/utils/itSchema.ts b/tests/unit/schemas/utils/itSchema.ts similarity index 100% rename from tests/unit/zurg/utils/itSchema.ts rename to tests/unit/schemas/utils/itSchema.ts diff --git a/tests/unit/zurg/utils/itValidate.ts b/tests/unit/schemas/utils/itValidate.ts similarity index 100% rename from tests/unit/zurg/utils/itValidate.ts rename to tests/unit/schemas/utils/itValidate.ts diff --git a/tests/unit/url/join.test.ts b/tests/unit/url/join.test.ts new file mode 100644 index 000000000..394628995 --- /dev/null +++ b/tests/unit/url/join.test.ts @@ -0,0 +1,101 @@ +import { join } from "../../../src/core/url/index"; + +describe("join", () => { + describe("basic functionality", () => { + it("should return empty string for empty base", () => { + expect(join("")).toBe(""); + expect(join("", "path")).toBe(""); + }); + + it("should handle single segment", () => { + expect(join("base", "segment")).toBe("base/segment"); + expect(join("base/", "segment")).toBe("base/segment"); + expect(join("base", "/segment")).toBe("base/segment"); + expect(join("base/", "/segment")).toBe("base/segment"); + }); + + it("should handle multiple segments", () => { + expect(join("base", "path1", "path2", "path3")).toBe("base/path1/path2/path3"); + expect(join("base/", "/path1/", "/path2/", "/path3/")).toBe("base/path1/path2/path3"); + }); + }); + + describe("URL handling", () => { + it("should handle absolute URLs", () => { + expect(join("https://example.com", "api", "v1")).toBe("https://example.com/api/v1"); + expect(join("https://example.com/", "/api/", "/v1/")).toBe("https://example.com/api/v1"); + expect(join("https://example.com/base", "api", "v1")).toBe("https://example.com/base/api/v1"); + }); + + it("should preserve URL query parameters and fragments", () => { + expect(join("https://example.com?query=1", "api")).toBe("https://example.com/api?query=1"); + expect(join("https://example.com#fragment", "api")).toBe("https://example.com/api#fragment"); + expect(join("https://example.com?query=1#fragment", "api")).toBe( + "https://example.com/api?query=1#fragment", + ); + }); + + it("should handle different protocols", () => { + expect(join("http://example.com", "api")).toBe("http://example.com/api"); + expect(join("ftp://example.com", "files")).toBe("ftp://example.com/files"); + expect(join("ws://example.com", "socket")).toBe("ws://example.com/socket"); + }); + + it("should fallback to path joining for malformed URLs", () => { + expect(join("not-a-url://", "path")).toBe("not-a-url:///path"); + }); + }); + + describe("edge cases", () => { + it("should handle empty segments", () => { + expect(join("base", "", "path")).toBe("base/path"); + expect(join("base", null as any, "path")).toBe("base/path"); + expect(join("base", undefined as any, "path")).toBe("base/path"); + }); + + it("should handle segments with only slashes", () => { + expect(join("base", "/", "path")).toBe("base/path"); + expect(join("base", "//", "path")).toBe("base/path"); + }); + + it("should handle base paths with trailing slashes", () => { + expect(join("base/", "path")).toBe("base/path"); + }); + + it("should handle complex nested paths", () => { + expect(join("api/v1/", "/users/", "/123/", "/profile")).toBe("api/v1/users/123/profile"); + }); + }); + + describe("real-world scenarios", () => { + it("should handle API endpoint construction", () => { + const baseUrl = "https://api.example.com/v1"; + expect(join(baseUrl, "users", "123", "posts")).toBe("https://api.example.com/v1/users/123/posts"); + }); + + it("should handle file path construction", () => { + expect(join("/var/www", "html", "assets", "images")).toBe("/var/www/html/assets/images"); + }); + + it("should handle relative path construction", () => { + expect(join("../parent", "child", "grandchild")).toBe("../parent/child/grandchild"); + }); + + it("should handle Windows-style paths", () => { + expect(join("C:\\Users", "Documents", "file.txt")).toBe("C:\\Users/Documents/file.txt"); + }); + }); + + describe("performance scenarios", () => { + it("should handle many segments efficiently", () => { + const segments = Array(100).fill("segment"); + const result = join("base", ...segments); + expect(result).toBe("base/" + segments.join("/")); + }); + + it("should handle long URLs", () => { + const longPath = "a".repeat(1000); + expect(join("https://example.com", longPath)).toBe(`https://example.com/${longPath}`); + }); + }); +}); diff --git a/tests/unit/url/qs.test.ts b/tests/unit/url/qs.test.ts new file mode 100644 index 000000000..80e7e0444 --- /dev/null +++ b/tests/unit/url/qs.test.ts @@ -0,0 +1,187 @@ +import { toQueryString } from "../../../src/core/url/index"; + +describe("Test qs toQueryString", () => { + describe("Basic functionality", () => { + it("should return empty string for null/undefined", () => { + expect(toQueryString(null)).toBe(""); + expect(toQueryString(undefined)).toBe(""); + }); + + it("should return empty string for primitive values", () => { + expect(toQueryString("hello")).toBe(""); + expect(toQueryString(42)).toBe(""); + expect(toQueryString(true)).toBe(""); + expect(toQueryString(false)).toBe(""); + }); + + it("should handle empty objects", () => { + expect(toQueryString({})).toBe(""); + }); + + it("should handle simple key-value pairs", () => { + const obj = { name: "John", age: 30 }; + expect(toQueryString(obj)).toBe("name=John&age=30"); + }); + }); + + describe("Array handling", () => { + it("should handle arrays with indices format (default)", () => { + const obj = { items: ["a", "b", "c"] }; + expect(toQueryString(obj)).toBe("items%5B0%5D=a&items%5B1%5D=b&items%5B2%5D=c"); + }); + + it("should handle arrays with repeat format", () => { + const obj = { items: ["a", "b", "c"] }; + expect(toQueryString(obj, { arrayFormat: "repeat" })).toBe("items=a&items=b&items=c"); + }); + + it("should handle empty arrays", () => { + const obj = { items: [] }; + expect(toQueryString(obj)).toBe(""); + }); + + it("should handle arrays with mixed types", () => { + const obj = { mixed: ["string", 42, true, false] }; + expect(toQueryString(obj)).toBe("mixed%5B0%5D=string&mixed%5B1%5D=42&mixed%5B2%5D=true&mixed%5B3%5D=false"); + }); + + it("should handle arrays with objects", () => { + const obj = { users: [{ name: "John" }, { name: "Jane" }] }; + expect(toQueryString(obj)).toBe("users%5B0%5D%5Bname%5D=John&users%5B1%5D%5Bname%5D=Jane"); + }); + + it("should handle arrays with objects in repeat format", () => { + const obj = { users: [{ name: "John" }, { name: "Jane" }] }; + expect(toQueryString(obj, { arrayFormat: "repeat" })).toBe("users%5Bname%5D=John&users%5Bname%5D=Jane"); + }); + }); + + describe("Nested objects", () => { + it("should handle nested objects", () => { + const obj = { user: { name: "John", age: 30 } }; + expect(toQueryString(obj)).toBe("user%5Bname%5D=John&user%5Bage%5D=30"); + }); + + it("should handle deeply nested objects", () => { + const obj = { user: { profile: { name: "John", settings: { theme: "dark" } } } }; + expect(toQueryString(obj)).toBe( + "user%5Bprofile%5D%5Bname%5D=John&user%5Bprofile%5D%5Bsettings%5D%5Btheme%5D=dark", + ); + }); + + it("should handle empty nested objects", () => { + const obj = { user: {} }; + expect(toQueryString(obj)).toBe(""); + }); + }); + + describe("Encoding", () => { + it("should encode by default", () => { + const obj = { name: "John Doe", email: "john@example.com" }; + expect(toQueryString(obj)).toBe("name=John%20Doe&email=john%40example.com"); + }); + + it("should not encode when encode is false", () => { + const obj = { name: "John Doe", email: "john@example.com" }; + expect(toQueryString(obj, { encode: false })).toBe("name=John Doe&email=john@example.com"); + }); + + it("should encode special characters in keys", () => { + const obj = { "user name": "John", "email[primary]": "john@example.com" }; + expect(toQueryString(obj)).toBe("user%20name=John&email%5Bprimary%5D=john%40example.com"); + }); + + it("should not encode special characters in keys when encode is false", () => { + const obj = { "user name": "John", "email[primary]": "john@example.com" }; + expect(toQueryString(obj, { encode: false })).toBe("user name=John&email[primary]=john@example.com"); + }); + }); + + describe("Mixed scenarios", () => { + it("should handle complex nested structures", () => { + const obj = { + filters: { + status: ["active", "pending"], + category: { + type: "electronics", + subcategories: ["phones", "laptops"], + }, + }, + sort: { field: "name", direction: "asc" }, + }; + expect(toQueryString(obj)).toBe( + "filters%5Bstatus%5D%5B0%5D=active&filters%5Bstatus%5D%5B1%5D=pending&filters%5Bcategory%5D%5Btype%5D=electronics&filters%5Bcategory%5D%5Bsubcategories%5D%5B0%5D=phones&filters%5Bcategory%5D%5Bsubcategories%5D%5B1%5D=laptops&sort%5Bfield%5D=name&sort%5Bdirection%5D=asc", + ); + }); + + it("should handle complex nested structures with repeat format", () => { + const obj = { + filters: { + status: ["active", "pending"], + category: { + type: "electronics", + subcategories: ["phones", "laptops"], + }, + }, + sort: { field: "name", direction: "asc" }, + }; + expect(toQueryString(obj, { arrayFormat: "repeat" })).toBe( + "filters%5Bstatus%5D=active&filters%5Bstatus%5D=pending&filters%5Bcategory%5D%5Btype%5D=electronics&filters%5Bcategory%5D%5Bsubcategories%5D=phones&filters%5Bcategory%5D%5Bsubcategories%5D=laptops&sort%5Bfield%5D=name&sort%5Bdirection%5D=asc", + ); + }); + + it("should handle arrays with null/undefined values", () => { + const obj = { items: ["a", null, "c", undefined, "e"] }; + expect(toQueryString(obj)).toBe("items%5B0%5D=a&items%5B1%5D=&items%5B2%5D=c&items%5B4%5D=e"); + }); + + it("should handle objects with null/undefined values", () => { + const obj = { name: "John", age: null, email: undefined, active: true }; + expect(toQueryString(obj)).toBe("name=John&age=&active=true"); + }); + }); + + describe("Edge cases", () => { + it("should handle numeric keys", () => { + const obj = { "0": "zero", "1": "one" }; + expect(toQueryString(obj)).toBe("0=zero&1=one"); + }); + + it("should handle boolean values in objects", () => { + const obj = { enabled: true, disabled: false }; + expect(toQueryString(obj)).toBe("enabled=true&disabled=false"); + }); + + it("should handle empty strings", () => { + const obj = { name: "", description: "test" }; + expect(toQueryString(obj)).toBe("name=&description=test"); + }); + + it("should handle zero values", () => { + const obj = { count: 0, price: 0.0 }; + expect(toQueryString(obj)).toBe("count=0&price=0"); + }); + + it("should handle arrays with empty strings", () => { + const obj = { items: ["a", "", "c"] }; + expect(toQueryString(obj)).toBe("items%5B0%5D=a&items%5B1%5D=&items%5B2%5D=c"); + }); + }); + + describe("Options combinations", () => { + it("should respect both arrayFormat and encode options", () => { + const obj = { items: ["a & b", "c & d"] }; + expect(toQueryString(obj, { arrayFormat: "repeat", encode: false })).toBe("items=a & b&items=c & d"); + }); + + it("should use default options when none provided", () => { + const obj = { items: ["a", "b"] }; + expect(toQueryString(obj)).toBe("items%5B0%5D=a&items%5B1%5D=b"); + }); + + it("should merge provided options with defaults", () => { + const obj = { items: ["a", "b"], name: "John Doe" }; + expect(toQueryString(obj, { encode: false })).toBe("items[0]=a&items[1]=b&name=John Doe"); + }); + }); +}); diff --git a/tests/unit/utils/setObjectProperty.test.ts b/tests/unit/utils/setObjectProperty.test.ts new file mode 100644 index 000000000..29f8e638d --- /dev/null +++ b/tests/unit/utils/setObjectProperty.test.ts @@ -0,0 +1,76 @@ +import { setObjectProperty } from "../../../src/core/utils/setObjectProperty"; + +interface TestCase { + description: string; + giveObject: object; + givePath: string; + giveValue: any; + wantObject: object; +} + +describe("Test setObjectProperty", () => { + const testCases: TestCase[] = [ + { + description: "empty", + giveObject: {}, + givePath: "", + giveValue: 0, + wantObject: { "": 0 }, + }, + { + description: "top-level primitive", + giveObject: {}, + givePath: "age", + giveValue: 42, + wantObject: { age: 42 }, + }, + { + description: "top-level object", + giveObject: {}, + givePath: "name", + giveValue: { first: "John", last: "Doe" }, + wantObject: { name: { first: "John", last: "Doe" } }, + }, + { + description: "top-level array", + giveObject: {}, + givePath: "values", + giveValue: [1, 2, 3], + wantObject: { values: [1, 2, 3] }, + }, + { + description: "nested object property", + giveObject: { + name: { + first: "John", + }, + }, + givePath: "name.last", + giveValue: "Doe", + wantObject: { name: { first: "John", last: "Doe" } }, + }, + { + description: "deeply nested object property", + giveObject: { + info: { + address: { + street: "123 Main St.", + }, + age: 42, + name: { + last: "Doe", + }, + }, + }, + givePath: "info.name.first", + giveValue: "John", + wantObject: { + info: { age: 42, address: { street: "123 Main St." }, name: { first: "John", last: "Doe" } }, + }, + }, + ]; + test.each(testCases)("$description", ({ giveObject, givePath, giveValue, wantObject }) => { + const result = setObjectProperty(giveObject, givePath, giveValue); + expect(result).toEqual(wantObject); + }); +}); diff --git a/tests/wire/.gitkeep b/tests/wire/.gitkeep new file mode 100644 index 000000000..e69de29bb diff --git a/tests/wire/applePay.test.ts b/tests/wire/applePay.test.ts new file mode 100644 index 000000000..3db07c812 --- /dev/null +++ b/tests/wire/applePay.test.ts @@ -0,0 +1,41 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("ApplePay", () => { + test("RegisterDomain", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { domain_name: "example.com" }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + status: "VERIFIED", + }; + server + .mockEndpoint() + .post("/v2/apple-pay/domains") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.applePay.registerDomain({ + domainName: "example.com", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + status: "VERIFIED", + }); + }); +}); diff --git a/tests/wire/bankAccounts.test.ts b/tests/wire/bankAccounts.test.ts new file mode 100644 index 000000000..61e810ada --- /dev/null +++ b/tests/wire/bankAccounts.test.ts @@ -0,0 +1,144 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("BankAccounts", () => { + test("GetByV1Id", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + bank_account: { + id: "w3yRgCGYQnwmdl0R3GB", + account_number_suffix: "971", + country: "US", + currency: "USD", + account_type: "CHECKING", + holder_name: "Jane Doe", + primary_bank_identification_number: "112200303", + secondary_bank_identification_number: "secondary_bank_identification_number", + debit_mandate_reference_id: "debit_mandate_reference_id", + reference_id: "reference_id", + location_id: "S8GWD5example", + status: "VERIFICATION_IN_PROGRESS", + creditable: false, + debitable: false, + fingerprint: "fingerprint", + version: 5, + bank_name: "Bank Name", + }, + }; + server + .mockEndpoint() + .get("/v2/bank-accounts/by-v1-id/v1_bank_account_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bankAccounts.getByV1Id({ + v1BankAccountId: "v1_bank_account_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + bankAccount: { + id: "w3yRgCGYQnwmdl0R3GB", + accountNumberSuffix: "971", + country: "US", + currency: "USD", + accountType: "CHECKING", + holderName: "Jane Doe", + primaryBankIdentificationNumber: "112200303", + secondaryBankIdentificationNumber: "secondary_bank_identification_number", + debitMandateReferenceId: "debit_mandate_reference_id", + referenceId: "reference_id", + locationId: "S8GWD5example", + status: "VERIFICATION_IN_PROGRESS", + creditable: false, + debitable: false, + fingerprint: "fingerprint", + version: 5, + bankName: "Bank Name", + }, + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + bank_account: { + id: "w3yRgCGYQnwmdl0R3GB", + account_number_suffix: "971", + country: "US", + currency: "USD", + account_type: "CHECKING", + holder_name: "Jane Doe", + primary_bank_identification_number: "112200303", + secondary_bank_identification_number: "secondary_bank_identification_number", + debit_mandate_reference_id: "debit_mandate_reference_id", + reference_id: "reference_id", + location_id: "S8GWD5example", + status: "VERIFICATION_IN_PROGRESS", + creditable: false, + debitable: false, + fingerprint: "fingerprint", + version: 5, + bank_name: "Bank Name", + }, + }; + server + .mockEndpoint() + .get("/v2/bank-accounts/bank_account_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bankAccounts.get({ + bankAccountId: "bank_account_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + bankAccount: { + id: "w3yRgCGYQnwmdl0R3GB", + accountNumberSuffix: "971", + country: "US", + currency: "USD", + accountType: "CHECKING", + holderName: "Jane Doe", + primaryBankIdentificationNumber: "112200303", + secondaryBankIdentificationNumber: "secondary_bank_identification_number", + debitMandateReferenceId: "debit_mandate_reference_id", + referenceId: "reference_id", + locationId: "S8GWD5example", + status: "VERIFICATION_IN_PROGRESS", + creditable: false, + debitable: false, + fingerprint: "fingerprint", + version: 5, + bankName: "Bank Name", + }, + }); + }); +}); diff --git a/tests/wire/bookings.test.ts b/tests/wire/bookings.test.ts new file mode 100644 index 000000000..8c702a91e --- /dev/null +++ b/tests/wire/bookings.test.ts @@ -0,0 +1,1327 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Bookings", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { booking: {} }; + const rawResponseBody = { + booking: { + id: "zkras0xv0xwswx", + version: 0, + status: "ACCEPTED", + created_at: "2020-10-28T15:47:41Z", + updated_at: "2020-10-28T15:47:41Z", + start_at: "2020-11-26T13:00:00Z", + location_id: "LEQHH0YY8B42M", + customer_id: "EX2QSVGTZN4K1E5QE1CBFNVQ8M", + customer_note: "", + seller_note: "", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMXUrsBWWcHTt79t", + service_variation_version: BigInt(1599775456731), + }, + ], + transition_time_minutes: 1, + all_day: true, + location_type: "BUSINESS_LOCATION", + creator_details: { + creator_type: "TEAM_MEMBER", + team_member_id: "team_member_id", + customer_id: "customer_id", + }, + source: "FIRST_PARTY_MERCHANT", + address: { + address_line_1: "address_line_1", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "administrative_district_level_1", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "postal_code", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/bookings") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.create({ + booking: {}, + }); + expect(response).toEqual({ + booking: { + id: "zkras0xv0xwswx", + version: 0, + status: "ACCEPTED", + createdAt: "2020-10-28T15:47:41Z", + updatedAt: "2020-10-28T15:47:41Z", + startAt: "2020-11-26T13:00:00Z", + locationId: "LEQHH0YY8B42M", + customerId: "EX2QSVGTZN4K1E5QE1CBFNVQ8M", + customerNote: "", + sellerNote: "", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMXUrsBWWcHTt79t", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + transitionTimeMinutes: 1, + allDay: true, + locationType: "BUSINESS_LOCATION", + creatorDetails: { + creatorType: "TEAM_MEMBER", + teamMemberId: "team_member_id", + customerId: "customer_id", + }, + source: "FIRST_PARTY_MERCHANT", + address: { + addressLine1: "address_line_1", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "administrative_district_level_1", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "postal_code", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("SearchAvailability", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { query: { filter: { start_at_range: {} } } }; + const rawResponseBody = { + availabilities: [ + { + start_at: "2020-11-26T13:00:00Z", + location_id: "LEQHH0YY8B42M", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMXUrsBWWcHTt79t", + service_variation_version: BigInt(1599775456731), + }, + ], + }, + { + start_at: "2020-11-26T13:30:00Z", + location_id: "LEQHH0YY8B42M", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMXUrsBWWcHTt79t", + service_variation_version: BigInt(1599775456731), + }, + ], + }, + { + start_at: "2020-11-26T14:00:00Z", + location_id: "LEQHH0YY8B42M", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMaJcbiRqPIGZuS9", + service_variation_version: BigInt(1599775456731), + }, + ], + }, + { + start_at: "2020-11-26T14:30:00Z", + location_id: "LEQHH0YY8B42M", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMaJcbiRqPIGZuS9", + service_variation_version: BigInt(1599775456731), + }, + ], + }, + { + start_at: "2020-11-26T15:00:00Z", + location_id: "LEQHH0YY8B42M", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMaJcbiRqPIGZuS9", + service_variation_version: BigInt(1599775456731), + }, + ], + }, + { + start_at: "2020-11-26T15:30:00Z", + location_id: "LEQHH0YY8B42M", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMaJcbiRqPIGZuS9", + service_variation_version: BigInt(1599775456731), + }, + ], + }, + { + start_at: "2020-11-26T16:00:00Z", + location_id: "LEQHH0YY8B42M", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMaJcbiRqPIGZuS9", + service_variation_version: BigInt(1599775456731), + }, + ], + }, + { + start_at: "2020-11-27T09:00:00Z", + location_id: "LEQHH0YY8B42M", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMXUrsBWWcHTt79t", + service_variation_version: BigInt(1599775456731), + }, + ], + }, + { + start_at: "2020-11-27T09:30:00Z", + location_id: "LEQHH0YY8B42M", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMaJcbiRqPIGZuS9", + service_variation_version: BigInt(1599775456731), + }, + ], + }, + { + start_at: "2020-11-27T10:00:00Z", + location_id: "LEQHH0YY8B42M", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMXUrsBWWcHTt79t", + service_variation_version: BigInt(1599775456731), + }, + ], + }, + { + start_at: "2020-11-27T10:30:00Z", + location_id: "LEQHH0YY8B42M", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMXUrsBWWcHTt79t", + service_variation_version: BigInt(1599775456731), + }, + ], + }, + { + start_at: "2020-11-27T11:00:00Z", + location_id: "LEQHH0YY8B42M", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMXUrsBWWcHTt79t", + service_variation_version: BigInt(1599775456731), + }, + ], + }, + { + start_at: "2020-11-27T11:30:00Z", + location_id: "LEQHH0YY8B42M", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMaJcbiRqPIGZuS9", + service_variation_version: BigInt(1599775456731), + }, + ], + }, + { + start_at: "2020-11-27T12:00:00Z", + location_id: "LEQHH0YY8B42M", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMaJcbiRqPIGZuS9", + service_variation_version: BigInt(1599775456731), + }, + ], + }, + { + start_at: "2020-11-27T12:30:00Z", + location_id: "LEQHH0YY8B42M", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMaJcbiRqPIGZuS9", + service_variation_version: BigInt(1599775456731), + }, + ], + }, + { + start_at: "2020-11-27T13:00:00Z", + location_id: "LEQHH0YY8B42M", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMXUrsBWWcHTt79t", + service_variation_version: BigInt(1599775456731), + }, + ], + }, + { + start_at: "2020-11-27T13:30:00Z", + location_id: "LEQHH0YY8B42M", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMXUrsBWWcHTt79t", + service_variation_version: BigInt(1599775456731), + }, + ], + }, + { + start_at: "2020-11-27T14:00:00Z", + location_id: "LEQHH0YY8B42M", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMaJcbiRqPIGZuS9", + service_variation_version: BigInt(1599775456731), + }, + ], + }, + ], + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/bookings/availability/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.searchAvailability({ + query: { + filter: { + startAtRange: {}, + }, + }, + }); + expect(response).toEqual({ + availabilities: [ + { + startAt: "2020-11-26T13:00:00Z", + locationId: "LEQHH0YY8B42M", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMXUrsBWWcHTt79t", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + }, + { + startAt: "2020-11-26T13:30:00Z", + locationId: "LEQHH0YY8B42M", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMXUrsBWWcHTt79t", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + }, + { + startAt: "2020-11-26T14:00:00Z", + locationId: "LEQHH0YY8B42M", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMaJcbiRqPIGZuS9", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + }, + { + startAt: "2020-11-26T14:30:00Z", + locationId: "LEQHH0YY8B42M", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMaJcbiRqPIGZuS9", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + }, + { + startAt: "2020-11-26T15:00:00Z", + locationId: "LEQHH0YY8B42M", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMaJcbiRqPIGZuS9", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + }, + { + startAt: "2020-11-26T15:30:00Z", + locationId: "LEQHH0YY8B42M", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMaJcbiRqPIGZuS9", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + }, + { + startAt: "2020-11-26T16:00:00Z", + locationId: "LEQHH0YY8B42M", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMaJcbiRqPIGZuS9", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + }, + { + startAt: "2020-11-27T09:00:00Z", + locationId: "LEQHH0YY8B42M", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMXUrsBWWcHTt79t", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + }, + { + startAt: "2020-11-27T09:30:00Z", + locationId: "LEQHH0YY8B42M", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMaJcbiRqPIGZuS9", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + }, + { + startAt: "2020-11-27T10:00:00Z", + locationId: "LEQHH0YY8B42M", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMXUrsBWWcHTt79t", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + }, + { + startAt: "2020-11-27T10:30:00Z", + locationId: "LEQHH0YY8B42M", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMXUrsBWWcHTt79t", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + }, + { + startAt: "2020-11-27T11:00:00Z", + locationId: "LEQHH0YY8B42M", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMXUrsBWWcHTt79t", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + }, + { + startAt: "2020-11-27T11:30:00Z", + locationId: "LEQHH0YY8B42M", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMaJcbiRqPIGZuS9", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + }, + { + startAt: "2020-11-27T12:00:00Z", + locationId: "LEQHH0YY8B42M", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMaJcbiRqPIGZuS9", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + }, + { + startAt: "2020-11-27T12:30:00Z", + locationId: "LEQHH0YY8B42M", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMaJcbiRqPIGZuS9", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + }, + { + startAt: "2020-11-27T13:00:00Z", + locationId: "LEQHH0YY8B42M", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMXUrsBWWcHTt79t", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + }, + { + startAt: "2020-11-27T13:30:00Z", + locationId: "LEQHH0YY8B42M", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMXUrsBWWcHTt79t", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + }, + { + startAt: "2020-11-27T14:00:00Z", + locationId: "LEQHH0YY8B42M", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMaJcbiRqPIGZuS9", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + }, + ], + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("BulkRetrieveBookings", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { booking_ids: ["booking_ids"] }; + const rawResponseBody = { + bookings: { + sc3p3m7dvctfr1: { + booking: { + id: "sc3p3m7dvctfr1", + version: 0, + status: "ACCEPTED", + created_at: "2023-04-26T18:19:21Z", + updated_at: "2023-04-26T18:19:21Z", + start_at: "2023-05-01T14:00:00Z", + location_id: "LY6WNBPVM6VGV", + customer_id: "4TDWKN9E8165X8Z77MRS0VFMJM", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "VG4FYBKK3UL6UITOEYQ6MFLS", + team_member_id: "TMjiqI3PxyLMKr4k", + service_variation_version: BigInt(1641341724039), + any_team_member: false, + }, + ], + all_day: false, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + tdegug1dvctdef: { + errors: [ + { + category: "INVALID_REQUEST_ERROR", + code: "NOT_FOUND", + detail: "Specified booking was not found.", + field: "booking_id", + }, + ], + }, + tdegug1fqni3wh: { + booking: { + id: "tdegug1fqni3wh", + version: 0, + status: "ACCEPTED", + created_at: "2023-04-26T18:19:30Z", + updated_at: "2023-04-26T18:19:30Z", + start_at: "2023-05-02T14:00:00Z", + location_id: "LY6WNBPVM6VGV", + customer_id: "4TDWKN9E8165X8Z77MRS0VFMJM", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "VG4FYBKK3UL6UITOEYQ6MFLS", + team_member_id: "TMjiqI3PxyLMKr4k", + service_variation_version: BigInt(1641341724039), + any_team_member: false, + }, + ], + all_day: false, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/bookings/bulk-retrieve") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.bulkRetrieveBookings({ + bookingIds: ["booking_ids"], + }); + expect(response).toEqual({ + bookings: { + sc3p3m7dvctfr1: { + booking: { + id: "sc3p3m7dvctfr1", + version: 0, + status: "ACCEPTED", + createdAt: "2023-04-26T18:19:21Z", + updatedAt: "2023-04-26T18:19:21Z", + startAt: "2023-05-01T14:00:00Z", + locationId: "LY6WNBPVM6VGV", + customerId: "4TDWKN9E8165X8Z77MRS0VFMJM", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "VG4FYBKK3UL6UITOEYQ6MFLS", + teamMemberId: "TMjiqI3PxyLMKr4k", + serviceVariationVersion: BigInt("1641341724039"), + anyTeamMember: false, + }, + ], + allDay: false, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + tdegug1dvctdef: { + errors: [ + { + category: "INVALID_REQUEST_ERROR", + code: "NOT_FOUND", + detail: "Specified booking was not found.", + field: "booking_id", + }, + ], + }, + tdegug1fqni3wh: { + booking: { + id: "tdegug1fqni3wh", + version: 0, + status: "ACCEPTED", + createdAt: "2023-04-26T18:19:30Z", + updatedAt: "2023-04-26T18:19:30Z", + startAt: "2023-05-02T14:00:00Z", + locationId: "LY6WNBPVM6VGV", + customerId: "4TDWKN9E8165X8Z77MRS0VFMJM", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "VG4FYBKK3UL6UITOEYQ6MFLS", + teamMemberId: "TMjiqI3PxyLMKr4k", + serviceVariationVersion: BigInt("1641341724039"), + anyTeamMember: false, + }, + ], + allDay: false, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("getBusinessProfile", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + business_booking_profile: { + seller_id: "MLJQYZZRM0D3Y", + created_at: "2020-09-10T21:40:38Z", + booking_enabled: true, + customer_timezone_choice: "CUSTOMER_CHOICE", + booking_policy: "ACCEPT_ALL", + allow_user_cancel: true, + business_appointment_settings: { + location_types: ["BUSINESS_LOCATION"], + alignment_time: "HALF_HOURLY", + min_booking_lead_time_seconds: 0, + max_booking_lead_time_seconds: 31536000, + any_team_member_booking_enabled: true, + multiple_service_booking_enabled: true, + max_appointments_per_day_limit_type: "PER_TEAM_MEMBER", + max_appointments_per_day_limit: 1, + cancellation_window_seconds: 1, + cancellation_fee_money: { currency: "USD" }, + cancellation_policy: "CUSTOM_POLICY", + cancellation_policy_text: "cancellation_policy_text", + skip_booking_flow_staff_selection: false, + }, + support_seller_level_writes: true, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/bookings/business-booking-profile") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.getBusinessProfile(); + expect(response).toEqual({ + businessBookingProfile: { + sellerId: "MLJQYZZRM0D3Y", + createdAt: "2020-09-10T21:40:38Z", + bookingEnabled: true, + customerTimezoneChoice: "CUSTOMER_CHOICE", + bookingPolicy: "ACCEPT_ALL", + allowUserCancel: true, + businessAppointmentSettings: { + locationTypes: ["BUSINESS_LOCATION"], + alignmentTime: "HALF_HOURLY", + minBookingLeadTimeSeconds: 0, + maxBookingLeadTimeSeconds: 31536000, + anyTeamMemberBookingEnabled: true, + multipleServiceBookingEnabled: true, + maxAppointmentsPerDayLimitType: "PER_TEAM_MEMBER", + maxAppointmentsPerDayLimit: 1, + cancellationWindowSeconds: 1, + cancellationFeeMoney: { + currency: "USD", + }, + cancellationPolicy: "CUSTOM_POLICY", + cancellationPolicyText: "cancellation_policy_text", + skipBookingFlowStaffSelection: false, + }, + supportSellerLevelWrites: true, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("RetrieveLocationBookingProfile", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + location_booking_profile: { + location_id: "L3HETDGYQ4A2C", + booking_site_url: "https://square.site/book/L3HETDGYQ4A2C/prod-business", + online_booking_enabled: true, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/bookings/location-booking-profiles/location_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.retrieveLocationBookingProfile({ + locationId: "location_id", + }); + expect(response).toEqual({ + locationBookingProfile: { + locationId: "L3HETDGYQ4A2C", + bookingSiteUrl: "https://square.site/book/L3HETDGYQ4A2C/prod-business", + onlineBookingEnabled: true, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("BulkRetrieveTeamMemberBookingProfiles", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { team_member_ids: ["team_member_ids"] }; + const rawResponseBody = { + team_member_booking_profiles: { + TMXUrsBWWcHTt79t: { + errors: [{ category: "INVALID_REQUEST_ERROR", code: "NOT_FOUND", detail: "Resource not found." }], + }, + TMaJcbiRqPIGZuS9: { + team_member_booking_profile: { + team_member_id: "TMaJcbiRqPIGZuS9", + display_name: "Sandbox Staff 1", + is_bookable: true, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + TMtdegug1fqni3wh: { + team_member_booking_profile: { + team_member_id: "TMtdegug1fqni3wh", + display_name: "Sandbox Staff 2", + is_bookable: true, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/bookings/team-member-booking-profiles/bulk-retrieve") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.bulkRetrieveTeamMemberBookingProfiles({ + teamMemberIds: ["team_member_ids"], + }); + expect(response).toEqual({ + teamMemberBookingProfiles: { + TMXUrsBWWcHTt79t: { + errors: [ + { + category: "INVALID_REQUEST_ERROR", + code: "NOT_FOUND", + detail: "Resource not found.", + }, + ], + }, + TMaJcbiRqPIGZuS9: { + teamMemberBookingProfile: { + teamMemberId: "TMaJcbiRqPIGZuS9", + displayName: "Sandbox Staff 1", + isBookable: true, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + TMtdegug1fqni3wh: { + teamMemberBookingProfile: { + teamMemberId: "TMtdegug1fqni3wh", + displayName: "Sandbox Staff 2", + isBookable: true, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + booking: { + id: "zkras0xv0xwswx", + version: 1, + status: "ACCEPTED", + created_at: "2020-10-28T15:47:41Z", + updated_at: "2020-10-28T15:49:25Z", + start_at: "2020-11-26T13:00:00Z", + location_id: "LEQHH0YY8B42M", + customer_id: "EX2QSVGTZN4K1E5QE1CBFNVQ8M", + customer_note: "", + seller_note: "", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMXUrsBWWcHTt79t", + service_variation_version: BigInt(1599775456731), + }, + ], + transition_time_minutes: 1, + all_day: true, + location_type: "BUSINESS_LOCATION", + creator_details: { + creator_type: "TEAM_MEMBER", + team_member_id: "team_member_id", + customer_id: "customer_id", + }, + source: "FIRST_PARTY_MERCHANT", + address: { + address_line_1: "address_line_1", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "administrative_district_level_1", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "postal_code", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/bookings/booking_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.get({ + bookingId: "booking_id", + }); + expect(response).toEqual({ + booking: { + id: "zkras0xv0xwswx", + version: 1, + status: "ACCEPTED", + createdAt: "2020-10-28T15:47:41Z", + updatedAt: "2020-10-28T15:49:25Z", + startAt: "2020-11-26T13:00:00Z", + locationId: "LEQHH0YY8B42M", + customerId: "EX2QSVGTZN4K1E5QE1CBFNVQ8M", + customerNote: "", + sellerNote: "", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMXUrsBWWcHTt79t", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + transitionTimeMinutes: 1, + allDay: true, + locationType: "BUSINESS_LOCATION", + creatorDetails: { + creatorType: "TEAM_MEMBER", + teamMemberId: "team_member_id", + customerId: "customer_id", + }, + source: "FIRST_PARTY_MERCHANT", + address: { + addressLine1: "address_line_1", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "administrative_district_level_1", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "postal_code", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { booking: {} }; + const rawResponseBody = { + booking: { + id: "zkras0xv0xwswx", + version: 2, + status: "ACCEPTED", + created_at: "2020-10-28T15:47:41Z", + updated_at: "2020-10-28T15:49:25Z", + start_at: "2020-11-26T13:00:00Z", + location_id: "LEQHH0YY8B42M", + customer_id: "EX2QSVGTZN4K1E5QE1CBFNVQ8M", + customer_note: "I would like to sit near the window please", + seller_note: "", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMXUrsBWWcHTt79t", + service_variation_version: BigInt(1599775456731), + }, + ], + transition_time_minutes: 1, + all_day: true, + location_type: "CUSTOMER_LOCATION", + creator_details: { + creator_type: "TEAM_MEMBER", + team_member_id: "team_member_id", + customer_id: "customer_id", + }, + source: "FIRST_PARTY_MERCHANT", + address: { + address_line_1: "1955 Broadway", + address_line_2: "Suite 600", + address_line_3: "address_line_3", + locality: "Oakland", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "CA", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "94612", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .put("/v2/bookings/booking_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.update({ + bookingId: "booking_id", + booking: {}, + }); + expect(response).toEqual({ + booking: { + id: "zkras0xv0xwswx", + version: 2, + status: "ACCEPTED", + createdAt: "2020-10-28T15:47:41Z", + updatedAt: "2020-10-28T15:49:25Z", + startAt: "2020-11-26T13:00:00Z", + locationId: "LEQHH0YY8B42M", + customerId: "EX2QSVGTZN4K1E5QE1CBFNVQ8M", + customerNote: "I would like to sit near the window please", + sellerNote: "", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMXUrsBWWcHTt79t", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + transitionTimeMinutes: 1, + allDay: true, + locationType: "CUSTOMER_LOCATION", + creatorDetails: { + creatorType: "TEAM_MEMBER", + teamMemberId: "team_member_id", + customerId: "customer_id", + }, + source: "FIRST_PARTY_MERCHANT", + address: { + addressLine1: "1955 Broadway", + addressLine2: "Suite 600", + addressLine3: "address_line_3", + locality: "Oakland", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "CA", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "94612", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("cancel", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = {}; + const rawResponseBody = { + booking: { + id: "zkras0xv0xwswx", + version: 1, + status: "CANCELLED_BY_CUSTOMER", + created_at: "2020-10-28T15:47:41Z", + updated_at: "2020-10-28T15:49:25Z", + start_at: "2020-11-26T13:00:00Z", + location_id: "LEQHH0YY8B42M", + customer_id: "EX2QSVGTZN4K1E5QE1CBFNVQ8M", + customer_note: "", + seller_note: "", + appointment_segments: [ + { + duration_minutes: 60, + service_variation_id: "RU3PBTZTK7DXZDQFCJHOK2MC", + team_member_id: "TMXUrsBWWcHTt79t", + service_variation_version: BigInt(1599775456731), + }, + ], + transition_time_minutes: 1, + all_day: true, + location_type: "BUSINESS_LOCATION", + creator_details: { + creator_type: "TEAM_MEMBER", + team_member_id: "team_member_id", + customer_id: "customer_id", + }, + source: "FIRST_PARTY_MERCHANT", + address: { + address_line_1: "address_line_1", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "administrative_district_level_1", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "postal_code", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/bookings/booking_id/cancel") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.cancel({ + bookingId: "booking_id", + }); + expect(response).toEqual({ + booking: { + id: "zkras0xv0xwswx", + version: 1, + status: "CANCELLED_BY_CUSTOMER", + createdAt: "2020-10-28T15:47:41Z", + updatedAt: "2020-10-28T15:49:25Z", + startAt: "2020-11-26T13:00:00Z", + locationId: "LEQHH0YY8B42M", + customerId: "EX2QSVGTZN4K1E5QE1CBFNVQ8M", + customerNote: "", + sellerNote: "", + appointmentSegments: [ + { + durationMinutes: 60, + serviceVariationId: "RU3PBTZTK7DXZDQFCJHOK2MC", + teamMemberId: "TMXUrsBWWcHTt79t", + serviceVariationVersion: BigInt("1599775456731"), + }, + ], + transitionTimeMinutes: 1, + allDay: true, + locationType: "BUSINESS_LOCATION", + creatorDetails: { + creatorType: "TEAM_MEMBER", + teamMemberId: "team_member_id", + customerId: "customer_id", + }, + source: "FIRST_PARTY_MERCHANT", + address: { + addressLine1: "address_line_1", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "administrative_district_level_1", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "postal_code", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/bookings/customAttributeDefinitions.test.ts b/tests/wire/bookings/customAttributeDefinitions.test.ts new file mode 100644 index 000000000..fcbf544cd --- /dev/null +++ b/tests/wire/bookings/customAttributeDefinitions.test.ts @@ -0,0 +1,203 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("CustomAttributeDefinitions", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { custom_attribute_definition: {} }; + const rawResponseBody = { + custom_attribute_definition: { + key: "favoriteShampoo", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Favorite Shampoo", + description: "The favorite shampoo of the customer.", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updated_at: "2022-11-16T15:27:30Z", + created_at: "2022-11-16T15:27:30Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/bookings/custom-attribute-definitions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.customAttributeDefinitions.create({ + customAttributeDefinition: {}, + }); + expect(response).toEqual({ + customAttributeDefinition: { + key: "favoriteShampoo", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Favorite Shampoo", + description: "The favorite shampoo of the customer.", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updatedAt: "2022-11-16T15:27:30Z", + createdAt: "2022-11-16T15:27:30Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + custom_attribute_definition: { + key: "favoriteShampoo", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Favorite shampoo", + description: "The favorite shampoo of the customer.", + visibility: "VISIBILITY_READ_WRITE_VALUES", + version: 1, + updated_at: "2022-11-16T15:27:30Z", + created_at: "2022-11-16T15:27:30Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/bookings/custom-attribute-definitions/key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.customAttributeDefinitions.get({ + key: "key", + }); + expect(response).toEqual({ + customAttributeDefinition: { + key: "favoriteShampoo", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Favorite shampoo", + description: "The favorite shampoo of the customer.", + visibility: "VISIBILITY_READ_WRITE_VALUES", + version: 1, + updatedAt: "2022-11-16T15:27:30Z", + createdAt: "2022-11-16T15:27:30Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { custom_attribute_definition: {} }; + const rawResponseBody = { + custom_attribute_definition: { + key: "favoriteShampoo", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Favorite shampoo", + description: "Update the description as desired.", + visibility: "VISIBILITY_READ_ONLY", + version: 2, + updated_at: "2022-11-16T15:39:38Z", + created_at: "2022-11-16T15:27:30Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .put("/v2/bookings/custom-attribute-definitions/key") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.customAttributeDefinitions.update({ + key: "key", + customAttributeDefinition: {}, + }); + expect(response).toEqual({ + customAttributeDefinition: { + key: "favoriteShampoo", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Favorite shampoo", + description: "Update the description as desired.", + visibility: "VISIBILITY_READ_ONLY", + version: 2, + updatedAt: "2022-11-16T15:39:38Z", + createdAt: "2022-11-16T15:27:30Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/bookings/custom-attribute-definitions/key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.customAttributeDefinitions.delete({ + key: "key", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/bookings/customAttributes.test.ts b/tests/wire/bookings/customAttributes.test.ts new file mode 100644 index 000000000..81ef7210a --- /dev/null +++ b/tests/wire/bookings/customAttributes.test.ts @@ -0,0 +1,443 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("CustomAttributes", () => { + test("batchDelete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { values: { key: { booking_id: "booking_id", key: "key" } } }; + const rawResponseBody = { + values: { + id1: { + booking_id: "N3NCVYY3WS27HF0HKANA3R9FP8", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + id2: { + booking_id: "SY8EMWRNDN3TQDP2H4KS1QWMMM", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + id3: { + booking_id: "SY8EMWRNDN3TQDP2H4KS1QWMMM", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/bookings/custom-attributes/bulk-delete") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.customAttributes.batchDelete({ + values: { + key: { + bookingId: "booking_id", + key: "key", + }, + }, + }); + expect(response).toEqual({ + values: { + id1: { + bookingId: "N3NCVYY3WS27HF0HKANA3R9FP8", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + id2: { + bookingId: "SY8EMWRNDN3TQDP2H4KS1QWMMM", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + id3: { + bookingId: "SY8EMWRNDN3TQDP2H4KS1QWMMM", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("batchUpsert", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { values: { key: { booking_id: "booking_id", custom_attribute: {} } } }; + const rawResponseBody = { + values: { + id1: { + booking_id: "N3NCVYY3WS27HF0HKANA3R9FP8", + custom_attribute: { + key: "favoriteShampoo", + value: "Spring Fresh", + version: 1, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updated_at: "2022-11-16T00:16:23Z", + created_at: "2022-11-16T23:14:47Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + id2: { + booking_id: "SY8EMWRNDN3TQDP2H4KS1QWMMM", + custom_attribute: { + key: "hasShoes", + value: false, + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updated_at: "2022-11-16T00:16:23Z", + created_at: "2022-11-16T00:16:20Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + id3: { + booking_id: "SY8EMWRNDN3TQDP2H4KS1QWMMM", + custom_attribute: { + key: "favoriteShampoo", + value: "Hydro-Cool", + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updated_at: "2022-11-16T00:16:23Z", + created_at: "2022-11-16T00:16:20Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + id4: { + booking_id: "N3NCVYY3WS27HF0HKANA3R9FP8", + custom_attribute: { + key: "partySize", + value: 4, + version: 1, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updated_at: "2022-11-16T00:16:23Z", + created_at: "2022-11-16T23:14:47Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + id5: { + booking_id: "70548QG1HN43B05G0KCZ4MMC1G", + custom_attribute: { + key: "celebrating", + value: "birthday", + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updated_at: "2022-11-16T00:16:23Z", + created_at: "2022-11-16T00:16:20Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/bookings/custom-attributes/bulk-upsert") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.customAttributes.batchUpsert({ + values: { + key: { + bookingId: "booking_id", + customAttribute: {}, + }, + }, + }); + expect(response).toEqual({ + values: { + id1: { + bookingId: "N3NCVYY3WS27HF0HKANA3R9FP8", + customAttribute: { + key: "favoriteShampoo", + value: "Spring Fresh", + version: 1, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updatedAt: "2022-11-16T00:16:23Z", + createdAt: "2022-11-16T23:14:47Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + id2: { + bookingId: "SY8EMWRNDN3TQDP2H4KS1QWMMM", + customAttribute: { + key: "hasShoes", + value: false, + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updatedAt: "2022-11-16T00:16:23Z", + createdAt: "2022-11-16T00:16:20Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + id3: { + bookingId: "SY8EMWRNDN3TQDP2H4KS1QWMMM", + customAttribute: { + key: "favoriteShampoo", + value: "Hydro-Cool", + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updatedAt: "2022-11-16T00:16:23Z", + createdAt: "2022-11-16T00:16:20Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + id4: { + bookingId: "N3NCVYY3WS27HF0HKANA3R9FP8", + customAttribute: { + key: "partySize", + value: 4, + version: 1, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updatedAt: "2022-11-16T00:16:23Z", + createdAt: "2022-11-16T23:14:47Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + id5: { + bookingId: "70548QG1HN43B05G0KCZ4MMC1G", + customAttribute: { + key: "celebrating", + value: "birthday", + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updatedAt: "2022-11-16T00:16:23Z", + createdAt: "2022-11-16T00:16:20Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + custom_attribute: { + key: "favoriteShampoo", + value: "Dune", + version: 1, + visibility: "VISIBILITY_READ_ONLY", + definition: { + key: "key", + schema: { key: "value" }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updated_at: "updated_at", + created_at: "created_at", + }, + updated_at: "2022-11-16T15:50:27Z", + created_at: "2022-11-16T15:50:27Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/bookings/booking_id/custom-attributes/key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.customAttributes.get({ + bookingId: "booking_id", + key: "key", + }); + expect(response).toEqual({ + customAttribute: { + key: "favoriteShampoo", + value: "Dune", + version: 1, + visibility: "VISIBILITY_READ_ONLY", + definition: { + key: "key", + schema: { + key: "value", + }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updatedAt: "updated_at", + createdAt: "created_at", + }, + updatedAt: "2022-11-16T15:50:27Z", + createdAt: "2022-11-16T15:50:27Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("upsert", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { custom_attribute: {} }; + const rawResponseBody = { + custom_attribute: { + key: "favoriteShampoo", + value: "Spring Fresh", + version: 1, + visibility: "VISIBILITY_READ_ONLY", + definition: { + key: "key", + schema: { key: "value" }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updated_at: "updated_at", + created_at: "created_at", + }, + updated_at: "2022-11-16T15:50:27Z", + created_at: "2022-11-16T15:50:27Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .put("/v2/bookings/booking_id/custom-attributes/key") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.customAttributes.upsert({ + bookingId: "booking_id", + key: "key", + customAttribute: {}, + }); + expect(response).toEqual({ + customAttribute: { + key: "favoriteShampoo", + value: "Spring Fresh", + version: 1, + visibility: "VISIBILITY_READ_ONLY", + definition: { + key: "key", + schema: { + key: "value", + }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updatedAt: "updated_at", + createdAt: "created_at", + }, + updatedAt: "2022-11-16T15:50:27Z", + createdAt: "2022-11-16T15:50:27Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/bookings/booking_id/custom-attributes/key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.customAttributes.delete({ + bookingId: "booking_id", + key: "key", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/bookings/teamMemberProfiles.test.ts b/tests/wire/bookings/teamMemberProfiles.test.ts new file mode 100644 index 000000000..cb71bc88d --- /dev/null +++ b/tests/wire/bookings/teamMemberProfiles.test.ts @@ -0,0 +1,52 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("TeamMemberProfiles", () => { + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + team_member_booking_profile: { + team_member_id: "TMaJcbiRqPIGZuS9", + description: "description", + display_name: "Sandbox Staff", + is_bookable: true, + profile_image_url: "profile_image_url", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/bookings/team-member-booking-profiles/team_member_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.bookings.teamMemberProfiles.get({ + teamMemberId: "team_member_id", + }); + expect(response).toEqual({ + teamMemberBookingProfile: { + teamMemberId: "TMaJcbiRqPIGZuS9", + description: "description", + displayName: "Sandbox Staff", + isBookable: true, + profileImageUrl: "profile_image_url", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/cards.test.ts b/tests/wire/cards.test.ts new file mode 100644 index 000000000..42ac023e4 --- /dev/null +++ b/tests/wire/cards.test.ts @@ -0,0 +1,345 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Cards", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "4935a656-a929-4792-b97c-8848be85c27c", + source_id: "cnon:uIbfJXhXETSP197M3GB", + card: { + cardholder_name: "Amelia Earhart", + billing_address: { + address_line_1: "500 Electric Ave", + address_line_2: "Suite 600", + locality: "New York", + administrative_district_level_1: "NY", + postal_code: "10003", + country: "US", + }, + customer_id: "VDKXEEKPJN48QDG3BGGFAK05P8", + reference_id: "user-id-1", + }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + card: { + id: "ccof:uIbfJXhXETSP197M3GB", + card_brand: "VISA", + last_4: "1111", + exp_month: BigInt(11), + exp_year: BigInt(2022), + cardholder_name: "Amelia Earhart", + billing_address: { + address_line_1: "500 Electric Ave", + address_line_2: "Suite 600", + address_line_3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "NY", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "10003", + country: "US", + first_name: "first_name", + last_name: "last_name", + }, + fingerprint: "ex-p-cs80EK9Flz7LsCMv-szbptQ_ssAGrhemzSTsPFgt9nzyE6t7okiLIQc-qw_quqKX4Q", + customer_id: "VDKXEEKPJN48QDG3BGGFAK05P8", + merchant_id: "6SSW7HV8K2ST5", + reference_id: "user-id-1", + enabled: true, + card_type: "CREDIT", + prepaid_type: "NOT_PREPAID", + bin: "411111", + version: BigInt(1), + card_co_brand: "UNKNOWN", + issuer_alert: "ISSUER_ALERT_CARD_CLOSED", + issuer_alert_at: "issuer_alert_at", + hsa_fsa: false, + }, + }; + server + .mockEndpoint() + .post("/v2/cards") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.cards.create({ + idempotencyKey: "4935a656-a929-4792-b97c-8848be85c27c", + sourceId: "cnon:uIbfJXhXETSP197M3GB", + card: { + cardholderName: "Amelia Earhart", + billingAddress: { + addressLine1: "500 Electric Ave", + addressLine2: "Suite 600", + locality: "New York", + administrativeDistrictLevel1: "NY", + postalCode: "10003", + country: "US", + }, + customerId: "VDKXEEKPJN48QDG3BGGFAK05P8", + referenceId: "user-id-1", + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + card: { + id: "ccof:uIbfJXhXETSP197M3GB", + cardBrand: "VISA", + last4: "1111", + expMonth: BigInt("11"), + expYear: BigInt("2022"), + cardholderName: "Amelia Earhart", + billingAddress: { + addressLine1: "500 Electric Ave", + addressLine2: "Suite 600", + addressLine3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "NY", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "10003", + country: "US", + firstName: "first_name", + lastName: "last_name", + }, + fingerprint: "ex-p-cs80EK9Flz7LsCMv-szbptQ_ssAGrhemzSTsPFgt9nzyE6t7okiLIQc-qw_quqKX4Q", + customerId: "VDKXEEKPJN48QDG3BGGFAK05P8", + merchantId: "6SSW7HV8K2ST5", + referenceId: "user-id-1", + enabled: true, + cardType: "CREDIT", + prepaidType: "NOT_PREPAID", + bin: "411111", + version: BigInt("1"), + cardCoBrand: "UNKNOWN", + issuerAlert: "ISSUER_ALERT_CARD_CLOSED", + issuerAlertAt: "issuer_alert_at", + hsaFsa: false, + }, + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + card: { + id: "ccof:uIbfJXhXETSP197M3GB", + card_brand: "VISA", + last_4: "1111", + exp_month: BigInt(11), + exp_year: BigInt(2022), + cardholder_name: "Amelia Earhart", + billing_address: { + address_line_1: "500 Electric Ave", + address_line_2: "Suite 600", + address_line_3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "NY", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "10003", + country: "US", + first_name: "first_name", + last_name: "last_name", + }, + fingerprint: "ex-p-cs80EK9Flz7LsCMv-szbptQ_ssAGrhemzSTsPFgt9nzyE6t7okiLIQc-qw_quqKX4Q", + customer_id: "VDKXEEKPJN48QDG3BGGFAK05P8", + merchant_id: "6SSW7HV8K2ST5", + reference_id: "user-id-1", + enabled: true, + card_type: "CREDIT", + prepaid_type: "NOT_PREPAID", + bin: "411111", + version: BigInt(1), + card_co_brand: "UNKNOWN", + issuer_alert: "ISSUER_ALERT_CARD_CLOSED", + issuer_alert_at: "issuer_alert_at", + hsa_fsa: false, + }, + }; + server.mockEndpoint().get("/v2/cards/card_id").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.cards.get({ + cardId: "card_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + card: { + id: "ccof:uIbfJXhXETSP197M3GB", + cardBrand: "VISA", + last4: "1111", + expMonth: BigInt("11"), + expYear: BigInt("2022"), + cardholderName: "Amelia Earhart", + billingAddress: { + addressLine1: "500 Electric Ave", + addressLine2: "Suite 600", + addressLine3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "NY", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "10003", + country: "US", + firstName: "first_name", + lastName: "last_name", + }, + fingerprint: "ex-p-cs80EK9Flz7LsCMv-szbptQ_ssAGrhemzSTsPFgt9nzyE6t7okiLIQc-qw_quqKX4Q", + customerId: "VDKXEEKPJN48QDG3BGGFAK05P8", + merchantId: "6SSW7HV8K2ST5", + referenceId: "user-id-1", + enabled: true, + cardType: "CREDIT", + prepaidType: "NOT_PREPAID", + bin: "411111", + version: BigInt("1"), + cardCoBrand: "UNKNOWN", + issuerAlert: "ISSUER_ALERT_CARD_CLOSED", + issuerAlertAt: "issuer_alert_at", + hsaFsa: false, + }, + }); + }); + + test("disable", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + card: { + id: "ccof:uIbfJXhXETSP197M3GB", + card_brand: "VISA", + last_4: "1111", + exp_month: BigInt(11), + exp_year: BigInt(2022), + cardholder_name: "Amelia Earhart", + billing_address: { + address_line_1: "500 Electric Ave", + address_line_2: "Suite 600", + address_line_3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "NY", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "10003", + country: "US", + first_name: "first_name", + last_name: "last_name", + }, + fingerprint: "ex-p-cs80EK9Flz7LsCMv-szbptQ_ssAGrhemzSTsPFgt9nzyE6t7okiLIQc-qw_quqKX4Q", + customer_id: "VDKXEEKPJN48QDG3BGGFAK05P8", + merchant_id: "6SSW7HV8K2ST5", + reference_id: "user-id-1", + enabled: false, + card_type: "CREDIT", + prepaid_type: "NOT_PREPAID", + bin: "411111", + version: BigInt(2), + card_co_brand: "UNKNOWN", + issuer_alert: "ISSUER_ALERT_CARD_CLOSED", + issuer_alert_at: "issuer_alert_at", + hsa_fsa: false, + }, + }; + server + .mockEndpoint() + .post("/v2/cards/card_id/disable") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.cards.disable({ + cardId: "card_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + card: { + id: "ccof:uIbfJXhXETSP197M3GB", + cardBrand: "VISA", + last4: "1111", + expMonth: BigInt("11"), + expYear: BigInt("2022"), + cardholderName: "Amelia Earhart", + billingAddress: { + addressLine1: "500 Electric Ave", + addressLine2: "Suite 600", + addressLine3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "NY", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "10003", + country: "US", + firstName: "first_name", + lastName: "last_name", + }, + fingerprint: "ex-p-cs80EK9Flz7LsCMv-szbptQ_ssAGrhemzSTsPFgt9nzyE6t7okiLIQc-qw_quqKX4Q", + customerId: "VDKXEEKPJN48QDG3BGGFAK05P8", + merchantId: "6SSW7HV8K2ST5", + referenceId: "user-id-1", + enabled: false, + cardType: "CREDIT", + prepaidType: "NOT_PREPAID", + bin: "411111", + version: BigInt("2"), + cardCoBrand: "UNKNOWN", + issuerAlert: "ISSUER_ALERT_CARD_CLOSED", + issuerAlertAt: "issuer_alert_at", + hsaFsa: false, + }, + }); + }); +}); diff --git a/tests/wire/cashDrawers/shifts.test.ts b/tests/wire/cashDrawers/shifts.test.ts new file mode 100644 index 000000000..fed14a578 --- /dev/null +++ b/tests/wire/cashDrawers/shifts.test.ts @@ -0,0 +1,109 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("Shifts", () => { + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + cash_drawer_shift: { + id: "DCC99978-09A6-4926-849F-300BE9C5793A", + state: "CLOSED", + opened_at: "2019-11-22T00:42:54.000Z", + ended_at: "2019-11-22T00:44:49.000Z", + closed_at: "2019-11-22T00:44:49.000Z", + description: "Misplaced some change", + opened_cash_money: { amount: BigInt(10000), currency: "USD" }, + cash_payment_money: { amount: BigInt(100), currency: "USD" }, + cash_refunds_money: { amount: BigInt(-100), currency: "USD" }, + cash_paid_in_money: { amount: BigInt(10000), currency: "USD" }, + cash_paid_out_money: { amount: BigInt(-10000), currency: "USD" }, + expected_cash_money: { amount: BigInt(10000), currency: "USD" }, + closed_cash_money: { amount: BigInt(9970), currency: "USD" }, + device: { id: "id", name: "My iPad" }, + created_at: "created_at", + updated_at: "updated_at", + location_id: "location_id", + team_member_ids: ["team_member_ids"], + opening_team_member_id: "", + ending_team_member_id: "", + closing_team_member_id: "", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/cash-drawers/shifts/shift_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.cashDrawers.shifts.get({ + shiftId: "shift_id", + locationId: "location_id", + }); + expect(response).toEqual({ + cashDrawerShift: { + id: "DCC99978-09A6-4926-849F-300BE9C5793A", + state: "CLOSED", + openedAt: "2019-11-22T00:42:54.000Z", + endedAt: "2019-11-22T00:44:49.000Z", + closedAt: "2019-11-22T00:44:49.000Z", + description: "Misplaced some change", + openedCashMoney: { + amount: BigInt("10000"), + currency: "USD", + }, + cashPaymentMoney: { + amount: BigInt("100"), + currency: "USD", + }, + cashRefundsMoney: { + amount: BigInt("-100"), + currency: "USD", + }, + cashPaidInMoney: { + amount: BigInt("10000"), + currency: "USD", + }, + cashPaidOutMoney: { + amount: BigInt("-10000"), + currency: "USD", + }, + expectedCashMoney: { + amount: BigInt("10000"), + currency: "USD", + }, + closedCashMoney: { + amount: BigInt("9970"), + currency: "USD", + }, + device: { + id: "id", + name: "My iPad", + }, + createdAt: "created_at", + updatedAt: "updated_at", + locationId: "location_id", + teamMemberIds: ["team_member_ids"], + openingTeamMemberId: "", + endingTeamMemberId: "", + closingTeamMemberId: "", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/catalog.test.ts b/tests/wire/catalog.test.ts new file mode 100644 index 000000000..1e3a5e102 --- /dev/null +++ b/tests/wire/catalog.test.ts @@ -0,0 +1,800 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Catalog", () => { + test("batchDelete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { object_ids: ["W62UWFY35CWMYGVWK6TWJDNI", "AA27W3M2GGTF3H6AVPNB77CK"] }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + deleted_object_ids: ["W62UWFY35CWMYGVWK6TWJDNI", "AA27W3M2GGTF3H6AVPNB77CK"], + deleted_at: "2016-11-16T22:25:24.878Z", + }; + server + .mockEndpoint() + .post("/v2/catalog/batch-delete") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.catalog.batchDelete({ + objectIds: ["W62UWFY35CWMYGVWK6TWJDNI", "AA27W3M2GGTF3H6AVPNB77CK"], + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + deletedObjectIds: ["W62UWFY35CWMYGVWK6TWJDNI", "AA27W3M2GGTF3H6AVPNB77CK"], + deletedAt: "2016-11-16T22:25:24.878Z", + }); + }); + + test("batchGet", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + object_ids: ["W62UWFY35CWMYGVWK6TWJDNI", "AA27W3M2GGTF3H6AVPNB77CK"], + include_related_objects: true, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + objects: [ + { + id: "id", + updated_at: "updated_at", + version: 1000000, + is_deleted: true, + custom_attribute_values: { key: {} }, + catalog_v1_ids: [{}], + present_at_all_locations: true, + present_at_location_ids: ["present_at_location_ids"], + absent_at_location_ids: ["absent_at_location_ids"], + image_id: "image_id", + type: "ITEM", + }, + { + id: "id", + updated_at: "updated_at", + version: 1000000, + is_deleted: true, + custom_attribute_values: { key: {} }, + catalog_v1_ids: [{}], + present_at_all_locations: true, + present_at_location_ids: ["present_at_location_ids"], + absent_at_location_ids: ["absent_at_location_ids"], + image_id: "image_id", + type: "ITEM", + }, + ], + related_objects: [ + { + id: "id", + updated_at: "updated_at", + version: 1000000, + is_deleted: true, + custom_attribute_values: { key: {} }, + catalog_v1_ids: [{}], + present_at_all_locations: true, + present_at_location_ids: ["present_at_location_ids"], + absent_at_location_ids: ["absent_at_location_ids"], + image_id: "image_id", + ordinal: 1000000, + type: "CATEGORY", + }, + { + id: "id", + updated_at: "updated_at", + version: 1000000, + is_deleted: true, + custom_attribute_values: { key: {} }, + catalog_v1_ids: [{}], + present_at_all_locations: true, + present_at_location_ids: ["present_at_location_ids"], + absent_at_location_ids: ["absent_at_location_ids"], + image_id: "image_id", + type: "TAX", + }, + ], + }; + server + .mockEndpoint() + .post("/v2/catalog/batch-retrieve") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.catalog.batchGet({ + objectIds: ["W62UWFY35CWMYGVWK6TWJDNI", "AA27W3M2GGTF3H6AVPNB77CK"], + includeRelatedObjects: true, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + objects: [ + { + type: "ITEM", + id: "id", + updatedAt: "updated_at", + version: BigInt("1000000"), + isDeleted: true, + customAttributeValues: { + key: {}, + }, + catalogV1Ids: [{}], + presentAtAllLocations: true, + presentAtLocationIds: ["present_at_location_ids"], + absentAtLocationIds: ["absent_at_location_ids"], + imageId: "image_id", + }, + { + type: "ITEM", + id: "id", + updatedAt: "updated_at", + version: BigInt("1000000"), + isDeleted: true, + customAttributeValues: { + key: {}, + }, + catalogV1Ids: [{}], + presentAtAllLocations: true, + presentAtLocationIds: ["present_at_location_ids"], + absentAtLocationIds: ["absent_at_location_ids"], + imageId: "image_id", + }, + ], + relatedObjects: [ + { + type: "CATEGORY", + id: "id", + updatedAt: "updated_at", + version: BigInt("1000000"), + isDeleted: true, + customAttributeValues: { + key: {}, + }, + catalogV1Ids: [{}], + presentAtAllLocations: true, + presentAtLocationIds: ["present_at_location_ids"], + absentAtLocationIds: ["absent_at_location_ids"], + imageId: "image_id", + ordinal: BigInt("1000000"), + }, + { + type: "TAX", + id: "id", + updatedAt: "updated_at", + version: BigInt("1000000"), + isDeleted: true, + customAttributeValues: { + key: {}, + }, + catalogV1Ids: [{}], + presentAtAllLocations: true, + presentAtLocationIds: ["present_at_location_ids"], + absentAtLocationIds: ["absent_at_location_ids"], + imageId: "image_id", + }, + ], + }); + }); + + test("batchUpsert", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "789ff020-f723-43a9-b4b5-43b5dc1fa3dc", + batches: [ + { + objects: [ + { id: "id", type: "ITEM" }, + { id: "id", type: "ITEM" }, + { id: "id", type: "ITEM" }, + { id: "id", type: "TAX" }, + ], + }, + ], + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + objects: [ + { + id: "id", + updated_at: "updated_at", + version: 1000000, + is_deleted: true, + custom_attribute_values: { key: {} }, + catalog_v1_ids: [{}], + present_at_all_locations: true, + present_at_location_ids: ["present_at_location_ids"], + absent_at_location_ids: ["absent_at_location_ids"], + image_id: "image_id", + type: "ITEM", + }, + { + id: "id", + updated_at: "updated_at", + version: 1000000, + is_deleted: true, + custom_attribute_values: { key: {} }, + catalog_v1_ids: [{}], + present_at_all_locations: true, + present_at_location_ids: ["present_at_location_ids"], + absent_at_location_ids: ["absent_at_location_ids"], + image_id: "image_id", + type: "ITEM", + }, + { + id: "id", + updated_at: "updated_at", + version: 1000000, + is_deleted: true, + custom_attribute_values: { key: {} }, + catalog_v1_ids: [{}], + present_at_all_locations: true, + present_at_location_ids: ["present_at_location_ids"], + absent_at_location_ids: ["absent_at_location_ids"], + image_id: "image_id", + ordinal: 1000000, + type: "CATEGORY", + }, + { + id: "id", + updated_at: "updated_at", + version: 1000000, + is_deleted: true, + custom_attribute_values: { key: {} }, + catalog_v1_ids: [{}], + present_at_all_locations: true, + present_at_location_ids: ["present_at_location_ids"], + absent_at_location_ids: ["absent_at_location_ids"], + image_id: "image_id", + type: "TAX", + }, + ], + updated_at: "updated_at", + id_mappings: [ + { client_object_id: "#Tea", object_id: "67GA7XA2FWMRYY2VCONTYZJR" }, + { client_object_id: "#Coffee", object_id: "MQ4TZKOG3SR2EQI3TWEK4AH7" }, + { client_object_id: "#Beverages", object_id: "XCS4SCGN4WQYE2VU4U3TKXEH" }, + { client_object_id: "#SalesTax", object_id: "HP5VNYPKZKTNCKZ2Z5NPUH6A" }, + { client_object_id: "#Tea_Mug", object_id: "CAJBHUIQH7ONTSZI2KTVOUP6" }, + { client_object_id: "#Coffee_Regular", object_id: "GY2GXJTVVPQAPW43GFRR3NG6" }, + { client_object_id: "#Coffee_Large", object_id: "JE6VHPSRQL6IWSN26C36CJ7W" }, + ], + }; + server + .mockEndpoint() + .post("/v2/catalog/batch-upsert") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.catalog.batchUpsert({ + idempotencyKey: "789ff020-f723-43a9-b4b5-43b5dc1fa3dc", + batches: [ + { + objects: [ + { + type: "ITEM", + id: "id", + }, + { + type: "ITEM", + id: "id", + }, + { + type: "ITEM", + id: "id", + }, + { + type: "TAX", + id: "id", + }, + ], + }, + ], + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + objects: [ + { + type: "ITEM", + id: "id", + updatedAt: "updated_at", + version: BigInt("1000000"), + isDeleted: true, + customAttributeValues: { + key: {}, + }, + catalogV1Ids: [{}], + presentAtAllLocations: true, + presentAtLocationIds: ["present_at_location_ids"], + absentAtLocationIds: ["absent_at_location_ids"], + imageId: "image_id", + }, + { + type: "ITEM", + id: "id", + updatedAt: "updated_at", + version: BigInt("1000000"), + isDeleted: true, + customAttributeValues: { + key: {}, + }, + catalogV1Ids: [{}], + presentAtAllLocations: true, + presentAtLocationIds: ["present_at_location_ids"], + absentAtLocationIds: ["absent_at_location_ids"], + imageId: "image_id", + }, + { + type: "CATEGORY", + id: "id", + updatedAt: "updated_at", + version: BigInt("1000000"), + isDeleted: true, + customAttributeValues: { + key: {}, + }, + catalogV1Ids: [{}], + presentAtAllLocations: true, + presentAtLocationIds: ["present_at_location_ids"], + absentAtLocationIds: ["absent_at_location_ids"], + imageId: "image_id", + ordinal: BigInt("1000000"), + }, + { + type: "TAX", + id: "id", + updatedAt: "updated_at", + version: BigInt("1000000"), + isDeleted: true, + customAttributeValues: { + key: {}, + }, + catalogV1Ids: [{}], + presentAtAllLocations: true, + presentAtLocationIds: ["present_at_location_ids"], + absentAtLocationIds: ["absent_at_location_ids"], + imageId: "image_id", + }, + ], + updatedAt: "updated_at", + idMappings: [ + { + clientObjectId: "#Tea", + objectId: "67GA7XA2FWMRYY2VCONTYZJR", + }, + { + clientObjectId: "#Coffee", + objectId: "MQ4TZKOG3SR2EQI3TWEK4AH7", + }, + { + clientObjectId: "#Beverages", + objectId: "XCS4SCGN4WQYE2VU4U3TKXEH", + }, + { + clientObjectId: "#SalesTax", + objectId: "HP5VNYPKZKTNCKZ2Z5NPUH6A", + }, + { + clientObjectId: "#Tea_Mug", + objectId: "CAJBHUIQH7ONTSZI2KTVOUP6", + }, + { + clientObjectId: "#Coffee_Regular", + objectId: "GY2GXJTVVPQAPW43GFRR3NG6", + }, + { + clientObjectId: "#Coffee_Large", + objectId: "JE6VHPSRQL6IWSN26C36CJ7W", + }, + ], + }); + }); + + test("info", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + limits: { + batch_upsert_max_objects_per_batch: 1000, + batch_upsert_max_total_objects: 10000, + batch_retrieve_max_object_ids: 1000, + search_max_page_limit: 1000, + batch_delete_max_object_ids: 200, + update_item_taxes_max_item_ids: 1000, + update_item_taxes_max_taxes_to_enable: 1000, + update_item_taxes_max_taxes_to_disable: 1000, + update_item_modifier_lists_max_item_ids: 1000, + update_item_modifier_lists_max_modifier_lists_to_enable: 1000, + update_item_modifier_lists_max_modifier_lists_to_disable: 1000, + }, + standard_unit_description_group: { standard_unit_descriptions: [{}], language_code: "language_code" }, + }; + server.mockEndpoint().get("/v2/catalog/info").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.catalog.info(); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + limits: { + batchUpsertMaxObjectsPerBatch: 1000, + batchUpsertMaxTotalObjects: 10000, + batchRetrieveMaxObjectIds: 1000, + searchMaxPageLimit: 1000, + batchDeleteMaxObjectIds: 200, + updateItemTaxesMaxItemIds: 1000, + updateItemTaxesMaxTaxesToEnable: 1000, + updateItemTaxesMaxTaxesToDisable: 1000, + updateItemModifierListsMaxItemIds: 1000, + updateItemModifierListsMaxModifierListsToEnable: 1000, + updateItemModifierListsMaxModifierListsToDisable: 1000, + }, + standardUnitDescriptionGroup: { + standardUnitDescriptions: [{}], + languageCode: "language_code", + }, + }); + }); + + test("search", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + object_types: ["ITEM"], + query: { prefix_query: { attribute_name: "name", attribute_prefix: "tea" } }, + limit: 100, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + cursor: "cursor", + objects: [ + { + id: "id", + updated_at: "updated_at", + version: 1000000, + is_deleted: true, + custom_attribute_values: { key: {} }, + catalog_v1_ids: [{}], + present_at_all_locations: true, + present_at_location_ids: ["present_at_location_ids"], + absent_at_location_ids: ["absent_at_location_ids"], + image_id: "image_id", + type: "ITEM", + }, + { + id: "id", + updated_at: "updated_at", + version: 1000000, + is_deleted: true, + custom_attribute_values: { key: {} }, + catalog_v1_ids: [{}], + present_at_all_locations: true, + present_at_location_ids: ["present_at_location_ids"], + absent_at_location_ids: ["absent_at_location_ids"], + image_id: "image_id", + type: "ITEM", + }, + ], + related_objects: [ + { + id: "id", + updated_at: "updated_at", + version: 1000000, + is_deleted: true, + custom_attribute_values: { key: {} }, + catalog_v1_ids: [{}], + present_at_all_locations: true, + present_at_location_ids: ["present_at_location_ids"], + absent_at_location_ids: ["absent_at_location_ids"], + image_id: "image_id", + type: "ITEM", + }, + ], + latest_time: "latest_time", + }; + server + .mockEndpoint() + .post("/v2/catalog/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.catalog.search({ + objectTypes: ["ITEM"], + query: { + prefixQuery: { + attributeName: "name", + attributePrefix: "tea", + }, + }, + limit: 100, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + cursor: "cursor", + objects: [ + { + type: "ITEM", + id: "id", + updatedAt: "updated_at", + version: BigInt("1000000"), + isDeleted: true, + customAttributeValues: { + key: {}, + }, + catalogV1Ids: [{}], + presentAtAllLocations: true, + presentAtLocationIds: ["present_at_location_ids"], + absentAtLocationIds: ["absent_at_location_ids"], + imageId: "image_id", + }, + { + type: "ITEM", + id: "id", + updatedAt: "updated_at", + version: BigInt("1000000"), + isDeleted: true, + customAttributeValues: { + key: {}, + }, + catalogV1Ids: [{}], + presentAtAllLocations: true, + presentAtLocationIds: ["present_at_location_ids"], + absentAtLocationIds: ["absent_at_location_ids"], + imageId: "image_id", + }, + ], + relatedObjects: [ + { + type: "ITEM", + id: "id", + updatedAt: "updated_at", + version: BigInt("1000000"), + isDeleted: true, + customAttributeValues: { + key: {}, + }, + catalogV1Ids: [{}], + presentAtAllLocations: true, + presentAtLocationIds: ["present_at_location_ids"], + absentAtLocationIds: ["absent_at_location_ids"], + imageId: "image_id", + }, + ], + latestTime: "latest_time", + }); + }); + + test("SearchItems", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + text_filter: "red", + category_ids: ["WINE_CATEGORY_ID"], + stock_levels: ["OUT", "LOW"], + enabled_location_ids: ["ATL_LOCATION_ID"], + limit: 100, + sort_order: "ASC", + product_types: ["REGULAR"], + custom_attribute_filters: [ + { custom_attribute_definition_id: "VEGAN_DEFINITION_ID", bool_filter: true }, + { custom_attribute_definition_id: "BRAND_DEFINITION_ID", string_filter: "Dark Horse" }, + { key: "VINTAGE", number_filter: { min: "min", max: "max" } }, + { custom_attribute_definition_id: "VARIETAL_DEFINITION_ID" }, + ], + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + items: [ + { + id: "id", + updated_at: "updated_at", + version: 1000000, + is_deleted: true, + custom_attribute_values: { key: {} }, + catalog_v1_ids: [{}], + present_at_all_locations: true, + present_at_location_ids: ["present_at_location_ids"], + absent_at_location_ids: ["absent_at_location_ids"], + image_id: "image_id", + type: "ITEM", + }, + ], + cursor: "cursor", + matched_variation_ids: ["VBJNPHCOKDFECR6VU25WRJUD"], + }; + server + .mockEndpoint() + .post("/v2/catalog/search-catalog-items") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.catalog.searchItems({ + textFilter: "red", + categoryIds: ["WINE_CATEGORY_ID"], + stockLevels: ["OUT", "LOW"], + enabledLocationIds: ["ATL_LOCATION_ID"], + limit: 100, + sortOrder: "ASC", + productTypes: ["REGULAR"], + customAttributeFilters: [ + { + customAttributeDefinitionId: "VEGAN_DEFINITION_ID", + boolFilter: true, + }, + { + customAttributeDefinitionId: "BRAND_DEFINITION_ID", + stringFilter: "Dark Horse", + }, + { + key: "VINTAGE", + numberFilter: { + min: "min", + max: "max", + }, + }, + { + customAttributeDefinitionId: "VARIETAL_DEFINITION_ID", + }, + ], + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + items: [ + { + type: "ITEM", + id: "id", + updatedAt: "updated_at", + version: BigInt("1000000"), + isDeleted: true, + customAttributeValues: { + key: {}, + }, + catalogV1Ids: [{}], + presentAtAllLocations: true, + presentAtLocationIds: ["present_at_location_ids"], + absentAtLocationIds: ["absent_at_location_ids"], + imageId: "image_id", + }, + ], + cursor: "cursor", + matchedVariationIds: ["VBJNPHCOKDFECR6VU25WRJUD"], + }); + }); + + test("UpdateItemModifierLists", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + item_ids: ["H42BRLUJ5KTZTTMPVSLFAACQ", "2JXOBJIHCWBQ4NZ3RIXQGJA6"], + modifier_lists_to_enable: ["H42BRLUJ5KTZTTMPVSLFAACQ", "2JXOBJIHCWBQ4NZ3RIXQGJA6"], + modifier_lists_to_disable: ["7WRC16CJZDVLSNDQ35PP6YAD"], + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + updated_at: "2016-11-16T22:25:24.878Z", + }; + server + .mockEndpoint() + .post("/v2/catalog/update-item-modifier-lists") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.catalog.updateItemModifierLists({ + itemIds: ["H42BRLUJ5KTZTTMPVSLFAACQ", "2JXOBJIHCWBQ4NZ3RIXQGJA6"], + modifierListsToEnable: ["H42BRLUJ5KTZTTMPVSLFAACQ", "2JXOBJIHCWBQ4NZ3RIXQGJA6"], + modifierListsToDisable: ["7WRC16CJZDVLSNDQ35PP6YAD"], + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + updatedAt: "2016-11-16T22:25:24.878Z", + }); + }); + + test("UpdateItemTaxes", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + item_ids: ["H42BRLUJ5KTZTTMPVSLFAACQ", "2JXOBJIHCWBQ4NZ3RIXQGJA6"], + taxes_to_enable: ["4WRCNHCJZDVLSNDQ35PP6YAD"], + taxes_to_disable: ["AQCEGCEBBQONINDOHRGZISEX"], + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + updated_at: "2016-11-16T22:25:24.878Z", + }; + server + .mockEndpoint() + .post("/v2/catalog/update-item-taxes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.catalog.updateItemTaxes({ + itemIds: ["H42BRLUJ5KTZTTMPVSLFAACQ", "2JXOBJIHCWBQ4NZ3RIXQGJA6"], + taxesToEnable: ["4WRCNHCJZDVLSNDQ35PP6YAD"], + taxesToDisable: ["AQCEGCEBBQONINDOHRGZISEX"], + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + updatedAt: "2016-11-16T22:25:24.878Z", + }); + }); +}); diff --git a/tests/wire/catalog/object.test.ts b/tests/wire/catalog/object.test.ts new file mode 100644 index 000000000..3b3a58854 --- /dev/null +++ b/tests/wire/catalog/object.test.ts @@ -0,0 +1,343 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("Object_", () => { + test("upsert", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "af3d1afc-7212-4300-b463-0bfc5314a5ae", + object: { id: "id", type: "ITEM" }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + catalog_object: { + id: "id", + updated_at: "updated_at", + version: 1000000, + is_deleted: true, + custom_attribute_values: { key: {} }, + catalog_v1_ids: [{}], + present_at_all_locations: true, + present_at_location_ids: ["present_at_location_ids"], + absent_at_location_ids: ["absent_at_location_ids"], + image_id: "image_id", + item_data: { + name: "name", + description: "description", + abbreviation: "abbreviation", + label_color: "label_color", + is_taxable: true, + category_id: "category_id", + tax_ids: ["tax_ids"], + modifier_list_info: [{ modifier_list_id: "modifier_list_id" }], + product_type: "REGULAR", + skip_modifier_screen: true, + item_options: [{}], + ecom_uri: "ecom_uri", + ecom_image_uris: ["ecom_image_uris"], + image_ids: ["image_ids"], + sort_name: "sort_name", + description_html: "description_html", + description_plaintext: "description_plaintext", + channels: ["channels"], + is_archived: true, + is_alcoholic: true, + }, + type: "ITEM", + }, + id_mappings: [ + { client_object_id: "#Cocoa", object_id: "R2TA2FOBUGCJZNIWJSOSNAI4" }, + { client_object_id: "#Small", object_id: "QRT53UP4LITLWGOGBZCUWP63" }, + { client_object_id: "#Large", object_id: "NS77DKEIQ3AEQTCP727DSA7U" }, + ], + }; + server + .mockEndpoint() + .post("/v2/catalog/object") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.catalog.object.upsert({ + idempotencyKey: "af3d1afc-7212-4300-b463-0bfc5314a5ae", + object: { + type: "ITEM", + id: "id", + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + catalogObject: { + type: "ITEM", + id: "id", + updatedAt: "updated_at", + version: BigInt("1000000"), + isDeleted: true, + customAttributeValues: { + key: {}, + }, + catalogV1Ids: [{}], + presentAtAllLocations: true, + presentAtLocationIds: ["present_at_location_ids"], + absentAtLocationIds: ["absent_at_location_ids"], + imageId: "image_id", + itemData: { + name: "name", + description: "description", + abbreviation: "abbreviation", + labelColor: "label_color", + isTaxable: true, + categoryId: "category_id", + taxIds: ["tax_ids"], + modifierListInfo: [ + { + modifierListId: "modifier_list_id", + }, + ], + productType: "REGULAR", + skipModifierScreen: true, + itemOptions: [{}], + ecomUri: "ecom_uri", + ecomImageUris: ["ecom_image_uris"], + imageIds: ["image_ids"], + sortName: "sort_name", + descriptionHtml: "description_html", + descriptionPlaintext: "description_plaintext", + channels: ["channels"], + isArchived: true, + isAlcoholic: true, + }, + }, + idMappings: [ + { + clientObjectId: "#Cocoa", + objectId: "R2TA2FOBUGCJZNIWJSOSNAI4", + }, + { + clientObjectId: "#Small", + objectId: "QRT53UP4LITLWGOGBZCUWP63", + }, + { + clientObjectId: "#Large", + objectId: "NS77DKEIQ3AEQTCP727DSA7U", + }, + ], + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + object: { + id: "id", + updated_at: "updated_at", + version: 1000000, + is_deleted: true, + custom_attribute_values: { key: {} }, + catalog_v1_ids: [{}], + present_at_all_locations: true, + present_at_location_ids: ["present_at_location_ids"], + absent_at_location_ids: ["absent_at_location_ids"], + image_id: "image_id", + item_data: { + name: "name", + description: "description", + abbreviation: "abbreviation", + label_color: "label_color", + is_taxable: true, + category_id: "category_id", + tax_ids: ["tax_ids"], + modifier_list_info: [{ modifier_list_id: "modifier_list_id" }], + product_type: "REGULAR", + skip_modifier_screen: true, + item_options: [{}], + ecom_uri: "ecom_uri", + ecom_image_uris: ["ecom_image_uris"], + image_ids: ["image_ids"], + sort_name: "sort_name", + description_html: "description_html", + description_plaintext: "description_plaintext", + channels: ["channels"], + is_archived: true, + is_alcoholic: true, + }, + type: "ITEM", + }, + related_objects: [ + { + id: "id", + updated_at: "updated_at", + version: 1000000, + is_deleted: true, + custom_attribute_values: { key: {} }, + catalog_v1_ids: [{}], + present_at_all_locations: true, + present_at_location_ids: ["present_at_location_ids"], + absent_at_location_ids: ["absent_at_location_ids"], + image_id: "image_id", + ordinal: 1000000, + type: "CATEGORY", + }, + { + id: "id", + updated_at: "updated_at", + version: 1000000, + is_deleted: true, + custom_attribute_values: { key: {} }, + catalog_v1_ids: [{}], + present_at_all_locations: true, + present_at_location_ids: ["present_at_location_ids"], + absent_at_location_ids: ["absent_at_location_ids"], + image_id: "image_id", + type: "TAX", + }, + ], + }; + server + .mockEndpoint() + .get("/v2/catalog/object/object_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.catalog.object.get({ + objectId: "object_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + object: { + type: "ITEM", + id: "id", + updatedAt: "updated_at", + version: BigInt("1000000"), + isDeleted: true, + customAttributeValues: { + key: {}, + }, + catalogV1Ids: [{}], + presentAtAllLocations: true, + presentAtLocationIds: ["present_at_location_ids"], + absentAtLocationIds: ["absent_at_location_ids"], + imageId: "image_id", + itemData: { + name: "name", + description: "description", + abbreviation: "abbreviation", + labelColor: "label_color", + isTaxable: true, + categoryId: "category_id", + taxIds: ["tax_ids"], + modifierListInfo: [ + { + modifierListId: "modifier_list_id", + }, + ], + productType: "REGULAR", + skipModifierScreen: true, + itemOptions: [{}], + ecomUri: "ecom_uri", + ecomImageUris: ["ecom_image_uris"], + imageIds: ["image_ids"], + sortName: "sort_name", + descriptionHtml: "description_html", + descriptionPlaintext: "description_plaintext", + channels: ["channels"], + isArchived: true, + isAlcoholic: true, + }, + }, + relatedObjects: [ + { + type: "CATEGORY", + id: "id", + updatedAt: "updated_at", + version: BigInt("1000000"), + isDeleted: true, + customAttributeValues: { + key: {}, + }, + catalogV1Ids: [{}], + presentAtAllLocations: true, + presentAtLocationIds: ["present_at_location_ids"], + absentAtLocationIds: ["absent_at_location_ids"], + imageId: "image_id", + ordinal: BigInt("1000000"), + }, + { + type: "TAX", + id: "id", + updatedAt: "updated_at", + version: BigInt("1000000"), + isDeleted: true, + customAttributeValues: { + key: {}, + }, + catalogV1Ids: [{}], + presentAtAllLocations: true, + presentAtLocationIds: ["present_at_location_ids"], + absentAtLocationIds: ["absent_at_location_ids"], + imageId: "image_id", + }, + ], + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + deleted_object_ids: ["7SB3ZQYJ5GDMVFL7JK46JCHT", "KQLFFHA6K6J3YQAQAWDQAL57"], + deleted_at: "2016-11-16T22:25:24.878Z", + }; + server + .mockEndpoint() + .delete("/v2/catalog/object/object_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.catalog.object.delete({ + objectId: "object_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + deletedObjectIds: ["7SB3ZQYJ5GDMVFL7JK46JCHT", "KQLFFHA6K6J3YQAQAWDQAL57"], + deletedAt: "2016-11-16T22:25:24.878Z", + }); + }); +}); diff --git a/tests/wire/checkout.test.ts b/tests/wire/checkout.test.ts new file mode 100644 index 000000000..cc8b24538 --- /dev/null +++ b/tests/wire/checkout.test.ts @@ -0,0 +1,325 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Checkout", () => { + test("RetrieveLocationSettings", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + location_settings: { + location_id: "LOCATION_ID_1", + customer_notes_enabled: true, + policies: [{ uid: "POLICY_ID_1", title: "Return Policy", description: "This is my Return Policy" }], + branding: { header_type: "FRAMED_LOGO", button_color: "#ffffff", button_shape: "ROUNDED" }, + tipping: { + percentages: [10, 15, 20], + smart_tipping_enabled: true, + default_percent: 15, + smart_tips: [{}], + }, + coupons: { enabled: true }, + updated_at: "2022-06-16T22:25:35Z", + }, + }; + server + .mockEndpoint() + .get("/v2/online-checkout/location-settings/location_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.checkout.retrieveLocationSettings({ + locationId: "location_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + locationSettings: { + locationId: "LOCATION_ID_1", + customerNotesEnabled: true, + policies: [ + { + uid: "POLICY_ID_1", + title: "Return Policy", + description: "This is my Return Policy", + }, + ], + branding: { + headerType: "FRAMED_LOGO", + buttonColor: "#ffffff", + buttonShape: "ROUNDED", + }, + tipping: { + percentages: [10, 15, 20], + smartTippingEnabled: true, + defaultPercent: 15, + smartTips: [{}], + }, + coupons: { + enabled: true, + }, + updatedAt: "2022-06-16T22:25:35Z", + }, + }); + }); + + test("UpdateLocationSettings", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { location_settings: {} }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + location_settings: { + location_id: "LOCATION_ID_1", + customer_notes_enabled: false, + policies: [ + { uid: "POLICY_ID_1", title: "Return Policy", description: "This is my Return Policy" }, + { + uid: "POLICY_ID_2", + title: "Return Policy", + description: "Items may be returned within 30 days of purchase.", + }, + ], + branding: { header_type: "FRAMED_LOGO", button_color: "#00b23b", button_shape: "ROUNDED" }, + tipping: { + percentages: [15, 20, 25], + smart_tipping_enabled: true, + default_percent: 20, + smart_tips: [{}], + }, + coupons: { enabled: true }, + updated_at: "2022-06-16T22:25:35Z", + }, + }; + server + .mockEndpoint() + .put("/v2/online-checkout/location-settings/location_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.checkout.updateLocationSettings({ + locationId: "location_id", + locationSettings: {}, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + locationSettings: { + locationId: "LOCATION_ID_1", + customerNotesEnabled: false, + policies: [ + { + uid: "POLICY_ID_1", + title: "Return Policy", + description: "This is my Return Policy", + }, + { + uid: "POLICY_ID_2", + title: "Return Policy", + description: "Items may be returned within 30 days of purchase.", + }, + ], + branding: { + headerType: "FRAMED_LOGO", + buttonColor: "#00b23b", + buttonShape: "ROUNDED", + }, + tipping: { + percentages: [15, 20, 25], + smartTippingEnabled: true, + defaultPercent: 20, + smartTips: [{}], + }, + coupons: { + enabled: true, + }, + updatedAt: "2022-06-16T22:25:35Z", + }, + }); + }); + + test("RetrieveMerchantSettings", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + merchant_settings: { + payment_methods: { + apple_pay: { enabled: true }, + google_pay: { enabled: true }, + afterpay_clearpay: { + order_eligibility_range: { + min: { amount: BigInt(100), currency: "USD" }, + max: { amount: BigInt(10000), currency: "USD" }, + }, + item_eligibility_range: { + min: { amount: BigInt(100), currency: "USD" }, + max: { amount: BigInt(10000), currency: "USD" }, + }, + enabled: true, + }, + }, + updated_at: "2022-06-16T22:25:35Z", + }, + }; + server + .mockEndpoint() + .get("/v2/online-checkout/merchant-settings") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.checkout.retrieveMerchantSettings(); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + merchantSettings: { + paymentMethods: { + applePay: { + enabled: true, + }, + googlePay: { + enabled: true, + }, + afterpayClearpay: { + orderEligibilityRange: { + min: { + amount: BigInt("100"), + currency: "USD", + }, + max: { + amount: BigInt("10000"), + currency: "USD", + }, + }, + itemEligibilityRange: { + min: { + amount: BigInt("100"), + currency: "USD", + }, + max: { + amount: BigInt("10000"), + currency: "USD", + }, + }, + enabled: true, + }, + }, + updatedAt: "2022-06-16T22:25:35Z", + }, + }); + }); + + test("UpdateMerchantSettings", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { merchant_settings: {} }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + merchant_settings: { + payment_methods: { + apple_pay: { enabled: false }, + google_pay: { enabled: true }, + afterpay_clearpay: { + order_eligibility_range: { + min: { amount: BigInt(100), currency: "USD" }, + max: { amount: BigInt(10000), currency: "USD" }, + }, + item_eligibility_range: { + min: { amount: BigInt(100), currency: "USD" }, + max: { amount: BigInt(10000), currency: "USD" }, + }, + enabled: true, + }, + }, + updated_at: "2022-06-16T22:25:35Z", + }, + }; + server + .mockEndpoint() + .put("/v2/online-checkout/merchant-settings") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.checkout.updateMerchantSettings({ + merchantSettings: {}, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + merchantSettings: { + paymentMethods: { + applePay: { + enabled: false, + }, + googlePay: { + enabled: true, + }, + afterpayClearpay: { + orderEligibilityRange: { + min: { + amount: BigInt("100"), + currency: "USD", + }, + max: { + amount: BigInt("10000"), + currency: "USD", + }, + }, + itemEligibilityRange: { + min: { + amount: BigInt("100"), + currency: "USD", + }, + max: { + amount: BigInt("10000"), + currency: "USD", + }, + }, + enabled: true, + }, + }, + updatedAt: "2022-06-16T22:25:35Z", + }, + }); + }); +}); diff --git a/tests/wire/checkout/paymentLinks.test.ts b/tests/wire/checkout/paymentLinks.test.ts new file mode 100644 index 000000000..8710b2721 --- /dev/null +++ b/tests/wire/checkout/paymentLinks.test.ts @@ -0,0 +1,463 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("PaymentLinks", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "cd9e25dc-d9f2-4430-aedb-61605070e95f", + quick_pay: { + name: "Auto Detailing", + price_money: { amount: BigInt(10000), currency: "USD" }, + location_id: "A9Y43N9ABXZBP", + }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + payment_link: { + id: "PKVT6XGJZXYUP3NZ", + version: 1, + description: "description", + order_id: "o4b7saqp4HzhNttf5AJxC0Srjd4F", + checkout_options: { + allow_tipping: true, + custom_fields: [{ title: "title" }], + subscription_plan_id: "subscription_plan_id", + redirect_url: "redirect_url", + merchant_support_email: "merchant_support_email", + ask_for_shipping_address: true, + shipping_fee: { charge: {} }, + enable_coupon: true, + enable_loyalty: true, + }, + pre_populated_data: { buyer_email: "buyer_email", buyer_phone_number: "buyer_phone_number" }, + url: "https://square.link/u/EXAMPLE", + long_url: "https://checkout.square.site/EXAMPLE", + created_at: "2022-04-25T23:58:01Z", + updated_at: "updated_at", + payment_note: "payment_note", + }, + related_resources: { + orders: [ + { + id: "o4b7saqp4HzhNttf5AJxC0Srjd4F", + location_id: "{LOCATION_ID}", + source: { name: "Test Online Checkout Application" }, + line_items: [ + { + uid: "8YX13D1U3jO7czP8JVrAR", + name: "Auto Detailing", + quantity: "1", + item_type: "ITEM", + base_price_money: { amount: BigInt(12500), currency: "USD" }, + variation_total_price_money: { amount: BigInt(12500), currency: "USD" }, + gross_sales_money: { amount: BigInt(12500), currency: "USD" }, + total_tax_money: { amount: BigInt(0), currency: "USD" }, + total_discount_money: { amount: BigInt(0), currency: "USD" }, + total_money: { amount: BigInt(12500), currency: "USD" }, + }, + ], + fulfillments: [{ uid: "bBpNrxjdQxGQP16sTmdzi", type: "PICKUP", state: "PROPOSED" }], + net_amounts: { + total_money: { amount: BigInt(12500), currency: "USD" }, + tax_money: { amount: BigInt(0), currency: "USD" }, + discount_money: { amount: BigInt(0), currency: "USD" }, + tip_money: { amount: BigInt(0), currency: "USD" }, + service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + created_at: "2022-03-03T00:53:15.829Z", + updated_at: "2022-03-03T00:53:15.829Z", + state: "DRAFT", + version: 1, + total_money: { amount: BigInt(12500), currency: "USD" }, + total_tax_money: { amount: BigInt(0), currency: "USD" }, + total_discount_money: { amount: BigInt(0), currency: "USD" }, + total_tip_money: { amount: BigInt(0), currency: "USD" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + ], + subscription_plans: [{ id: "id", type: "ITEM" }], + }, + }; + server + .mockEndpoint() + .post("/v2/online-checkout/payment-links") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.checkout.paymentLinks.create({ + idempotencyKey: "cd9e25dc-d9f2-4430-aedb-61605070e95f", + quickPay: { + name: "Auto Detailing", + priceMoney: { + amount: BigInt("10000"), + currency: "USD", + }, + locationId: "A9Y43N9ABXZBP", + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + paymentLink: { + id: "PKVT6XGJZXYUP3NZ", + version: 1, + description: "description", + orderId: "o4b7saqp4HzhNttf5AJxC0Srjd4F", + checkoutOptions: { + allowTipping: true, + customFields: [ + { + title: "title", + }, + ], + subscriptionPlanId: "subscription_plan_id", + redirectUrl: "redirect_url", + merchantSupportEmail: "merchant_support_email", + askForShippingAddress: true, + shippingFee: { + charge: {}, + }, + enableCoupon: true, + enableLoyalty: true, + }, + prePopulatedData: { + buyerEmail: "buyer_email", + buyerPhoneNumber: "buyer_phone_number", + }, + url: "https://square.link/u/EXAMPLE", + longUrl: "https://checkout.square.site/EXAMPLE", + createdAt: "2022-04-25T23:58:01Z", + updatedAt: "updated_at", + paymentNote: "payment_note", + }, + relatedResources: { + orders: [ + { + id: "o4b7saqp4HzhNttf5AJxC0Srjd4F", + locationId: "{LOCATION_ID}", + source: { + name: "Test Online Checkout Application", + }, + lineItems: [ + { + uid: "8YX13D1U3jO7czP8JVrAR", + name: "Auto Detailing", + quantity: "1", + itemType: "ITEM", + basePriceMoney: { + amount: BigInt("12500"), + currency: "USD", + }, + variationTotalPriceMoney: { + amount: BigInt("12500"), + currency: "USD", + }, + grossSalesMoney: { + amount: BigInt("12500"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("12500"), + currency: "USD", + }, + }, + ], + fulfillments: [ + { + uid: "bBpNrxjdQxGQP16sTmdzi", + type: "PICKUP", + state: "PROPOSED", + }, + ], + netAmounts: { + totalMoney: { + amount: BigInt("12500"), + currency: "USD", + }, + taxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + discountMoney: { + amount: BigInt("0"), + currency: "USD", + }, + tipMoney: { + amount: BigInt("0"), + currency: "USD", + }, + serviceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + createdAt: "2022-03-03T00:53:15.829Z", + updatedAt: "2022-03-03T00:53:15.829Z", + state: "DRAFT", + version: 1, + totalMoney: { + amount: BigInt("12500"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalTipMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + ], + subscriptionPlans: [ + { + type: "ITEM", + id: "id", + }, + ], + }, + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + payment_link: { + id: "LLO5Q3FRCFICDB4B", + version: 1, + description: "description", + order_id: "4uKASDATqSd1QQ9jV86sPhMdVEbSJc4F", + checkout_options: { + allow_tipping: true, + custom_fields: [{ title: "title" }], + subscription_plan_id: "subscription_plan_id", + redirect_url: "redirect_url", + merchant_support_email: "merchant_support_email", + ask_for_shipping_address: true, + shipping_fee: { charge: {} }, + enable_coupon: true, + enable_loyalty: true, + }, + pre_populated_data: { buyer_email: "buyer_email", buyer_phone_number: "buyer_phone_number" }, + url: "https://square.link/u/EXAMPLE", + long_url: "https://checkout.square.site/EXAMPLE", + created_at: "2022-04-26T00:10:29Z", + updated_at: "updated_at", + payment_note: "payment_note", + }, + }; + server + .mockEndpoint() + .get("/v2/online-checkout/payment-links/id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.checkout.paymentLinks.get({ + id: "id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + paymentLink: { + id: "LLO5Q3FRCFICDB4B", + version: 1, + description: "description", + orderId: "4uKASDATqSd1QQ9jV86sPhMdVEbSJc4F", + checkoutOptions: { + allowTipping: true, + customFields: [ + { + title: "title", + }, + ], + subscriptionPlanId: "subscription_plan_id", + redirectUrl: "redirect_url", + merchantSupportEmail: "merchant_support_email", + askForShippingAddress: true, + shippingFee: { + charge: {}, + }, + enableCoupon: true, + enableLoyalty: true, + }, + prePopulatedData: { + buyerEmail: "buyer_email", + buyerPhoneNumber: "buyer_phone_number", + }, + url: "https://square.link/u/EXAMPLE", + longUrl: "https://checkout.square.site/EXAMPLE", + createdAt: "2022-04-26T00:10:29Z", + updatedAt: "updated_at", + paymentNote: "payment_note", + }, + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { payment_link: { version: 1, checkout_options: { ask_for_shipping_address: true } } }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + payment_link: { + id: "TY4BWEDJ6AI5MBIV", + version: 2, + description: "description", + order_id: "Qqc8ypQGvxVwc46Cch4zHTaJqc4F", + checkout_options: { + allow_tipping: true, + custom_fields: [{ title: "title" }], + subscription_plan_id: "subscription_plan_id", + redirect_url: "redirect_url", + merchant_support_email: "merchant_support_email", + ask_for_shipping_address: true, + shipping_fee: { charge: {} }, + enable_coupon: true, + enable_loyalty: true, + }, + pre_populated_data: { buyer_email: "buyer_email", buyer_phone_number: "buyer_phone_number" }, + url: "https://square.link/u/EXAMPLE", + long_url: "https://checkout.square.site/EXAMPLE", + created_at: "2022-04-26T00:15:15Z", + updated_at: "2022-04-26T00:18:24Z", + payment_note: "test", + }, + }; + server + .mockEndpoint() + .put("/v2/online-checkout/payment-links/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.checkout.paymentLinks.update({ + id: "id", + paymentLink: { + version: 1, + checkoutOptions: { + askForShippingAddress: true, + }, + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + paymentLink: { + id: "TY4BWEDJ6AI5MBIV", + version: 2, + description: "description", + orderId: "Qqc8ypQGvxVwc46Cch4zHTaJqc4F", + checkoutOptions: { + allowTipping: true, + customFields: [ + { + title: "title", + }, + ], + subscriptionPlanId: "subscription_plan_id", + redirectUrl: "redirect_url", + merchantSupportEmail: "merchant_support_email", + askForShippingAddress: true, + shippingFee: { + charge: {}, + }, + enableCoupon: true, + enableLoyalty: true, + }, + prePopulatedData: { + buyerEmail: "buyer_email", + buyerPhoneNumber: "buyer_phone_number", + }, + url: "https://square.link/u/EXAMPLE", + longUrl: "https://checkout.square.site/EXAMPLE", + createdAt: "2022-04-26T00:15:15Z", + updatedAt: "2022-04-26T00:18:24Z", + paymentNote: "test", + }, + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + id: "MQASNYL6QB6DFCJ3", + cancelled_order_id: "asx8LgZ6MRzD0fObfkJ6obBmSh4F", + }; + server + .mockEndpoint() + .delete("/v2/online-checkout/payment-links/id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.checkout.paymentLinks.delete({ + id: "id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + id: "MQASNYL6QB6DFCJ3", + cancelledOrderId: "asx8LgZ6MRzD0fObfkJ6obBmSh4F", + }); + }); +}); diff --git a/tests/wire/customers.test.ts b/tests/wire/customers.test.ts new file mode 100644 index 000000000..21fdb5b60 --- /dev/null +++ b/tests/wire/customers.test.ts @@ -0,0 +1,1121 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Customers", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + given_name: "Amelia", + family_name: "Earhart", + email_address: "Amelia.Earhart@example.com", + address: { + address_line_1: "500 Electric Ave", + address_line_2: "Suite 600", + locality: "New York", + administrative_district_level_1: "NY", + postal_code: "10003", + country: "US", + }, + phone_number: "+1-212-555-4240", + reference_id: "YOUR_REFERENCE_ID", + note: "a customer", + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + customer: { + id: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + created_at: "2016-03-23T20:21:54.859Z", + updated_at: "2016-03-23T20:21:54.859Z", + given_name: "Amelia", + family_name: "Earhart", + nickname: "nickname", + company_name: "company_name", + email_address: "Amelia.Earhart@example.com", + address: { + address_line_1: "500 Electric Ave", + address_line_2: "Suite 600", + address_line_3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "NY", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "10003", + country: "US", + first_name: "first_name", + last_name: "last_name", + }, + phone_number: "+1-212-555-4240", + birthday: "birthday", + reference_id: "YOUR_REFERENCE_ID", + note: "a customer", + preferences: { email_unsubscribed: false }, + creation_source: "THIRD_PARTY", + group_ids: ["group_ids"], + segment_ids: ["segment_ids"], + version: BigInt(0), + tax_ids: { eu_vat: "eu_vat" }, + }, + }; + server + .mockEndpoint() + .post("/v2/customers") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.create({ + givenName: "Amelia", + familyName: "Earhart", + emailAddress: "Amelia.Earhart@example.com", + address: { + addressLine1: "500 Electric Ave", + addressLine2: "Suite 600", + locality: "New York", + administrativeDistrictLevel1: "NY", + postalCode: "10003", + country: "US", + }, + phoneNumber: "+1-212-555-4240", + referenceId: "YOUR_REFERENCE_ID", + note: "a customer", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + customer: { + id: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + createdAt: "2016-03-23T20:21:54.859Z", + updatedAt: "2016-03-23T20:21:54.859Z", + givenName: "Amelia", + familyName: "Earhart", + nickname: "nickname", + companyName: "company_name", + emailAddress: "Amelia.Earhart@example.com", + address: { + addressLine1: "500 Electric Ave", + addressLine2: "Suite 600", + addressLine3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "NY", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "10003", + country: "US", + firstName: "first_name", + lastName: "last_name", + }, + phoneNumber: "+1-212-555-4240", + birthday: "birthday", + referenceId: "YOUR_REFERENCE_ID", + note: "a customer", + preferences: { + emailUnsubscribed: false, + }, + creationSource: "THIRD_PARTY", + groupIds: ["group_ids"], + segmentIds: ["segment_ids"], + version: BigInt("0"), + taxIds: { + euVat: "eu_vat", + }, + }, + }); + }); + + test("batchCreate", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + customers: { + "8bb76c4f-e35d-4c5b-90de-1194cd9179f0": { + given_name: "Amelia", + family_name: "Earhart", + email_address: "Amelia.Earhart@example.com", + address: { + address_line_1: "500 Electric Ave", + address_line_2: "Suite 600", + locality: "New York", + administrative_district_level_1: "NY", + postal_code: "10003", + country: "US", + }, + phone_number: "+1-212-555-4240", + reference_id: "YOUR_REFERENCE_ID", + note: "a customer", + }, + "d1689f23-b25d-4932-b2f0-aed00f5e2029": { + given_name: "Marie", + family_name: "Curie", + email_address: "Marie.Curie@example.com", + address: { + address_line_1: "500 Electric Ave", + address_line_2: "Suite 601", + locality: "New York", + administrative_district_level_1: "NY", + postal_code: "10003", + country: "US", + }, + phone_number: "+1-212-444-4240", + reference_id: "YOUR_REFERENCE_ID", + note: "another customer", + }, + }, + }; + const rawResponseBody = { + responses: { + "8bb76c4f-e35d-4c5b-90de-1194cd9179f4": { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + customer: { + id: "8DDA5NZVBZFGAX0V3HPF81HHE0", + created_at: "2024-03-23T20:21:54.859Z", + updated_at: "2024-03-23T20:21:54.859Z", + given_name: "Amelia", + family_name: "Earhart", + email_address: "Amelia.Earhart@example.com", + address: { + address_line_1: "500 Electric Ave", + address_line_2: "Suite 600", + locality: "New York", + administrative_district_level_1: "NY", + postal_code: "10003", + country: "US", + }, + phone_number: "+1-212-555-4240", + reference_id: "YOUR_REFERENCE_ID", + note: "a customer", + preferences: { email_unsubscribed: false }, + creation_source: "THIRD_PARTY", + version: BigInt(0), + }, + }, + "d1689f23-b25d-4932-b2f0-aed00f5e2029": { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + customer: { + id: "N18CPRVXR5214XPBBA6BZQWF3C", + created_at: "2024-03-23T20:21:54.859Z", + updated_at: "2024-03-23T20:21:54.859Z", + given_name: "Marie", + family_name: "Curie", + email_address: "Marie.Curie@example.com", + address: { + address_line_1: "500 Electric Ave", + address_line_2: "Suite 601", + locality: "New York", + administrative_district_level_1: "NY", + postal_code: "10003", + country: "US", + }, + phone_number: "+1-212-444-4240", + reference_id: "YOUR_REFERENCE_ID", + note: "another customer", + preferences: { email_unsubscribed: false }, + creation_source: "THIRD_PARTY", + version: BigInt(0), + }, + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/customers/bulk-create") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.batchCreate({ + customers: { + "8bb76c4f-e35d-4c5b-90de-1194cd9179f0": { + givenName: "Amelia", + familyName: "Earhart", + emailAddress: "Amelia.Earhart@example.com", + address: { + addressLine1: "500 Electric Ave", + addressLine2: "Suite 600", + locality: "New York", + administrativeDistrictLevel1: "NY", + postalCode: "10003", + country: "US", + }, + phoneNumber: "+1-212-555-4240", + referenceId: "YOUR_REFERENCE_ID", + note: "a customer", + }, + "d1689f23-b25d-4932-b2f0-aed00f5e2029": { + givenName: "Marie", + familyName: "Curie", + emailAddress: "Marie.Curie@example.com", + address: { + addressLine1: "500 Electric Ave", + addressLine2: "Suite 601", + locality: "New York", + administrativeDistrictLevel1: "NY", + postalCode: "10003", + country: "US", + }, + phoneNumber: "+1-212-444-4240", + referenceId: "YOUR_REFERENCE_ID", + note: "another customer", + }, + }, + }); + expect(response).toEqual({ + responses: { + "8bb76c4f-e35d-4c5b-90de-1194cd9179f4": { + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + customer: { + id: "8DDA5NZVBZFGAX0V3HPF81HHE0", + createdAt: "2024-03-23T20:21:54.859Z", + updatedAt: "2024-03-23T20:21:54.859Z", + givenName: "Amelia", + familyName: "Earhart", + emailAddress: "Amelia.Earhart@example.com", + address: { + addressLine1: "500 Electric Ave", + addressLine2: "Suite 600", + locality: "New York", + administrativeDistrictLevel1: "NY", + postalCode: "10003", + country: "US", + }, + phoneNumber: "+1-212-555-4240", + referenceId: "YOUR_REFERENCE_ID", + note: "a customer", + preferences: { + emailUnsubscribed: false, + }, + creationSource: "THIRD_PARTY", + version: BigInt("0"), + }, + }, + "d1689f23-b25d-4932-b2f0-aed00f5e2029": { + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + customer: { + id: "N18CPRVXR5214XPBBA6BZQWF3C", + createdAt: "2024-03-23T20:21:54.859Z", + updatedAt: "2024-03-23T20:21:54.859Z", + givenName: "Marie", + familyName: "Curie", + emailAddress: "Marie.Curie@example.com", + address: { + addressLine1: "500 Electric Ave", + addressLine2: "Suite 601", + locality: "New York", + administrativeDistrictLevel1: "NY", + postalCode: "10003", + country: "US", + }, + phoneNumber: "+1-212-444-4240", + referenceId: "YOUR_REFERENCE_ID", + note: "another customer", + preferences: { + emailUnsubscribed: false, + }, + creationSource: "THIRD_PARTY", + version: BigInt("0"), + }, + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("BulkDeleteCustomers", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + customer_ids: ["8DDA5NZVBZFGAX0V3HPF81HHE0", "N18CPRVXR5214XPBBA6BZQWF3C", "2GYD7WNXF7BJZW1PMGNXZ3Y8M8"], + }; + const rawResponseBody = { + responses: { + "2GYD7WNXF7BJZW1PMGNXZ3Y8M8": { + errors: [ + { + category: "INVALID_REQUEST_ERROR", + code: "NOT_FOUND", + detail: "Customer with ID `2GYD7WNXF7BJZW1PMGNXZ3Y8M8` not found.", + }, + ], + }, + "8DDA5NZVBZFGAX0V3HPF81HHE0": { errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }] }, + N18CPRVXR5214XPBBA6BZQWF3C: { errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }] }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/customers/bulk-delete") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.bulkDeleteCustomers({ + customerIds: ["8DDA5NZVBZFGAX0V3HPF81HHE0", "N18CPRVXR5214XPBBA6BZQWF3C", "2GYD7WNXF7BJZW1PMGNXZ3Y8M8"], + }); + expect(response).toEqual({ + responses: { + "2GYD7WNXF7BJZW1PMGNXZ3Y8M8": { + errors: [ + { + category: "INVALID_REQUEST_ERROR", + code: "NOT_FOUND", + detail: "Customer with ID `2GYD7WNXF7BJZW1PMGNXZ3Y8M8` not found.", + }, + ], + }, + "8DDA5NZVBZFGAX0V3HPF81HHE0": { + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + N18CPRVXR5214XPBBA6BZQWF3C: { + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("BulkRetrieveCustomers", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + customer_ids: ["8DDA5NZVBZFGAX0V3HPF81HHE0", "N18CPRVXR5214XPBBA6BZQWF3C", "2GYD7WNXF7BJZW1PMGNXZ3Y8M8"], + }; + const rawResponseBody = { + responses: { + "2GYD7WNXF7BJZW1PMGNXZ3Y8M8": { + errors: [ + { + category: "INVALID_REQUEST_ERROR", + code: "NOT_FOUND", + detail: "Customer with ID `2GYD7WNXF7BJZW1PMGNXZ3Y8M8` not found.", + }, + ], + }, + "8DDA5NZVBZFGAX0V3HPF81HHE0": { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + customer: { + id: "8DDA5NZVBZFGAX0V3HPF81HHE0", + created_at: "2024-01-19T00:27:54.59Z", + updated_at: "2024-01-19T00:38:06Z", + given_name: "Amelia", + family_name: "Earhart", + email_address: "New.Amelia.Earhart@example.com", + birthday: "1897-07-24", + note: "updated customer note", + preferences: { email_unsubscribed: false }, + creation_source: "THIRD_PARTY", + version: BigInt(3), + }, + }, + N18CPRVXR5214XPBBA6BZQWF3C: { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + customer: { + id: "N18CPRVXR5214XPBBA6BZQWF3C", + created_at: "2024-01-19T00:27:54.59Z", + updated_at: "2024-01-19T00:38:06Z", + given_name: "Marie", + family_name: "Curie", + preferences: { email_unsubscribed: false }, + creation_source: "THIRD_PARTY", + version: BigInt(1), + }, + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/customers/bulk-retrieve") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.bulkRetrieveCustomers({ + customerIds: ["8DDA5NZVBZFGAX0V3HPF81HHE0", "N18CPRVXR5214XPBBA6BZQWF3C", "2GYD7WNXF7BJZW1PMGNXZ3Y8M8"], + }); + expect(response).toEqual({ + responses: { + "2GYD7WNXF7BJZW1PMGNXZ3Y8M8": { + errors: [ + { + category: "INVALID_REQUEST_ERROR", + code: "NOT_FOUND", + detail: "Customer with ID `2GYD7WNXF7BJZW1PMGNXZ3Y8M8` not found.", + }, + ], + }, + "8DDA5NZVBZFGAX0V3HPF81HHE0": { + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + customer: { + id: "8DDA5NZVBZFGAX0V3HPF81HHE0", + createdAt: "2024-01-19T00:27:54.59Z", + updatedAt: "2024-01-19T00:38:06Z", + givenName: "Amelia", + familyName: "Earhart", + emailAddress: "New.Amelia.Earhart@example.com", + birthday: "1897-07-24", + note: "updated customer note", + preferences: { + emailUnsubscribed: false, + }, + creationSource: "THIRD_PARTY", + version: BigInt("3"), + }, + }, + N18CPRVXR5214XPBBA6BZQWF3C: { + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + customer: { + id: "N18CPRVXR5214XPBBA6BZQWF3C", + createdAt: "2024-01-19T00:27:54.59Z", + updatedAt: "2024-01-19T00:38:06Z", + givenName: "Marie", + familyName: "Curie", + preferences: { + emailUnsubscribed: false, + }, + creationSource: "THIRD_PARTY", + version: BigInt("1"), + }, + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("BulkUpdateCustomers", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + customers: { + "8DDA5NZVBZFGAX0V3HPF81HHE0": { + email_address: "New.Amelia.Earhart@example.com", + note: "updated customer note", + version: BigInt(2), + }, + N18CPRVXR5214XPBBA6BZQWF3C: { given_name: "Marie", family_name: "Curie", version: BigInt(0) }, + }, + }; + const rawResponseBody = { + responses: { + "8DDA5NZVBZFGAX0V3HPF81HHE0": { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + customer: { + id: "8DDA5NZVBZFGAX0V3HPF81HHE0", + created_at: "2024-01-19T00:27:54.59Z", + updated_at: "2024-01-19T00:38:06Z", + given_name: "Amelia", + family_name: "Earhart", + email_address: "New.Amelia.Earhart@example.com", + birthday: "1897-07-24", + note: "updated customer note", + preferences: { email_unsubscribed: false }, + creation_source: "THIRD_PARTY", + version: BigInt(3), + }, + }, + N18CPRVXR5214XPBBA6BZQWF3C: { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + customer: { + id: "N18CPRVXR5214XPBBA6BZQWF3C", + created_at: "2024-01-19T00:27:54.59Z", + updated_at: "2024-01-19T00:38:06Z", + given_name: "Marie", + family_name: "Curie", + preferences: { email_unsubscribed: false }, + creation_source: "THIRD_PARTY", + version: BigInt(1), + }, + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/customers/bulk-update") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.bulkUpdateCustomers({ + customers: { + "8DDA5NZVBZFGAX0V3HPF81HHE0": { + emailAddress: "New.Amelia.Earhart@example.com", + note: "updated customer note", + version: BigInt("2"), + }, + N18CPRVXR5214XPBBA6BZQWF3C: { + givenName: "Marie", + familyName: "Curie", + version: BigInt("0"), + }, + }, + }); + expect(response).toEqual({ + responses: { + "8DDA5NZVBZFGAX0V3HPF81HHE0": { + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + customer: { + id: "8DDA5NZVBZFGAX0V3HPF81HHE0", + createdAt: "2024-01-19T00:27:54.59Z", + updatedAt: "2024-01-19T00:38:06Z", + givenName: "Amelia", + familyName: "Earhart", + emailAddress: "New.Amelia.Earhart@example.com", + birthday: "1897-07-24", + note: "updated customer note", + preferences: { + emailUnsubscribed: false, + }, + creationSource: "THIRD_PARTY", + version: BigInt("3"), + }, + }, + N18CPRVXR5214XPBBA6BZQWF3C: { + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + customer: { + id: "N18CPRVXR5214XPBBA6BZQWF3C", + createdAt: "2024-01-19T00:27:54.59Z", + updatedAt: "2024-01-19T00:38:06Z", + givenName: "Marie", + familyName: "Curie", + preferences: { + emailUnsubscribed: false, + }, + creationSource: "THIRD_PARTY", + version: BigInt("1"), + }, + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("search", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + limit: BigInt(2), + query: { + filter: { + creation_source: { values: ["THIRD_PARTY"], rule: "INCLUDE" }, + created_at: { start_at: "2018-01-01T00:00:00-00:00", end_at: "2018-02-01T00:00:00-00:00" }, + email_address: { fuzzy: "example.com" }, + group_ids: { all: ["545AXB44B4XXWMVQ4W8SBT3HHF"] }, + }, + sort: { field: "CREATED_AT", order: "ASC" }, + }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + customers: [ + { + id: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + created_at: "2018-01-23T20:21:54.859Z", + updated_at: "2020-04-20T10:02:43.083Z", + given_name: "James", + family_name: "Bond", + nickname: "nickname", + company_name: "company_name", + email_address: "james.bond@example.com", + address: { + address_line_1: "505 Electric Ave", + address_line_2: "Suite 600", + locality: "New York", + administrative_district_level_1: "NY", + postal_code: "10003", + country: "US", + }, + phone_number: "+1-212-555-4250", + birthday: "birthday", + reference_id: "YOUR_REFERENCE_ID_2", + note: "note", + preferences: { email_unsubscribed: false }, + creation_source: "DIRECTORY", + group_ids: ["545AXB44B4XXWMVQ4W8SBT3HHF"], + segment_ids: ["1KB9JE5EGJXCW.REACHABLE"], + version: BigInt(7), + }, + { + id: "A9641GZW2H7Z56YYSD41Q12HDW", + created_at: "2018-01-30T14:10:54.859Z", + updated_at: "2018-03-08T18:25:21.342Z", + given_name: "Amelia", + family_name: "Earhart", + nickname: "nickname", + company_name: "company_name", + email_address: "amelia.earhart@example.com", + address: { + address_line_1: "500 Electric Ave", + address_line_2: "Suite 600", + locality: "New York", + administrative_district_level_1: "NY", + postal_code: "10003", + country: "US", + }, + phone_number: "+1-212-555-9238", + birthday: "birthday", + reference_id: "YOUR_REFERENCE_ID_1", + note: "a customer", + preferences: { email_unsubscribed: false }, + creation_source: "THIRD_PARTY", + group_ids: ["545AXB44B4XXWMVQ4W8SBT3HHF"], + segment_ids: ["1KB9JE5EGJXCW.REACHABLE"], + version: BigInt(1), + }, + ], + cursor: "9dpS093Uy12AzeE", + count: BigInt(1000000), + }; + server + .mockEndpoint() + .post("/v2/customers/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.search({ + limit: BigInt("2"), + query: { + filter: { + creationSource: { + values: ["THIRD_PARTY"], + rule: "INCLUDE", + }, + createdAt: { + startAt: "2018-01-01T00:00:00-00:00", + endAt: "2018-02-01T00:00:00-00:00", + }, + emailAddress: { + fuzzy: "example.com", + }, + groupIds: { + all: ["545AXB44B4XXWMVQ4W8SBT3HHF"], + }, + }, + sort: { + field: "CREATED_AT", + order: "ASC", + }, + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + customers: [ + { + id: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + createdAt: "2018-01-23T20:21:54.859Z", + updatedAt: "2020-04-20T10:02:43.083Z", + givenName: "James", + familyName: "Bond", + nickname: "nickname", + companyName: "company_name", + emailAddress: "james.bond@example.com", + address: { + addressLine1: "505 Electric Ave", + addressLine2: "Suite 600", + locality: "New York", + administrativeDistrictLevel1: "NY", + postalCode: "10003", + country: "US", + }, + phoneNumber: "+1-212-555-4250", + birthday: "birthday", + referenceId: "YOUR_REFERENCE_ID_2", + note: "note", + preferences: { + emailUnsubscribed: false, + }, + creationSource: "DIRECTORY", + groupIds: ["545AXB44B4XXWMVQ4W8SBT3HHF"], + segmentIds: ["1KB9JE5EGJXCW.REACHABLE"], + version: BigInt("7"), + }, + { + id: "A9641GZW2H7Z56YYSD41Q12HDW", + createdAt: "2018-01-30T14:10:54.859Z", + updatedAt: "2018-03-08T18:25:21.342Z", + givenName: "Amelia", + familyName: "Earhart", + nickname: "nickname", + companyName: "company_name", + emailAddress: "amelia.earhart@example.com", + address: { + addressLine1: "500 Electric Ave", + addressLine2: "Suite 600", + locality: "New York", + administrativeDistrictLevel1: "NY", + postalCode: "10003", + country: "US", + }, + phoneNumber: "+1-212-555-9238", + birthday: "birthday", + referenceId: "YOUR_REFERENCE_ID_1", + note: "a customer", + preferences: { + emailUnsubscribed: false, + }, + creationSource: "THIRD_PARTY", + groupIds: ["545AXB44B4XXWMVQ4W8SBT3HHF"], + segmentIds: ["1KB9JE5EGJXCW.REACHABLE"], + version: BigInt("1"), + }, + ], + cursor: "9dpS093Uy12AzeE", + count: BigInt("1000000"), + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + customer: { + id: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + created_at: "2016-03-23T20:21:54.859Z", + updated_at: "2016-03-23T20:21:54.859Z", + given_name: "Amelia", + family_name: "Earhart", + nickname: "nickname", + company_name: "company_name", + email_address: "Amelia.Earhart@example.com", + address: { + address_line_1: "500 Electric Ave", + address_line_2: "Suite 600", + address_line_3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "NY", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "10003", + country: "US", + first_name: "first_name", + last_name: "last_name", + }, + phone_number: "+1-212-555-4240", + birthday: "birthday", + reference_id: "YOUR_REFERENCE_ID", + note: "a customer", + preferences: { email_unsubscribed: false }, + creation_source: "THIRD_PARTY", + group_ids: ["545AXB44B4XXWMVQ4W8SBT3HHF"], + segment_ids: ["1KB9JE5EGJXCW.REACHABLE"], + version: BigInt(1), + tax_ids: { eu_vat: "eu_vat" }, + }, + }; + server + .mockEndpoint() + .get("/v2/customers/customer_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.get({ + customerId: "customer_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + customer: { + id: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + createdAt: "2016-03-23T20:21:54.859Z", + updatedAt: "2016-03-23T20:21:54.859Z", + givenName: "Amelia", + familyName: "Earhart", + nickname: "nickname", + companyName: "company_name", + emailAddress: "Amelia.Earhart@example.com", + address: { + addressLine1: "500 Electric Ave", + addressLine2: "Suite 600", + addressLine3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "NY", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "10003", + country: "US", + firstName: "first_name", + lastName: "last_name", + }, + phoneNumber: "+1-212-555-4240", + birthday: "birthday", + referenceId: "YOUR_REFERENCE_ID", + note: "a customer", + preferences: { + emailUnsubscribed: false, + }, + creationSource: "THIRD_PARTY", + groupIds: ["545AXB44B4XXWMVQ4W8SBT3HHF"], + segmentIds: ["1KB9JE5EGJXCW.REACHABLE"], + version: BigInt("1"), + taxIds: { + euVat: "eu_vat", + }, + }, + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + email_address: "New.Amelia.Earhart@example.com", + note: "updated customer note", + version: BigInt(2), + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + customer: { + id: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + created_at: "2016-03-23T20:21:54.859Z", + updated_at: "2016-05-15T20:21:55Z", + given_name: "Amelia", + family_name: "Earhart", + nickname: "nickname", + company_name: "company_name", + email_address: "New.Amelia.Earhart@example.com", + address: { + address_line_1: "500 Electric Ave", + address_line_2: "Suite 600", + address_line_3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "NY", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "10003", + country: "US", + first_name: "first_name", + last_name: "last_name", + }, + phone_number: "phone_number", + birthday: "birthday", + reference_id: "YOUR_REFERENCE_ID", + note: "updated customer note", + preferences: { email_unsubscribed: false }, + creation_source: "THIRD_PARTY", + group_ids: ["group_ids"], + segment_ids: ["segment_ids"], + version: BigInt(3), + tax_ids: { eu_vat: "eu_vat" }, + }, + }; + server + .mockEndpoint() + .put("/v2/customers/customer_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.update({ + customerId: "customer_id", + emailAddress: "New.Amelia.Earhart@example.com", + note: "updated customer note", + version: BigInt("2"), + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + customer: { + id: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + createdAt: "2016-03-23T20:21:54.859Z", + updatedAt: "2016-05-15T20:21:55Z", + givenName: "Amelia", + familyName: "Earhart", + nickname: "nickname", + companyName: "company_name", + emailAddress: "New.Amelia.Earhart@example.com", + address: { + addressLine1: "500 Electric Ave", + addressLine2: "Suite 600", + addressLine3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "NY", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "10003", + country: "US", + firstName: "first_name", + lastName: "last_name", + }, + phoneNumber: "phone_number", + birthday: "birthday", + referenceId: "YOUR_REFERENCE_ID", + note: "updated customer note", + preferences: { + emailUnsubscribed: false, + }, + creationSource: "THIRD_PARTY", + groupIds: ["group_ids"], + segmentIds: ["segment_ids"], + version: BigInt("3"), + taxIds: { + euVat: "eu_vat", + }, + }, + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/customers/customer_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.delete({ + customerId: "customer_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/customers/cards.test.ts b/tests/wire/customers/cards.test.ts new file mode 100644 index 000000000..0f8e33d61 --- /dev/null +++ b/tests/wire/customers/cards.test.ts @@ -0,0 +1,165 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("Cards", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + card_nonce: "YOUR_CARD_NONCE", + billing_address: { + address_line_1: "500 Electric Ave", + address_line_2: "Suite 600", + locality: "New York", + administrative_district_level_1: "NY", + postal_code: "10003", + country: "US", + }, + cardholder_name: "Amelia Earhart", + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + card: { + id: "icard-card_id", + card_brand: "VISA", + last_4: "1111", + exp_month: BigInt(11), + exp_year: BigInt(2018), + cardholder_name: "Amelia Earhart", + billing_address: { + address_line_1: "500 Electric Ave", + address_line_2: "Suite 600", + address_line_3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "NY", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "10003", + country: "US", + first_name: "first_name", + last_name: "last_name", + }, + fingerprint: "fingerprint", + customer_id: "customer_id", + merchant_id: "merchant_id", + reference_id: "reference_id", + enabled: true, + card_type: "UNKNOWN_CARD_TYPE", + prepaid_type: "UNKNOWN_PREPAID_TYPE", + bin: "bin", + version: BigInt(1000000), + card_co_brand: "UNKNOWN", + issuer_alert: "ISSUER_ALERT_CARD_CLOSED", + issuer_alert_at: "issuer_alert_at", + hsa_fsa: true, + }, + }; + server + .mockEndpoint() + .post("/v2/customers/customer_id/cards") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.cards.create({ + customerId: "customer_id", + cardNonce: "YOUR_CARD_NONCE", + billingAddress: { + addressLine1: "500 Electric Ave", + addressLine2: "Suite 600", + locality: "New York", + administrativeDistrictLevel1: "NY", + postalCode: "10003", + country: "US", + }, + cardholderName: "Amelia Earhart", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + card: { + id: "icard-card_id", + cardBrand: "VISA", + last4: "1111", + expMonth: BigInt("11"), + expYear: BigInt("2018"), + cardholderName: "Amelia Earhart", + billingAddress: { + addressLine1: "500 Electric Ave", + addressLine2: "Suite 600", + addressLine3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "NY", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "10003", + country: "US", + firstName: "first_name", + lastName: "last_name", + }, + fingerprint: "fingerprint", + customerId: "customer_id", + merchantId: "merchant_id", + referenceId: "reference_id", + enabled: true, + cardType: "UNKNOWN_CARD_TYPE", + prepaidType: "UNKNOWN_PREPAID_TYPE", + bin: "bin", + version: BigInt("1000000"), + cardCoBrand: "UNKNOWN", + issuerAlert: "ISSUER_ALERT_CARD_CLOSED", + issuerAlertAt: "issuer_alert_at", + hsaFsa: true, + }, + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/customers/customer_id/cards/card_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.cards.delete({ + customerId: "customer_id", + cardId: "card_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/customers/customAttributeDefinitions.test.ts b/tests/wire/customers/customAttributeDefinitions.test.ts new file mode 100644 index 000000000..671c42ace --- /dev/null +++ b/tests/wire/customers/customAttributeDefinitions.test.ts @@ -0,0 +1,471 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("CustomAttributeDefinitions", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + custom_attribute_definition: { + key: "favoritemovie", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Favorite Movie", + description: "The favorite movie of the customer.", + visibility: "VISIBILITY_HIDDEN", + }, + }; + const rawResponseBody = { + custom_attribute_definition: { + key: "favoritemovie", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Favorite Movie", + description: "The favorite movie of the customer.", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updated_at: "2022-04-26T15:27:30Z", + created_at: "2022-04-26T15:27:30Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/customers/custom-attribute-definitions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.customAttributeDefinitions.create({ + customAttributeDefinition: { + key: "favoritemovie", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Favorite Movie", + description: "The favorite movie of the customer.", + visibility: "VISIBILITY_HIDDEN", + }, + }); + expect(response).toEqual({ + customAttributeDefinition: { + key: "favoritemovie", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Favorite Movie", + description: "The favorite movie of the customer.", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updatedAt: "2022-04-26T15:27:30Z", + createdAt: "2022-04-26T15:27:30Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + custom_attribute_definition: { + key: "favoritemovie", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Favorite Movie", + description: "The favorite movie of the customer.", + visibility: "VISIBILITY_READ_WRITE_VALUES", + version: 1, + updated_at: "2022-04-26T15:27:30Z", + created_at: "2022-04-26T15:27:30Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/customers/custom-attribute-definitions/key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.customAttributeDefinitions.get({ + key: "key", + }); + expect(response).toEqual({ + customAttributeDefinition: { + key: "favoritemovie", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Favorite Movie", + description: "The favorite movie of the customer.", + visibility: "VISIBILITY_READ_WRITE_VALUES", + version: 1, + updatedAt: "2022-04-26T15:27:30Z", + createdAt: "2022-04-26T15:27:30Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + custom_attribute_definition: { + description: "Update the description as desired.", + visibility: "VISIBILITY_READ_ONLY", + }, + }; + const rawResponseBody = { + custom_attribute_definition: { + key: "favoritemovie", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Favorite Movie", + description: "Update the description as desired.", + visibility: "VISIBILITY_READ_ONLY", + version: 2, + updated_at: "2022-04-26T15:39:38Z", + created_at: "2022-04-26T15:27:30Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .put("/v2/customers/custom-attribute-definitions/key") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.customAttributeDefinitions.update({ + key: "key", + customAttributeDefinition: { + description: "Update the description as desired.", + visibility: "VISIBILITY_READ_ONLY", + }, + }); + expect(response).toEqual({ + customAttributeDefinition: { + key: "favoritemovie", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Favorite Movie", + description: "Update the description as desired.", + visibility: "VISIBILITY_READ_ONLY", + version: 2, + updatedAt: "2022-04-26T15:39:38Z", + createdAt: "2022-04-26T15:27:30Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/customers/custom-attribute-definitions/key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.customAttributeDefinitions.delete({ + key: "key", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("batchUpsert", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + values: { + id1: { + customer_id: "N3NCVYY3WS27HF0HKANA3R9FP8", + custom_attribute: { key: "favoritemovie", value: "Dune" }, + }, + id2: { + customer_id: "SY8EMWRNDN3TQDP2H4KS1QWMMM", + custom_attribute: { key: "ownsmovie", value: false }, + }, + id3: { + customer_id: "SY8EMWRNDN3TQDP2H4KS1QWMMM", + custom_attribute: { key: "favoritemovie", value: "Star Wars" }, + }, + id4: { + customer_id: "N3NCVYY3WS27HF0HKANA3R9FP8", + custom_attribute: { key: "square:a0f1505a-2aa1-490d-91a8-8d31ff181808", value: "10.5" }, + }, + id5: { + customer_id: "70548QG1HN43B05G0KCZ4MMC1G", + custom_attribute: { + key: "sq0ids-0evKIskIGaY45fCyNL66aw:backupemail", + value: "fake-email@squareup.com", + }, + }, + }, + }; + const rawResponseBody = { + values: { + id1: { + customer_id: "N3NCVYY3WS27HF0HKANA3R9FP8", + custom_attribute: { + key: "favoritemovie", + value: "Dune", + version: 1, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updated_at: "2021-12-09T00:16:23Z", + created_at: "2021-12-08T23:14:47Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + id2: { + customer_id: "SY8EMWRNDN3TQDP2H4KS1QWMMM", + custom_attribute: { + key: "ownsmovie", + value: false, + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updated_at: "2021-12-09T00:16:23Z", + created_at: "2021-12-09T00:16:20Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + id3: { + customer_id: "SY8EMWRNDN3TQDP2H4KS1QWMMM", + custom_attribute: { + key: "favoritemovie", + value: "Star Wars", + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updated_at: "2021-12-09T00:16:23Z", + created_at: "2021-12-09T00:16:20Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + id4: { + customer_id: "N3NCVYY3WS27HF0HKANA3R9FP8", + custom_attribute: { + key: "square:a0f1505a-2aa1-490d-91a8-8d31ff181808", + value: "10.5", + version: 1, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updated_at: "2021-12-09T00:16:23Z", + created_at: "2021-12-08T23:14:47Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + id5: { + customer_id: "70548QG1HN43B05G0KCZ4MMC1G", + custom_attribute: { + key: "sq0ids-0evKIskIGaY45fCyNL66aw:backupemail", + value: "fake-email@squareup.com", + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updated_at: "2021-12-09T00:16:23Z", + created_at: "2021-12-09T00:16:20Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/customers/custom-attributes/bulk-upsert") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.customAttributeDefinitions.batchUpsert({ + values: { + id1: { + customerId: "N3NCVYY3WS27HF0HKANA3R9FP8", + customAttribute: { + key: "favoritemovie", + value: "Dune", + }, + }, + id2: { + customerId: "SY8EMWRNDN3TQDP2H4KS1QWMMM", + customAttribute: { + key: "ownsmovie", + value: false, + }, + }, + id3: { + customerId: "SY8EMWRNDN3TQDP2H4KS1QWMMM", + customAttribute: { + key: "favoritemovie", + value: "Star Wars", + }, + }, + id4: { + customerId: "N3NCVYY3WS27HF0HKANA3R9FP8", + customAttribute: { + key: "square:a0f1505a-2aa1-490d-91a8-8d31ff181808", + value: "10.5", + }, + }, + id5: { + customerId: "70548QG1HN43B05G0KCZ4MMC1G", + customAttribute: { + key: "sq0ids-0evKIskIGaY45fCyNL66aw:backupemail", + value: "fake-email@squareup.com", + }, + }, + }, + }); + expect(response).toEqual({ + values: { + id1: { + customerId: "N3NCVYY3WS27HF0HKANA3R9FP8", + customAttribute: { + key: "favoritemovie", + value: "Dune", + version: 1, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updatedAt: "2021-12-09T00:16:23Z", + createdAt: "2021-12-08T23:14:47Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + id2: { + customerId: "SY8EMWRNDN3TQDP2H4KS1QWMMM", + customAttribute: { + key: "ownsmovie", + value: false, + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updatedAt: "2021-12-09T00:16:23Z", + createdAt: "2021-12-09T00:16:20Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + id3: { + customerId: "SY8EMWRNDN3TQDP2H4KS1QWMMM", + customAttribute: { + key: "favoritemovie", + value: "Star Wars", + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updatedAt: "2021-12-09T00:16:23Z", + createdAt: "2021-12-09T00:16:20Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + id4: { + customerId: "N3NCVYY3WS27HF0HKANA3R9FP8", + customAttribute: { + key: "square:a0f1505a-2aa1-490d-91a8-8d31ff181808", + value: "10.5", + version: 1, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updatedAt: "2021-12-09T00:16:23Z", + createdAt: "2021-12-08T23:14:47Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + id5: { + customerId: "70548QG1HN43B05G0KCZ4MMC1G", + customAttribute: { + key: "sq0ids-0evKIskIGaY45fCyNL66aw:backupemail", + value: "fake-email@squareup.com", + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updatedAt: "2021-12-09T00:16:23Z", + createdAt: "2021-12-09T00:16:20Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/customers/customAttributes.test.ts b/tests/wire/customers/customAttributes.test.ts new file mode 100644 index 000000000..1e17e6722 --- /dev/null +++ b/tests/wire/customers/customAttributes.test.ts @@ -0,0 +1,181 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("CustomAttributes", () => { + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + custom_attribute: { + key: "favoritemovie", + value: "Dune", + version: 1, + visibility: "VISIBILITY_READ_ONLY", + definition: { + key: "key", + schema: { key: "value" }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updated_at: "updated_at", + created_at: "created_at", + }, + updated_at: "2022-04-26T15:50:27Z", + created_at: "2022-04-26T15:50:27Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/customers/customer_id/custom-attributes/key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.customAttributes.get({ + customerId: "customer_id", + key: "key", + }); + expect(response).toEqual({ + customAttribute: { + key: "favoritemovie", + value: "Dune", + version: 1, + visibility: "VISIBILITY_READ_ONLY", + definition: { + key: "key", + schema: { + key: "value", + }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updatedAt: "updated_at", + createdAt: "created_at", + }, + updatedAt: "2022-04-26T15:50:27Z", + createdAt: "2022-04-26T15:50:27Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("upsert", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { custom_attribute: { value: "Dune" } }; + const rawResponseBody = { + custom_attribute: { + key: "favoritemovie", + value: "Dune", + version: 1, + visibility: "VISIBILITY_READ_ONLY", + definition: { + key: "key", + schema: { key: "value" }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updated_at: "updated_at", + created_at: "created_at", + }, + updated_at: "2022-04-26T15:50:27Z", + created_at: "2022-04-26T15:50:27Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/customers/customer_id/custom-attributes/key") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.customAttributes.upsert({ + customerId: "customer_id", + key: "key", + customAttribute: { + value: "Dune", + }, + }); + expect(response).toEqual({ + customAttribute: { + key: "favoritemovie", + value: "Dune", + version: 1, + visibility: "VISIBILITY_READ_ONLY", + definition: { + key: "key", + schema: { + key: "value", + }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updatedAt: "updated_at", + createdAt: "created_at", + }, + updatedAt: "2022-04-26T15:50:27Z", + createdAt: "2022-04-26T15:50:27Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/customers/customer_id/custom-attributes/key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.customAttributes.delete({ + customerId: "customer_id", + key: "key", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/customers/groups.test.ts b/tests/wire/customers/groups.test.ts new file mode 100644 index 000000000..80a92ceff --- /dev/null +++ b/tests/wire/customers/groups.test.ts @@ -0,0 +1,233 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("Groups", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { group: { name: "Loyal Customers" } }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + group: { + id: "2TAT3CMH4Q0A9M87XJZED0WMR3", + name: "Loyal Customers", + created_at: "2020-04-13T21:54:57.863Z", + updated_at: "2020-04-13T21:54:58Z", + }, + }; + server + .mockEndpoint() + .post("/v2/customers/groups") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.groups.create({ + group: { + name: "Loyal Customers", + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + group: { + id: "2TAT3CMH4Q0A9M87XJZED0WMR3", + name: "Loyal Customers", + createdAt: "2020-04-13T21:54:57.863Z", + updatedAt: "2020-04-13T21:54:58Z", + }, + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + group: { + id: "2TAT3CMH4Q0A9M87XJZED0WMR3", + name: "Loyal Customers", + created_at: "2020-04-13T21:54:57.863Z", + updated_at: "2020-04-13T21:54:58Z", + }, + }; + server + .mockEndpoint() + .get("/v2/customers/groups/group_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.groups.get({ + groupId: "group_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + group: { + id: "2TAT3CMH4Q0A9M87XJZED0WMR3", + name: "Loyal Customers", + createdAt: "2020-04-13T21:54:57.863Z", + updatedAt: "2020-04-13T21:54:58Z", + }, + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { group: { name: "Loyal Customers" } }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + group: { + id: "2TAT3CMH4Q0A9M87XJZED0WMR3", + name: "Loyal Customers", + created_at: "2020-04-13T21:54:57.863Z", + updated_at: "2020-04-13T21:54:58Z", + }, + }; + server + .mockEndpoint() + .put("/v2/customers/groups/group_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.groups.update({ + groupId: "group_id", + group: { + name: "Loyal Customers", + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + group: { + id: "2TAT3CMH4Q0A9M87XJZED0WMR3", + name: "Loyal Customers", + createdAt: "2020-04-13T21:54:57.863Z", + updatedAt: "2020-04-13T21:54:58Z", + }, + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/customers/groups/group_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.groups.delete({ + groupId: "group_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("add", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .put("/v2/customers/customer_id/groups/group_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.groups.add({ + customerId: "customer_id", + groupId: "group_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("remove", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/customers/customer_id/groups/group_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.groups.remove({ + customerId: "customer_id", + groupId: "group_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/customers/segments.test.ts b/tests/wire/customers/segments.test.ts new file mode 100644 index 000000000..e891d9cb7 --- /dev/null +++ b/tests/wire/customers/segments.test.ts @@ -0,0 +1,50 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("Segments", () => { + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + segment: { + id: "GMNXRZVEXNQDF.CHURN_RISK", + name: "Lapsed", + created_at: "2020-01-09T19:33:24.469Z", + updated_at: "2020-04-13T23:01:13Z", + }, + }; + server + .mockEndpoint() + .get("/v2/customers/segments/segment_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.customers.segments.get({ + segmentId: "segment_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + segment: { + id: "GMNXRZVEXNQDF.CHURN_RISK", + name: "Lapsed", + createdAt: "2020-01-09T19:33:24.469Z", + updatedAt: "2020-04-13T23:01:13Z", + }, + }); + }); +}); diff --git a/tests/wire/devices.test.ts b/tests/wire/devices.test.ts new file mode 100644 index 000000000..02e86f2dd --- /dev/null +++ b/tests/wire/devices.test.ts @@ -0,0 +1,132 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Devices", () => { + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + device: { + id: "device:995CS397A6475287", + attributes: { + type: "TERMINAL", + manufacturer: "Square", + model: "T2", + name: "Square Terminal 995", + manufacturers_id: "995CS397A6475287", + updated_at: "2023-09-29T13:12:22.365049321Z", + version: "5.41.0085", + merchant_token: "MLCHXZCBWFGDW", + }, + components: [ + { + type: "APPLICATION", + application_details: { + application_type: "TERMINAL_API", + version: "6.25", + session_location: "LMN2K7S3RTOU3", + }, + }, + { type: "CARD_READER", card_reader_details: { version: "3.53.70" } }, + { type: "BATTERY", battery_details: { visible_percent: 5, external_power: "AVAILABLE_CHARGING" } }, + { + type: "WIFI", + wifi_details: { + active: true, + ssid: "Staff Network", + ip_address_v4: "10.0.0.7", + secure_connection: "WPA/WPA2 PSK", + signal_strength: { value: 2 }, + }, + }, + { type: "ETHERNET", ethernet_details: { active: false } }, + ], + status: { category: "AVAILABLE" }, + }, + }; + server + .mockEndpoint() + .get("/v2/devices/device_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.devices.get({ + deviceId: "device_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + device: { + id: "device:995CS397A6475287", + attributes: { + type: "TERMINAL", + manufacturer: "Square", + model: "T2", + name: "Square Terminal 995", + manufacturersId: "995CS397A6475287", + updatedAt: "2023-09-29T13:12:22.365049321Z", + version: "5.41.0085", + merchantToken: "MLCHXZCBWFGDW", + }, + components: [ + { + type: "APPLICATION", + applicationDetails: { + applicationType: "TERMINAL_API", + version: "6.25", + sessionLocation: "LMN2K7S3RTOU3", + }, + }, + { + type: "CARD_READER", + cardReaderDetails: { + version: "3.53.70", + }, + }, + { + type: "BATTERY", + batteryDetails: { + visiblePercent: 5, + externalPower: "AVAILABLE_CHARGING", + }, + }, + { + type: "WIFI", + wifiDetails: { + active: true, + ssid: "Staff Network", + ipAddressV4: "10.0.0.7", + secureConnection: "WPA/WPA2 PSK", + signalStrength: { + value: 2, + }, + }, + }, + { + type: "ETHERNET", + ethernetDetails: { + active: false, + }, + }, + ], + status: { + category: "AVAILABLE", + }, + }, + }); + }); +}); diff --git a/tests/wire/devices/codes.test.ts b/tests/wire/devices/codes.test.ts new file mode 100644 index 000000000..489f9ed99 --- /dev/null +++ b/tests/wire/devices/codes.test.ts @@ -0,0 +1,129 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("Codes", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "01bb00a6-0c86-4770-94ed-f5fca973cd56", + device_code: { name: "Counter 1", product_type: "TERMINAL_API", location_id: "B5E4484SHHNYH" }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + device_code: { + id: "B3Z6NAMYQSMTM", + name: "Counter 1", + code: "EBCARJ", + device_id: "device_id", + product_type: "TERMINAL_API", + location_id: "B5E4484SHHNYH", + status: "UNPAIRED", + pair_by: "2020-02-06T18:49:33.000Z", + created_at: "2020-02-06T18:44:33.000Z", + status_changed_at: "2020-02-06T18:44:33.000Z", + paired_at: "paired_at", + }, + }; + server + .mockEndpoint() + .post("/v2/devices/codes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.devices.codes.create({ + idempotencyKey: "01bb00a6-0c86-4770-94ed-f5fca973cd56", + deviceCode: { + name: "Counter 1", + productType: "TERMINAL_API", + locationId: "B5E4484SHHNYH", + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + deviceCode: { + id: "B3Z6NAMYQSMTM", + name: "Counter 1", + code: "EBCARJ", + deviceId: "device_id", + productType: "TERMINAL_API", + locationId: "B5E4484SHHNYH", + status: "UNPAIRED", + pairBy: "2020-02-06T18:49:33.000Z", + createdAt: "2020-02-06T18:44:33.000Z", + statusChangedAt: "2020-02-06T18:44:33.000Z", + pairedAt: "paired_at", + }, + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + device_code: { + id: "B3Z6NAMYQSMTM", + name: "Counter 1", + code: "EBCARJ", + device_id: "907CS13101300122", + product_type: "TERMINAL_API", + location_id: "B5E4484SHHNYH", + status: "PAIRED", + pair_by: "2020-02-06T18:49:33.000Z", + created_at: "2020-02-06T18:44:33.000Z", + status_changed_at: "2020-02-06T18:47:28.000Z", + paired_at: "paired_at", + }, + }; + server + .mockEndpoint() + .get("/v2/devices/codes/id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.devices.codes.get({ + id: "id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + deviceCode: { + id: "B3Z6NAMYQSMTM", + name: "Counter 1", + code: "EBCARJ", + deviceId: "907CS13101300122", + productType: "TERMINAL_API", + locationId: "B5E4484SHHNYH", + status: "PAIRED", + pairBy: "2020-02-06T18:49:33.000Z", + createdAt: "2020-02-06T18:44:33.000Z", + statusChangedAt: "2020-02-06T18:47:28.000Z", + pairedAt: "paired_at", + }, + }); + }); +}); diff --git a/tests/wire/disputes.test.ts b/tests/wire/disputes.test.ts new file mode 100644 index 000000000..334677ebc --- /dev/null +++ b/tests/wire/disputes.test.ts @@ -0,0 +1,280 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Disputes", () => { + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + dispute: { + dispute_id: "dispute_id", + id: "XDgyFu7yo1E2S5lQGGpYn", + amount_money: { amount: BigInt(2500), currency: "USD" }, + reason: "NO_KNOWLEDGE", + state: "ACCEPTED", + due_at: "2022-07-13T00:00:00.000Z", + disputed_payment: { payment_id: "zhyh1ch64kRBrrlfVhwjCEjZWzNZY" }, + evidence_ids: ["evidence_ids"], + card_brand: "VISA", + created_at: "2022-06-29T18:45:22.265Z", + updated_at: "2022-07-07T19:14:42.650Z", + brand_dispute_id: "100000809947", + reported_date: "reported_date", + reported_at: "2022-06-29T00:00:00.000Z", + version: 2, + location_id: "L1HN3ZMQK64X9", + }, + }; + server + .mockEndpoint() + .get("/v2/disputes/dispute_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.disputes.get({ + disputeId: "dispute_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + dispute: { + disputeId: "dispute_id", + id: "XDgyFu7yo1E2S5lQGGpYn", + amountMoney: { + amount: BigInt("2500"), + currency: "USD", + }, + reason: "NO_KNOWLEDGE", + state: "ACCEPTED", + dueAt: "2022-07-13T00:00:00.000Z", + disputedPayment: { + paymentId: "zhyh1ch64kRBrrlfVhwjCEjZWzNZY", + }, + evidenceIds: ["evidence_ids"], + cardBrand: "VISA", + createdAt: "2022-06-29T18:45:22.265Z", + updatedAt: "2022-07-07T19:14:42.650Z", + brandDisputeId: "100000809947", + reportedDate: "reported_date", + reportedAt: "2022-06-29T00:00:00.000Z", + version: 2, + locationId: "L1HN3ZMQK64X9", + }, + }); + }); + + test("accept", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + dispute: { + dispute_id: "dispute_id", + id: "XDgyFu7yo1E2S5lQGGpYn", + amount_money: { amount: BigInt(2500), currency: "USD" }, + reason: "NO_KNOWLEDGE", + state: "ACCEPTED", + due_at: "2022-07-13T00:00:00.000Z", + disputed_payment: { payment_id: "zhyh1ch64kRBrrlfVhwjCEjZWzNZY" }, + evidence_ids: ["evidence_ids"], + card_brand: "VISA", + created_at: "2022-06-29T18:45:22.265Z", + updated_at: "2022-07-07T19:14:42.650Z", + brand_dispute_id: "100000809947", + reported_date: "reported_date", + reported_at: "2022-06-29T00:00:00.000Z", + version: 2, + location_id: "L1HN3ZMQK64X9", + }, + }; + server + .mockEndpoint() + .post("/v2/disputes/dispute_id/accept") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.disputes.accept({ + disputeId: "dispute_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + dispute: { + disputeId: "dispute_id", + id: "XDgyFu7yo1E2S5lQGGpYn", + amountMoney: { + amount: BigInt("2500"), + currency: "USD", + }, + reason: "NO_KNOWLEDGE", + state: "ACCEPTED", + dueAt: "2022-07-13T00:00:00.000Z", + disputedPayment: { + paymentId: "zhyh1ch64kRBrrlfVhwjCEjZWzNZY", + }, + evidenceIds: ["evidence_ids"], + cardBrand: "VISA", + createdAt: "2022-06-29T18:45:22.265Z", + updatedAt: "2022-07-07T19:14:42.650Z", + brandDisputeId: "100000809947", + reportedDate: "reported_date", + reportedAt: "2022-06-29T00:00:00.000Z", + version: 2, + locationId: "L1HN3ZMQK64X9", + }, + }); + }); + + test("CreateEvidenceText", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "ed3ee3933d946f1514d505d173c82648", + evidence_type: "TRACKING_NUMBER", + evidence_text: "1Z8888888888888888", + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + evidence: { + evidence_id: "evidence_id", + id: "TOomLInj6iWmP3N8qfCXrB", + dispute_id: "bVTprrwk0gygTLZ96VX1oB", + evidence_file: { filename: "filename", filetype: "filetype" }, + evidence_text: "The customer purchased the item twice, on April 11 and April 28.", + uploaded_at: "2022-05-18T16:01:10.000Z", + evidence_type: "REBUTTAL_EXPLANATION", + }, + }; + server + .mockEndpoint() + .post("/v2/disputes/dispute_id/evidence-text") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.disputes.createEvidenceText({ + disputeId: "dispute_id", + idempotencyKey: "ed3ee3933d946f1514d505d173c82648", + evidenceType: "TRACKING_NUMBER", + evidenceText: "1Z8888888888888888", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + evidence: { + evidenceId: "evidence_id", + id: "TOomLInj6iWmP3N8qfCXrB", + disputeId: "bVTprrwk0gygTLZ96VX1oB", + evidenceFile: { + filename: "filename", + filetype: "filetype", + }, + evidenceText: "The customer purchased the item twice, on April 11 and April 28.", + uploadedAt: "2022-05-18T16:01:10.000Z", + evidenceType: "REBUTTAL_EXPLANATION", + }, + }); + }); + + test("SubmitEvidence", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + dispute: { + dispute_id: "dispute_id", + id: "EAZoK70gX3fyvibecLwIGB", + amount_money: { amount: BigInt(4350), currency: "USD" }, + reason: "CUSTOMER_REQUESTS_CREDIT", + state: "PROCESSING", + due_at: "2022-06-01T00:00:00.000Z", + disputed_payment: { payment_id: "2yeBUWJzllJTpmnSqtMRAL19taB" }, + evidence_ids: ["evidence_ids"], + card_brand: "VISA", + created_at: "2022-05-18T16:02:15.313Z", + updated_at: "2022-05-18T16:02:15.313Z", + brand_dispute_id: "100000399240", + reported_date: "reported_date", + reported_at: "2022-05-18T00:00:00.000Z", + version: 4, + location_id: "LSY8XKGSMMX94", + }, + }; + server + .mockEndpoint() + .post("/v2/disputes/dispute_id/submit-evidence") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.disputes.submitEvidence({ + disputeId: "dispute_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + dispute: { + disputeId: "dispute_id", + id: "EAZoK70gX3fyvibecLwIGB", + amountMoney: { + amount: BigInt("4350"), + currency: "USD", + }, + reason: "CUSTOMER_REQUESTS_CREDIT", + state: "PROCESSING", + dueAt: "2022-06-01T00:00:00.000Z", + disputedPayment: { + paymentId: "2yeBUWJzllJTpmnSqtMRAL19taB", + }, + evidenceIds: ["evidence_ids"], + cardBrand: "VISA", + createdAt: "2022-05-18T16:02:15.313Z", + updatedAt: "2022-05-18T16:02:15.313Z", + brandDisputeId: "100000399240", + reportedDate: "reported_date", + reportedAt: "2022-05-18T00:00:00.000Z", + version: 4, + locationId: "LSY8XKGSMMX94", + }, + }); + }); +}); diff --git a/tests/wire/disputes/evidence.test.ts b/tests/wire/disputes/evidence.test.ts new file mode 100644 index 000000000..e0496da11 --- /dev/null +++ b/tests/wire/disputes/evidence.test.ts @@ -0,0 +1,91 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("Evidence", () => { + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + evidence: { + evidence_id: "evidence_id", + id: "TOomLInj6iWmP3N8qfCXrB", + dispute_id: "bVTprrwk0gygTLZ96VX1oB", + evidence_file: { filename: "customer-interaction.jpg", filetype: "image/jpeg" }, + evidence_text: "evidence_text", + uploaded_at: "2022-05-18T16:01:10.000Z", + evidence_type: "CARDHOLDER_COMMUNICATION", + }, + }; + server + .mockEndpoint() + .get("/v2/disputes/dispute_id/evidence/evidence_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.disputes.evidence.get({ + disputeId: "dispute_id", + evidenceId: "evidence_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + evidence: { + evidenceId: "evidence_id", + id: "TOomLInj6iWmP3N8qfCXrB", + disputeId: "bVTprrwk0gygTLZ96VX1oB", + evidenceFile: { + filename: "customer-interaction.jpg", + filetype: "image/jpeg", + }, + evidenceText: "evidence_text", + uploadedAt: "2022-05-18T16:01:10.000Z", + evidenceType: "CARDHOLDER_COMMUNICATION", + }, + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/disputes/dispute_id/evidence/evidence_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.disputes.evidence.delete({ + disputeId: "dispute_id", + evidenceId: "evidence_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/employees.test.ts b/tests/wire/employees.test.ts new file mode 100644 index 000000000..1e270b2bb --- /dev/null +++ b/tests/wire/employees.test.ts @@ -0,0 +1,56 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Employees", () => { + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + employee: { + id: "id", + first_name: "first_name", + last_name: "last_name", + email: "email", + phone_number: "phone_number", + location_ids: ["location_ids"], + status: "ACTIVE", + is_owner: true, + created_at: "created_at", + updated_at: "updated_at", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server.mockEndpoint().get("/v2/employees/id").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.employees.get({ + id: "id", + }); + expect(response).toEqual({ + employee: { + id: "id", + firstName: "first_name", + lastName: "last_name", + email: "email", + phoneNumber: "phone_number", + locationIds: ["location_ids"], + status: "ACTIVE", + isOwner: true, + createdAt: "created_at", + updatedAt: "updated_at", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/events.test.ts b/tests/wire/events.test.ts new file mode 100644 index 000000000..43a51517f --- /dev/null +++ b/tests/wire/events.test.ts @@ -0,0 +1,193 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Events", () => { + test("SearchEvents", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = {}; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + events: [ + { + merchant_id: "0HPGX5JYE6EE1", + location_id: "VJDQQP3CG14EY", + type: "dispute.state.updated", + event_id: "73ecd468-0aba-424f-b862-583d44efe7c8", + created_at: "2022-04-26T10:08:40.454726", + data: { + type: "dispute", + id: "ORSEVtZAJxb37RA1EiGw", + object: { + dispute: { + amount_money: { amount: 8801, currency: "USD" }, + brand_dispute_id: "r9rKGSBBQbywBNnWWIiGFg", + card_brand: "VISA", + created_at: "2020-02-19T21:24:53.258Z", + disputed_payment: { payment_id: "fbmsaEOpoARDKxiSGH1fqPuqoqFZY" }, + due_at: "2020-03-04T00:00:00.000Z", + id: "ORSEVtZAJxb37RA1EiGw", + location_id: "VJDQQP3CG14EY", + reason: "AMOUNT_DIFFERS", + reported_at: "2020-02-19T00:00:00.000Z", + state: "WON", + updated_at: "2020-02-19T21:34:41.851Z", + version: 6, + }, + }, + }, + }, + ], + metadata: [{ event_id: "73ecd468-0aba-424f-b862-583d44efe7c8", api_version: "2022-12-13" }], + cursor: "6b571fc9773647f=", + }; + server + .mockEndpoint() + .post("/v2/events") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.events.searchEvents(); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + events: [ + { + merchantId: "0HPGX5JYE6EE1", + locationId: "VJDQQP3CG14EY", + type: "dispute.state.updated", + eventId: "73ecd468-0aba-424f-b862-583d44efe7c8", + createdAt: "2022-04-26T10:08:40.454726", + data: { + type: "dispute", + id: "ORSEVtZAJxb37RA1EiGw", + object: { + dispute: { + amount_money: { + amount: 8801, + currency: "USD", + }, + brand_dispute_id: "r9rKGSBBQbywBNnWWIiGFg", + card_brand: "VISA", + created_at: "2020-02-19T21:24:53.258Z", + disputed_payment: { + payment_id: "fbmsaEOpoARDKxiSGH1fqPuqoqFZY", + }, + due_at: "2020-03-04T00:00:00.000Z", + id: "ORSEVtZAJxb37RA1EiGw", + location_id: "VJDQQP3CG14EY", + reason: "AMOUNT_DIFFERS", + reported_at: "2020-02-19T00:00:00.000Z", + state: "WON", + updated_at: "2020-02-19T21:34:41.851Z", + version: 6, + }, + }, + }, + }, + ], + metadata: [ + { + eventId: "73ecd468-0aba-424f-b862-583d44efe7c8", + apiVersion: "2022-12-13", + }, + ], + cursor: "6b571fc9773647f=", + }); + }); + + test("DisableEvents", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server.mockEndpoint().put("/v2/events/disable").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.events.disableEvents(); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("EnableEvents", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server.mockEndpoint().put("/v2/events/enable").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.events.enableEvents(); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("ListEventTypes", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + event_types: ["inventory.count.updated"], + metadata: [ + { + event_type: "inventory.count.updated", + api_version_introduced: "2018-07-12", + release_status: "PUBLIC", + }, + ], + }; + server.mockEndpoint().get("/v2/events/types").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.events.listEventTypes(); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + eventTypes: ["inventory.count.updated"], + metadata: [ + { + eventType: "inventory.count.updated", + apiVersionIntroduced: "2018-07-12", + releaseStatus: "PUBLIC", + }, + ], + }); + }); +}); diff --git a/tests/wire/giftCards.test.ts b/tests/wire/giftCards.test.ts new file mode 100644 index 000000000..ed74f1206 --- /dev/null +++ b/tests/wire/giftCards.test.ts @@ -0,0 +1,335 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("GiftCards", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "NC9Tm69EjbjtConu", + location_id: "81FN9BNFZTKS4", + gift_card: { type: "DIGITAL" }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + gift_card: { + id: "gftc:6cbacbb64cf54e2ca9f573d619038059", + type: "DIGITAL", + gan_source: "SQUARE", + state: "PENDING", + balance_money: { amount: BigInt(0), currency: "USD" }, + gan: "7783320006753271", + created_at: "2021-05-20T22:26:54.000Z", + customer_ids: ["customer_ids"], + }, + }; + server + .mockEndpoint() + .post("/v2/gift-cards") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.giftCards.create({ + idempotencyKey: "NC9Tm69EjbjtConu", + locationId: "81FN9BNFZTKS4", + giftCard: { + type: "DIGITAL", + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + giftCard: { + id: "gftc:6cbacbb64cf54e2ca9f573d619038059", + type: "DIGITAL", + ganSource: "SQUARE", + state: "PENDING", + balanceMoney: { + amount: BigInt("0"), + currency: "USD", + }, + gan: "7783320006753271", + createdAt: "2021-05-20T22:26:54.000Z", + customerIds: ["customer_ids"], + }, + }); + }); + + test("getFromGAN", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { gan: "7783320001001635" }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + gift_card: { + id: "gftc:6944163553804e439d89adb47caf806a", + type: "DIGITAL", + gan_source: "SQUARE", + state: "ACTIVE", + balance_money: { amount: BigInt(5000), currency: "USD" }, + gan: "7783320001001635", + created_at: "2021-05-20T22:26:54.000Z", + customer_ids: ["customer_ids"], + }, + }; + server + .mockEndpoint() + .post("/v2/gift-cards/from-gan") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.giftCards.getFromGan({ + gan: "7783320001001635", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + giftCard: { + id: "gftc:6944163553804e439d89adb47caf806a", + type: "DIGITAL", + ganSource: "SQUARE", + state: "ACTIVE", + balanceMoney: { + amount: BigInt("5000"), + currency: "USD", + }, + gan: "7783320001001635", + createdAt: "2021-05-20T22:26:54.000Z", + customerIds: ["customer_ids"], + }, + }); + }); + + test("getFromNonce", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { nonce: "cnon:7783322135245171" }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + gift_card: { + id: "gftc:6944163553804e439d89adb47caf806a", + type: "DIGITAL", + gan_source: "SQUARE", + state: "ACTIVE", + balance_money: { amount: BigInt(5000), currency: "USD" }, + gan: "7783320001001635", + created_at: "2021-05-20T22:26:54.000Z", + customer_ids: ["customer_ids"], + }, + }; + server + .mockEndpoint() + .post("/v2/gift-cards/from-nonce") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.giftCards.getFromNonce({ + nonce: "cnon:7783322135245171", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + giftCard: { + id: "gftc:6944163553804e439d89adb47caf806a", + type: "DIGITAL", + ganSource: "SQUARE", + state: "ACTIVE", + balanceMoney: { + amount: BigInt("5000"), + currency: "USD", + }, + gan: "7783320001001635", + createdAt: "2021-05-20T22:26:54.000Z", + customerIds: ["customer_ids"], + }, + }); + }); + + test("LinkCustomer", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { customer_id: "GKY0FZ3V717AH8Q2D821PNT2ZW" }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + gift_card: { + id: "gftc:71ea002277a34f8a945e284b04822edb", + type: "DIGITAL", + gan_source: "SQUARE", + state: "ACTIVE", + balance_money: { amount: BigInt(2500), currency: "USD" }, + gan: "7783320005440920", + created_at: "2021-03-25T05:13:01Z", + customer_ids: ["GKY0FZ3V717AH8Q2D821PNT2ZW"], + }, + }; + server + .mockEndpoint() + .post("/v2/gift-cards/gift_card_id/link-customer") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.giftCards.linkCustomer({ + giftCardId: "gift_card_id", + customerId: "GKY0FZ3V717AH8Q2D821PNT2ZW", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + giftCard: { + id: "gftc:71ea002277a34f8a945e284b04822edb", + type: "DIGITAL", + ganSource: "SQUARE", + state: "ACTIVE", + balanceMoney: { + amount: BigInt("2500"), + currency: "USD", + }, + gan: "7783320005440920", + createdAt: "2021-03-25T05:13:01Z", + customerIds: ["GKY0FZ3V717AH8Q2D821PNT2ZW"], + }, + }); + }); + + test("UnlinkCustomer", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { customer_id: "GKY0FZ3V717AH8Q2D821PNT2ZW" }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + gift_card: { + id: "gftc:71ea002277a34f8a945e284b04822edb", + type: "DIGITAL", + gan_source: "SQUARE", + state: "ACTIVE", + balance_money: { amount: BigInt(2500), currency: "USD" }, + gan: "7783320005440920", + created_at: "2021-03-25T05:13:01Z", + customer_ids: ["customer_ids"], + }, + }; + server + .mockEndpoint() + .post("/v2/gift-cards/gift_card_id/unlink-customer") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.giftCards.unlinkCustomer({ + giftCardId: "gift_card_id", + customerId: "GKY0FZ3V717AH8Q2D821PNT2ZW", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + giftCard: { + id: "gftc:71ea002277a34f8a945e284b04822edb", + type: "DIGITAL", + ganSource: "SQUARE", + state: "ACTIVE", + balanceMoney: { + amount: BigInt("2500"), + currency: "USD", + }, + gan: "7783320005440920", + createdAt: "2021-03-25T05:13:01Z", + customerIds: ["customer_ids"], + }, + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + gift_card: { + id: "gftc:00113070ba5745f0b2377c1b9570cb03", + type: "DIGITAL", + gan_source: "SQUARE", + state: "ACTIVE", + balance_money: { amount: BigInt(1000), currency: "USD" }, + gan: "7783320001001635", + created_at: "2021-05-20T22:26:54.000Z", + customer_ids: ["customer_ids"], + }, + }; + server.mockEndpoint().get("/v2/gift-cards/id").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.giftCards.get({ + id: "id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + giftCard: { + id: "gftc:00113070ba5745f0b2377c1b9570cb03", + type: "DIGITAL", + ganSource: "SQUARE", + state: "ACTIVE", + balanceMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + gan: "7783320001001635", + createdAt: "2021-05-20T22:26:54.000Z", + customerIds: ["customer_ids"], + }, + }); + }); +}); diff --git a/tests/wire/giftCards/activities.test.ts b/tests/wire/giftCards/activities.test.ts new file mode 100644 index 000000000..fd98a1564 --- /dev/null +++ b/tests/wire/giftCards/activities.test.ts @@ -0,0 +1,191 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("Activities", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "U16kfr-kA70er-q4Rsym-7U7NnY", + gift_card_activity: { + type: "ACTIVATE", + location_id: "81FN9BNFZTKS4", + gift_card_id: "gftc:6d55a72470d940c6ba09c0ab8ad08d20", + activate_activity_details: { + order_id: "jJNGHm4gLI6XkFbwtiSLqK72KkAZY", + line_item_uid: "eIWl7X0nMuO9Ewbh0ChIx", + }, + }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + gift_card_activity: { + id: "gcact_c8f8cbf1f24b448d8ecf39ed03f97864", + type: "ACTIVATE", + location_id: "81FN9BNFZTKS4", + created_at: "2021-05-20T22:26:54.000Z", + gift_card_id: "gftc:6d55a72470d940c6ba09c0ab8ad08d20", + gift_card_gan: "7783320002929081", + gift_card_balance_money: { amount: BigInt(1000), currency: "USD" }, + load_activity_details: { + order_id: "order_id", + line_item_uid: "line_item_uid", + reference_id: "reference_id", + buyer_payment_instrument_ids: ["buyer_payment_instrument_ids"], + }, + activate_activity_details: { + amount_money: { amount: BigInt(1000), currency: "USD" }, + order_id: "jJNGHm4gLI6XkFbwtiSLqK72KkAZY", + line_item_uid: "eIWl7X0nMuO9Ewbh0ChIx", + reference_id: "reference_id", + buyer_payment_instrument_ids: ["buyer_payment_instrument_ids"], + }, + redeem_activity_details: { + amount_money: {}, + payment_id: "payment_id", + reference_id: "reference_id", + status: "PENDING", + }, + clear_balance_activity_details: { reason: "SUSPICIOUS_ACTIVITY" }, + deactivate_activity_details: { reason: "SUSPICIOUS_ACTIVITY" }, + adjust_increment_activity_details: { amount_money: {}, reason: "COMPLIMENTARY" }, + adjust_decrement_activity_details: { amount_money: {}, reason: "SUSPICIOUS_ACTIVITY" }, + refund_activity_details: { + redeem_activity_id: "redeem_activity_id", + reference_id: "reference_id", + payment_id: "payment_id", + }, + unlinked_activity_refund_activity_details: { + amount_money: {}, + reference_id: "reference_id", + payment_id: "payment_id", + }, + import_activity_details: { amount_money: {} }, + block_activity_details: { reason: "CHARGEBACK_BLOCK" }, + unblock_activity_details: { reason: "CHARGEBACK_UNBLOCK" }, + import_reversal_activity_details: { amount_money: {} }, + transfer_balance_to_activity_details: { + transfer_from_gift_card_id: "transfer_from_gift_card_id", + amount_money: {}, + }, + transfer_balance_from_activity_details: { + transfer_to_gift_card_id: "transfer_to_gift_card_id", + amount_money: {}, + }, + }, + }; + server + .mockEndpoint() + .post("/v2/gift-cards/activities") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.giftCards.activities.create({ + idempotencyKey: "U16kfr-kA70er-q4Rsym-7U7NnY", + giftCardActivity: { + type: "ACTIVATE", + locationId: "81FN9BNFZTKS4", + giftCardId: "gftc:6d55a72470d940c6ba09c0ab8ad08d20", + activateActivityDetails: { + orderId: "jJNGHm4gLI6XkFbwtiSLqK72KkAZY", + lineItemUid: "eIWl7X0nMuO9Ewbh0ChIx", + }, + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + giftCardActivity: { + id: "gcact_c8f8cbf1f24b448d8ecf39ed03f97864", + type: "ACTIVATE", + locationId: "81FN9BNFZTKS4", + createdAt: "2021-05-20T22:26:54.000Z", + giftCardId: "gftc:6d55a72470d940c6ba09c0ab8ad08d20", + giftCardGan: "7783320002929081", + giftCardBalanceMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + loadActivityDetails: { + orderId: "order_id", + lineItemUid: "line_item_uid", + referenceId: "reference_id", + buyerPaymentInstrumentIds: ["buyer_payment_instrument_ids"], + }, + activateActivityDetails: { + amountMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + orderId: "jJNGHm4gLI6XkFbwtiSLqK72KkAZY", + lineItemUid: "eIWl7X0nMuO9Ewbh0ChIx", + referenceId: "reference_id", + buyerPaymentInstrumentIds: ["buyer_payment_instrument_ids"], + }, + redeemActivityDetails: { + amountMoney: {}, + paymentId: "payment_id", + referenceId: "reference_id", + status: "PENDING", + }, + clearBalanceActivityDetails: { + reason: "SUSPICIOUS_ACTIVITY", + }, + deactivateActivityDetails: { + reason: "SUSPICIOUS_ACTIVITY", + }, + adjustIncrementActivityDetails: { + amountMoney: {}, + reason: "COMPLIMENTARY", + }, + adjustDecrementActivityDetails: { + amountMoney: {}, + reason: "SUSPICIOUS_ACTIVITY", + }, + refundActivityDetails: { + redeemActivityId: "redeem_activity_id", + referenceId: "reference_id", + paymentId: "payment_id", + }, + unlinkedActivityRefundActivityDetails: { + amountMoney: {}, + referenceId: "reference_id", + paymentId: "payment_id", + }, + importActivityDetails: { + amountMoney: {}, + }, + blockActivityDetails: { + reason: "CHARGEBACK_BLOCK", + }, + unblockActivityDetails: { + reason: "CHARGEBACK_UNBLOCK", + }, + importReversalActivityDetails: { + amountMoney: {}, + }, + transferBalanceToActivityDetails: { + transferFromGiftCardId: "transfer_from_gift_card_id", + amountMoney: {}, + }, + transferBalanceFromActivityDetails: { + transferToGiftCardId: "transfer_to_gift_card_id", + amountMoney: {}, + }, + }, + }); + }); +}); diff --git a/tests/wire/inventory.test.ts b/tests/wire/inventory.test.ts new file mode 100644 index 000000000..cf796a8b6 --- /dev/null +++ b/tests/wire/inventory.test.ts @@ -0,0 +1,730 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Inventory", () => { + test("DeprecatedGetAdjustment", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + adjustment: { + id: "UDMOEO78BG6GYWA2XDRYX3KB", + reference_id: "4a366069-4096-47a2-99a5-0084ac879509", + from_state: "IN_STOCK", + to_state: "SOLD", + location_id: "C6W5YS5QM06F5", + catalog_object_id: "W62UWFY35CWMYGVWK6TWJDNI", + catalog_object_type: "ITEM_VARIATION", + quantity: "7", + total_price_money: { amount: BigInt(4550), currency: "USD" }, + occurred_at: "2016-11-16T25:44:22.837Z", + created_at: "2016-11-17T13:02:15.142Z", + source: { + product: "SQUARE_POS", + application_id: "416ff29c-86c4-4feb-b58c-9705f21f3ea0", + name: "Square Point of Sale 4.37", + }, + employee_id: "employee_id", + team_member_id: "LRK57NSQ5X7PUD05", + transaction_id: "transaction_id", + refund_id: "refund_id", + purchase_order_id: "purchase_order_id", + goods_receipt_id: "goods_receipt_id", + adjustment_group: { + id: "id", + root_adjustment_id: "root_adjustment_id", + from_state: "CUSTOM", + to_state: "CUSTOM", + }, + }, + }; + server + .mockEndpoint() + .get("/v2/inventory/adjustment/adjustment_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.inventory.deprecatedGetAdjustment({ + adjustmentId: "adjustment_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + adjustment: { + id: "UDMOEO78BG6GYWA2XDRYX3KB", + referenceId: "4a366069-4096-47a2-99a5-0084ac879509", + fromState: "IN_STOCK", + toState: "SOLD", + locationId: "C6W5YS5QM06F5", + catalogObjectId: "W62UWFY35CWMYGVWK6TWJDNI", + catalogObjectType: "ITEM_VARIATION", + quantity: "7", + totalPriceMoney: { + amount: BigInt("4550"), + currency: "USD", + }, + occurredAt: "2016-11-16T25:44:22.837Z", + createdAt: "2016-11-17T13:02:15.142Z", + source: { + product: "SQUARE_POS", + applicationId: "416ff29c-86c4-4feb-b58c-9705f21f3ea0", + name: "Square Point of Sale 4.37", + }, + employeeId: "employee_id", + teamMemberId: "LRK57NSQ5X7PUD05", + transactionId: "transaction_id", + refundId: "refund_id", + purchaseOrderId: "purchase_order_id", + goodsReceiptId: "goods_receipt_id", + adjustmentGroup: { + id: "id", + rootAdjustmentId: "root_adjustment_id", + fromState: "CUSTOM", + toState: "CUSTOM", + }, + }, + }); + }); + + test("getAdjustment", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + adjustment: { + id: "UDMOEO78BG6GYWA2XDRYX3KB", + reference_id: "4a366069-4096-47a2-99a5-0084ac879509", + from_state: "IN_STOCK", + to_state: "SOLD", + location_id: "C6W5YS5QM06F5", + catalog_object_id: "W62UWFY35CWMYGVWK6TWJDNI", + catalog_object_type: "ITEM_VARIATION", + quantity: "7", + total_price_money: { amount: BigInt(4550), currency: "USD" }, + occurred_at: "2016-11-16T25:44:22.837Z", + created_at: "2016-11-17T13:02:15.142Z", + source: { + product: "SQUARE_POS", + application_id: "416ff29c-86c4-4feb-b58c-9705f21f3ea0", + name: "Square Point of Sale 4.37", + }, + employee_id: "employee_id", + team_member_id: "LRK57NSQ5X7PUD05", + transaction_id: "transaction_id", + refund_id: "refund_id", + purchase_order_id: "purchase_order_id", + goods_receipt_id: "goods_receipt_id", + adjustment_group: { + id: "id", + root_adjustment_id: "root_adjustment_id", + from_state: "CUSTOM", + to_state: "CUSTOM", + }, + }, + }; + server + .mockEndpoint() + .get("/v2/inventory/adjustments/adjustment_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.inventory.getAdjustment({ + adjustmentId: "adjustment_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + adjustment: { + id: "UDMOEO78BG6GYWA2XDRYX3KB", + referenceId: "4a366069-4096-47a2-99a5-0084ac879509", + fromState: "IN_STOCK", + toState: "SOLD", + locationId: "C6W5YS5QM06F5", + catalogObjectId: "W62UWFY35CWMYGVWK6TWJDNI", + catalogObjectType: "ITEM_VARIATION", + quantity: "7", + totalPriceMoney: { + amount: BigInt("4550"), + currency: "USD", + }, + occurredAt: "2016-11-16T25:44:22.837Z", + createdAt: "2016-11-17T13:02:15.142Z", + source: { + product: "SQUARE_POS", + applicationId: "416ff29c-86c4-4feb-b58c-9705f21f3ea0", + name: "Square Point of Sale 4.37", + }, + employeeId: "employee_id", + teamMemberId: "LRK57NSQ5X7PUD05", + transactionId: "transaction_id", + refundId: "refund_id", + purchaseOrderId: "purchase_order_id", + goodsReceiptId: "goods_receipt_id", + adjustmentGroup: { + id: "id", + rootAdjustmentId: "root_adjustment_id", + fromState: "CUSTOM", + toState: "CUSTOM", + }, + }, + }); + }); + + test("DeprecatedBatchChange", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "8fc6a5b0-9fe8-4b46-b46b-2ef95793abbe", + changes: [ + { + type: "PHYSICAL_COUNT", + physical_count: { + reference_id: "1536bfbf-efed-48bf-b17d-a197141b2a92", + catalog_object_id: "W62UWFY35CWMYGVWK6TWJDNI", + state: "IN_STOCK", + location_id: "C6W5YS5QM06F5", + quantity: "53", + team_member_id: "LRK57NSQ5X7PUD05", + occurred_at: "2016-11-16T22:25:24.878Z", + }, + }, + ], + ignore_unchanged_counts: true, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + counts: [ + { + catalog_object_id: "W62UWFY35CWMYGVWK6TWJDNI", + catalog_object_type: "ITEM_VARIATION", + state: "IN_STOCK", + location_id: "C6W5YS5QM06F5", + quantity: "53", + calculated_at: "2016-11-16T22:28:01.223Z", + is_estimated: true, + }, + ], + changes: [{ type: "PHYSICAL_COUNT", measurement_unit_id: "measurement_unit_id" }], + }; + server + .mockEndpoint() + .post("/v2/inventory/batch-change") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.inventory.deprecatedBatchChange({ + idempotencyKey: "8fc6a5b0-9fe8-4b46-b46b-2ef95793abbe", + changes: [ + { + type: "PHYSICAL_COUNT", + physicalCount: { + referenceId: "1536bfbf-efed-48bf-b17d-a197141b2a92", + catalogObjectId: "W62UWFY35CWMYGVWK6TWJDNI", + state: "IN_STOCK", + locationId: "C6W5YS5QM06F5", + quantity: "53", + teamMemberId: "LRK57NSQ5X7PUD05", + occurredAt: "2016-11-16T22:25:24.878Z", + }, + }, + ], + ignoreUnchangedCounts: true, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + counts: [ + { + catalogObjectId: "W62UWFY35CWMYGVWK6TWJDNI", + catalogObjectType: "ITEM_VARIATION", + state: "IN_STOCK", + locationId: "C6W5YS5QM06F5", + quantity: "53", + calculatedAt: "2016-11-16T22:28:01.223Z", + isEstimated: true, + }, + ], + changes: [ + { + type: "PHYSICAL_COUNT", + measurementUnitId: "measurement_unit_id", + }, + ], + }); + }); + + test("DeprecatedBatchGetChanges", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + catalog_object_ids: ["W62UWFY35CWMYGVWK6TWJDNI"], + location_ids: ["C6W5YS5QM06F5"], + types: ["PHYSICAL_COUNT"], + states: ["IN_STOCK"], + updated_after: "2016-11-01T00:00:00.000Z", + updated_before: "2016-12-01T00:00:00.000Z", + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + changes: [ + { + type: "PHYSICAL_COUNT", + physical_count: { + id: "46YDTW253DWGGK9HMAE6XCAO", + reference_id: "22c07cf4-5626-4224-89f9-691112019399", + catalog_object_id: "W62UWFY35CWMYGVWK6TWJDNI", + catalog_object_type: "ITEM_VARIATION", + state: "IN_STOCK", + location_id: "C6W5YS5QM06F5", + quantity: "86", + source: { + product: "SQUARE_POS", + application_id: "416ff29c-86c4-4feb-b58c-9705f21f3ea0", + name: "Square Point of Sale 4.37", + }, + team_member_id: "LRK57NSQ5X7PUD05", + occurred_at: "2016-11-16T22:24:49.028Z", + created_at: "2016-11-16T22:25:24.878Z", + }, + measurement_unit_id: "measurement_unit_id", + }, + ], + cursor: "cursor", + }; + server + .mockEndpoint() + .post("/v2/inventory/batch-retrieve-changes") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.inventory.deprecatedBatchGetChanges({ + catalogObjectIds: ["W62UWFY35CWMYGVWK6TWJDNI"], + locationIds: ["C6W5YS5QM06F5"], + types: ["PHYSICAL_COUNT"], + states: ["IN_STOCK"], + updatedAfter: "2016-11-01T00:00:00.000Z", + updatedBefore: "2016-12-01T00:00:00.000Z", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + changes: [ + { + type: "PHYSICAL_COUNT", + physicalCount: { + id: "46YDTW253DWGGK9HMAE6XCAO", + referenceId: "22c07cf4-5626-4224-89f9-691112019399", + catalogObjectId: "W62UWFY35CWMYGVWK6TWJDNI", + catalogObjectType: "ITEM_VARIATION", + state: "IN_STOCK", + locationId: "C6W5YS5QM06F5", + quantity: "86", + source: { + product: "SQUARE_POS", + applicationId: "416ff29c-86c4-4feb-b58c-9705f21f3ea0", + name: "Square Point of Sale 4.37", + }, + teamMemberId: "LRK57NSQ5X7PUD05", + occurredAt: "2016-11-16T22:24:49.028Z", + createdAt: "2016-11-16T22:25:24.878Z", + }, + measurementUnitId: "measurement_unit_id", + }, + ], + cursor: "cursor", + }); + }); + + test("DeprecatedBatchGetCounts", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + catalog_object_ids: ["W62UWFY35CWMYGVWK6TWJDNI"], + location_ids: ["59TNP9SA8VGDA"], + updated_after: "2016-11-16T00:00:00.000Z", + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + counts: [ + { + catalog_object_id: "W62UWFY35CWMYGVWK6TWJDNI", + catalog_object_type: "ITEM_VARIATION", + state: "IN_STOCK", + location_id: "59TNP9SA8VGDA", + quantity: "79", + calculated_at: "2016-11-16T22:28:01.223Z", + is_estimated: true, + }, + ], + cursor: "cursor", + }; + server + .mockEndpoint() + .post("/v2/inventory/batch-retrieve-counts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.inventory.deprecatedBatchGetCounts({ + catalogObjectIds: ["W62UWFY35CWMYGVWK6TWJDNI"], + locationIds: ["59TNP9SA8VGDA"], + updatedAfter: "2016-11-16T00:00:00.000Z", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + counts: [ + { + catalogObjectId: "W62UWFY35CWMYGVWK6TWJDNI", + catalogObjectType: "ITEM_VARIATION", + state: "IN_STOCK", + locationId: "59TNP9SA8VGDA", + quantity: "79", + calculatedAt: "2016-11-16T22:28:01.223Z", + isEstimated: true, + }, + ], + cursor: "cursor", + }); + }); + + test("BatchCreateChanges", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "8fc6a5b0-9fe8-4b46-b46b-2ef95793abbe", + changes: [ + { + type: "PHYSICAL_COUNT", + physical_count: { + reference_id: "1536bfbf-efed-48bf-b17d-a197141b2a92", + catalog_object_id: "W62UWFY35CWMYGVWK6TWJDNI", + state: "IN_STOCK", + location_id: "C6W5YS5QM06F5", + quantity: "53", + team_member_id: "LRK57NSQ5X7PUD05", + occurred_at: "2016-11-16T22:25:24.878Z", + }, + }, + ], + ignore_unchanged_counts: true, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + counts: [ + { + catalog_object_id: "W62UWFY35CWMYGVWK6TWJDNI", + catalog_object_type: "ITEM_VARIATION", + state: "IN_STOCK", + location_id: "C6W5YS5QM06F5", + quantity: "53", + calculated_at: "2016-11-16T22:28:01.223Z", + is_estimated: true, + }, + ], + changes: [{ type: "PHYSICAL_COUNT", measurement_unit_id: "measurement_unit_id" }], + }; + server + .mockEndpoint() + .post("/v2/inventory/changes/batch-create") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.inventory.batchCreateChanges({ + idempotencyKey: "8fc6a5b0-9fe8-4b46-b46b-2ef95793abbe", + changes: [ + { + type: "PHYSICAL_COUNT", + physicalCount: { + referenceId: "1536bfbf-efed-48bf-b17d-a197141b2a92", + catalogObjectId: "W62UWFY35CWMYGVWK6TWJDNI", + state: "IN_STOCK", + locationId: "C6W5YS5QM06F5", + quantity: "53", + teamMemberId: "LRK57NSQ5X7PUD05", + occurredAt: "2016-11-16T22:25:24.878Z", + }, + }, + ], + ignoreUnchangedCounts: true, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + counts: [ + { + catalogObjectId: "W62UWFY35CWMYGVWK6TWJDNI", + catalogObjectType: "ITEM_VARIATION", + state: "IN_STOCK", + locationId: "C6W5YS5QM06F5", + quantity: "53", + calculatedAt: "2016-11-16T22:28:01.223Z", + isEstimated: true, + }, + ], + changes: [ + { + type: "PHYSICAL_COUNT", + measurementUnitId: "measurement_unit_id", + }, + ], + }); + }); + + test("deprecatedGetPhysicalCount", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + count: { + id: "ANZADNPLKADOJKJIUANKLMLQ", + reference_id: "f857ec37-f9a0-4458-8e23-5b5e0bea4e53", + catalog_object_id: "W62UWFY35CWMYGVWK6TWJDNI", + catalog_object_type: "ITEM_VARIATION", + state: "IN_STOCK", + location_id: "C6W5YS5QM06F5", + quantity: "15", + source: { + product: "SQUARE_POS", + application_id: "416ff29c-86c4-4feb-b58c-9705f21f3ea0", + name: "Square Point of Sale 4.37", + }, + employee_id: "employee_id", + team_member_id: "LRK57NSQ5X7PUD05", + occurred_at: "2016-11-16T22:25:24.878Z", + created_at: "2016-11-16T22:25:24.878Z", + }, + }; + server + .mockEndpoint() + .get("/v2/inventory/physical-count/physical_count_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.inventory.deprecatedGetPhysicalCount({ + physicalCountId: "physical_count_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + count: { + id: "ANZADNPLKADOJKJIUANKLMLQ", + referenceId: "f857ec37-f9a0-4458-8e23-5b5e0bea4e53", + catalogObjectId: "W62UWFY35CWMYGVWK6TWJDNI", + catalogObjectType: "ITEM_VARIATION", + state: "IN_STOCK", + locationId: "C6W5YS5QM06F5", + quantity: "15", + source: { + product: "SQUARE_POS", + applicationId: "416ff29c-86c4-4feb-b58c-9705f21f3ea0", + name: "Square Point of Sale 4.37", + }, + employeeId: "employee_id", + teamMemberId: "LRK57NSQ5X7PUD05", + occurredAt: "2016-11-16T22:25:24.878Z", + createdAt: "2016-11-16T22:25:24.878Z", + }, + }); + }); + + test("getPhysicalCount", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + count: { + id: "ANZADNPLKADOJKJIUANKLMLQ", + reference_id: "f857ec37-f9a0-4458-8e23-5b5e0bea4e53", + catalog_object_id: "W62UWFY35CWMYGVWK6TWJDNI", + catalog_object_type: "ITEM_VARIATION", + state: "IN_STOCK", + location_id: "C6W5YS5QM06F5", + quantity: "15", + source: { + product: "SQUARE_POS", + application_id: "416ff29c-86c4-4feb-b58c-9705f21f3ea0", + name: "Square Point of Sale 4.37", + }, + employee_id: "employee_id", + team_member_id: "LRK57NSQ5X7PUD05", + occurred_at: "2016-11-16T22:25:24.878Z", + created_at: "2016-11-16T22:25:24.878Z", + }, + }; + server + .mockEndpoint() + .get("/v2/inventory/physical-counts/physical_count_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.inventory.getPhysicalCount({ + physicalCountId: "physical_count_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + count: { + id: "ANZADNPLKADOJKJIUANKLMLQ", + referenceId: "f857ec37-f9a0-4458-8e23-5b5e0bea4e53", + catalogObjectId: "W62UWFY35CWMYGVWK6TWJDNI", + catalogObjectType: "ITEM_VARIATION", + state: "IN_STOCK", + locationId: "C6W5YS5QM06F5", + quantity: "15", + source: { + product: "SQUARE_POS", + applicationId: "416ff29c-86c4-4feb-b58c-9705f21f3ea0", + name: "Square Point of Sale 4.37", + }, + employeeId: "employee_id", + teamMemberId: "LRK57NSQ5X7PUD05", + occurredAt: "2016-11-16T22:25:24.878Z", + createdAt: "2016-11-16T22:25:24.878Z", + }, + }); + }); + + test("getTransfer", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + transfer: { + id: "UDMOEO78BG6GYWA2XDRYX3KB", + reference_id: "4a366069-4096-47a2-99a5-0084ac879509", + state: "IN_STOCK", + from_location_id: "C6W5YS5QM06F5", + to_location_id: "59TNP9SA8VGDA", + catalog_object_id: "W62UWFY35CWMYGVWK6TWJDNI", + catalog_object_type: "ITEM_VARIATION", + quantity: "7", + occurred_at: "2016-11-16T25:44:22.837Z", + created_at: "2016-11-17T13:02:15.142Z", + source: { + product: "SQUARE_POS", + application_id: "416ff29c-86c4-4feb-b58c-9705f21f3ea0", + name: "Square Point of Sale 4.37", + }, + employee_id: "employee_id", + team_member_id: "LRK57NSQ5X7PUD05", + }, + }; + server + .mockEndpoint() + .get("/v2/inventory/transfers/transfer_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.inventory.getTransfer({ + transferId: "transfer_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + transfer: { + id: "UDMOEO78BG6GYWA2XDRYX3KB", + referenceId: "4a366069-4096-47a2-99a5-0084ac879509", + state: "IN_STOCK", + fromLocationId: "C6W5YS5QM06F5", + toLocationId: "59TNP9SA8VGDA", + catalogObjectId: "W62UWFY35CWMYGVWK6TWJDNI", + catalogObjectType: "ITEM_VARIATION", + quantity: "7", + occurredAt: "2016-11-16T25:44:22.837Z", + createdAt: "2016-11-17T13:02:15.142Z", + source: { + product: "SQUARE_POS", + applicationId: "416ff29c-86c4-4feb-b58c-9705f21f3ea0", + name: "Square Point of Sale 4.37", + }, + employeeId: "employee_id", + teamMemberId: "LRK57NSQ5X7PUD05", + }, + }); + }); +}); diff --git a/tests/wire/invoices.test.ts b/tests/wire/invoices.test.ts new file mode 100644 index 000000000..01fff266f --- /dev/null +++ b/tests/wire/invoices.test.ts @@ -0,0 +1,1328 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Invoices", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + invoice: { + location_id: "ES0RJRZYEC39A", + order_id: "CAISENgvlJ6jLWAzERDzjyHVybY", + primary_recipient: { customer_id: "JDKYHBWT1D4F8MFH63DBMEN8Y4" }, + payment_requests: [ + { + request_type: "BALANCE", + due_date: "2030-01-24", + tipping_enabled: true, + automatic_payment_source: "NONE", + reminders: [{ relative_scheduled_days: -1, message: "Your invoice is due tomorrow" }], + }, + ], + delivery_method: "EMAIL", + invoice_number: "inv-100", + title: "Event Planning Services", + description: "We appreciate your business!", + scheduled_at: "2030-01-13T10:00:00Z", + accepted_payment_methods: { + card: true, + square_gift_card: false, + bank_account: false, + buy_now_pay_later: false, + cash_app_pay: false, + }, + custom_fields: [ + { label: "Event Reference Number", value: "Ref. #1234", placement: "ABOVE_LINE_ITEMS" }, + { label: "Terms of Service", value: "The terms of service are...", placement: "BELOW_LINE_ITEMS" }, + ], + sale_or_service_date: "2030-01-24", + store_payment_method_enabled: false, + }, + idempotency_key: "ce3748f9-5fc1-4762-aa12-aae5e843f1f4", + }; + const rawResponseBody = { + invoice: { + id: "inv:0-ChCHu2mZEabLeeHahQnXDjZQECY", + version: 0, + location_id: "ES0RJRZYEC39A", + order_id: "CAISENgvlJ6jLWAzERDzjyHVybY", + primary_recipient: { + customer_id: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + given_name: "Amelia", + family_name: "Earhart", + email_address: "Amelia.Earhart@example.com", + phone_number: "1-212-555-4240", + company_name: "company_name", + }, + payment_requests: [ + { + uid: "2da7964f-f3d2-4f43-81e8-5aa220bf3355", + request_type: "BALANCE", + due_date: "2030-01-24", + tipping_enabled: true, + automatic_payment_source: "NONE", + reminders: [ + { + uid: "beebd363-e47f-4075-8785-c235aaa7df11", + relative_scheduled_days: -1, + message: "Your invoice is due tomorrow", + status: "PENDING", + }, + ], + computed_amount_money: { amount: BigInt(10000), currency: "USD" }, + total_completed_amount_money: { amount: BigInt(0), currency: "USD" }, + }, + ], + delivery_method: "EMAIL", + invoice_number: "inv-100", + title: "Event Planning Services", + description: "We appreciate your business!", + scheduled_at: "2030-01-13T10:00:00Z", + public_url: "public_url", + next_payment_amount_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + status: "DRAFT", + timezone: "America/Los_Angeles", + created_at: "2020-06-18T17:45:13Z", + updated_at: "2020-06-18T17:45:13Z", + accepted_payment_methods: { + card: true, + square_gift_card: false, + bank_account: false, + buy_now_pay_later: false, + cash_app_pay: false, + }, + custom_fields: [ + { label: "Event Reference Number", value: "Ref. #1234", placement: "ABOVE_LINE_ITEMS" }, + { label: "Terms of Service", value: "The terms of service are...", placement: "BELOW_LINE_ITEMS" }, + ], + subscription_id: "subscription_id", + sale_or_service_date: "2030-01-24", + payment_conditions: "payment_conditions", + store_payment_method_enabled: false, + attachments: [{}], + creator_team_member_id: "creator_team_member_id", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/invoices") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.invoices.create({ + invoice: { + locationId: "ES0RJRZYEC39A", + orderId: "CAISENgvlJ6jLWAzERDzjyHVybY", + primaryRecipient: { + customerId: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + }, + paymentRequests: [ + { + requestType: "BALANCE", + dueDate: "2030-01-24", + tippingEnabled: true, + automaticPaymentSource: "NONE", + reminders: [ + { + relativeScheduledDays: -1, + message: "Your invoice is due tomorrow", + }, + ], + }, + ], + deliveryMethod: "EMAIL", + invoiceNumber: "inv-100", + title: "Event Planning Services", + description: "We appreciate your business!", + scheduledAt: "2030-01-13T10:00:00Z", + acceptedPaymentMethods: { + card: true, + squareGiftCard: false, + bankAccount: false, + buyNowPayLater: false, + cashAppPay: false, + }, + customFields: [ + { + label: "Event Reference Number", + value: "Ref. #1234", + placement: "ABOVE_LINE_ITEMS", + }, + { + label: "Terms of Service", + value: "The terms of service are...", + placement: "BELOW_LINE_ITEMS", + }, + ], + saleOrServiceDate: "2030-01-24", + storePaymentMethodEnabled: false, + }, + idempotencyKey: "ce3748f9-5fc1-4762-aa12-aae5e843f1f4", + }); + expect(response).toEqual({ + invoice: { + id: "inv:0-ChCHu2mZEabLeeHahQnXDjZQECY", + version: 0, + locationId: "ES0RJRZYEC39A", + orderId: "CAISENgvlJ6jLWAzERDzjyHVybY", + primaryRecipient: { + customerId: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + givenName: "Amelia", + familyName: "Earhart", + emailAddress: "Amelia.Earhart@example.com", + phoneNumber: "1-212-555-4240", + companyName: "company_name", + }, + paymentRequests: [ + { + uid: "2da7964f-f3d2-4f43-81e8-5aa220bf3355", + requestType: "BALANCE", + dueDate: "2030-01-24", + tippingEnabled: true, + automaticPaymentSource: "NONE", + reminders: [ + { + uid: "beebd363-e47f-4075-8785-c235aaa7df11", + relativeScheduledDays: -1, + message: "Your invoice is due tomorrow", + status: "PENDING", + }, + ], + computedAmountMoney: { + amount: BigInt("10000"), + currency: "USD", + }, + totalCompletedAmountMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + ], + deliveryMethod: "EMAIL", + invoiceNumber: "inv-100", + title: "Event Planning Services", + description: "We appreciate your business!", + scheduledAt: "2030-01-13T10:00:00Z", + publicUrl: "public_url", + nextPaymentAmountMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + status: "DRAFT", + timezone: "America/Los_Angeles", + createdAt: "2020-06-18T17:45:13Z", + updatedAt: "2020-06-18T17:45:13Z", + acceptedPaymentMethods: { + card: true, + squareGiftCard: false, + bankAccount: false, + buyNowPayLater: false, + cashAppPay: false, + }, + customFields: [ + { + label: "Event Reference Number", + value: "Ref. #1234", + placement: "ABOVE_LINE_ITEMS", + }, + { + label: "Terms of Service", + value: "The terms of service are...", + placement: "BELOW_LINE_ITEMS", + }, + ], + subscriptionId: "subscription_id", + saleOrServiceDate: "2030-01-24", + paymentConditions: "payment_conditions", + storePaymentMethodEnabled: false, + attachments: [{}], + creatorTeamMemberId: "creator_team_member_id", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("search", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + query: { + filter: { location_ids: ["ES0RJRZYEC39A"], customer_ids: ["JDKYHBWT1D4F8MFH63DBMEN8Y4"] }, + sort: { field: "INVOICE_SORT_DATE", order: "DESC" }, + }, + limit: 100, + }; + const rawResponseBody = { + invoices: [ + { + id: "inv:0-ChCHu2mZEabLeeHahQnXDjZQECY", + version: 0, + location_id: "ES0RJRZYEC39A", + order_id: "CAISENgvlJ6jLWAzERDzjyHVybY", + primary_recipient: { + customer_id: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + given_name: "Amelia", + family_name: "Earhart", + email_address: "Amelia.Earhart@example.com", + phone_number: "1-212-555-4240", + }, + payment_requests: [ + { + uid: "2da7964f-f3d2-4f43-81e8-5aa220bf3355", + request_type: "BALANCE", + due_date: "2030-01-24", + tipping_enabled: true, + automatic_payment_source: "NONE", + reminders: [ + { + uid: "beebd363-e47f-4075-8785-c235aaa7df11", + relative_scheduled_days: -1, + message: "Your invoice is due tomorrow", + status: "PENDING", + }, + ], + computed_amount_money: { amount: BigInt(10000), currency: "USD" }, + total_completed_amount_money: { amount: BigInt(0), currency: "USD" }, + }, + ], + delivery_method: "EMAIL", + invoice_number: "inv-100", + title: "Event Planning Services", + description: "We appreciate your business!", + scheduled_at: "2030-01-13T10:00:00Z", + public_url: "public_url", + status: "DRAFT", + timezone: "America/Los_Angeles", + created_at: "2020-06-18T17:45:13Z", + updated_at: "2020-06-18T17:45:13Z", + accepted_payment_methods: { + card: true, + square_gift_card: false, + bank_account: false, + buy_now_pay_later: false, + cash_app_pay: false, + }, + custom_fields: [ + { label: "Event Reference Number", value: "Ref. #1234", placement: "ABOVE_LINE_ITEMS" }, + { + label: "Terms of Service", + value: "The terms of service are...", + placement: "BELOW_LINE_ITEMS", + }, + ], + subscription_id: "subscription_id", + sale_or_service_date: "2030-01-24", + payment_conditions: "payment_conditions", + store_payment_method_enabled: false, + attachments: [{}], + creator_team_member_id: "creator_team_member_id", + }, + { + id: "inv:0-ChC366qAfskpGrBI_1bozs9mEA3", + version: 3, + location_id: "ES0RJRZYEC39A", + order_id: "a65jnS8NXbfprvGJzY9F4fQTuaB", + primary_recipient: { + customer_id: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + given_name: "Amelia", + family_name: "Earhart", + email_address: "Amelia.Earhart@example.com", + phone_number: "1-212-555-4240", + }, + payment_requests: [ + { + uid: "66c3bdfd-5090-4ff9-a8a0-c1e1a2ffa176", + request_type: "DEPOSIT", + due_date: "2021-01-23", + percentage_requested: "25", + tipping_enabled: false, + automatic_payment_source: "CARD_ON_FILE", + card_id: "ccof:IkWfpLj4tNHMyFii3GB", + computed_amount_money: { amount: BigInt(1000), currency: "USD" }, + total_completed_amount_money: { amount: BigInt(1000), currency: "USD" }, + }, + { + uid: "120c5e18-4f80-4f6b-b159-774cb9bf8f99", + request_type: "BALANCE", + due_date: "2021-06-15", + tipping_enabled: false, + automatic_payment_source: "CARD_ON_FILE", + card_id: "ccof:IkWfpLj4tNHMyFii3GB", + computed_amount_money: { amount: BigInt(3000), currency: "USD" }, + total_completed_amount_money: { amount: BigInt(0), currency: "USD" }, + }, + ], + delivery_method: "EMAIL", + invoice_number: "inv-455", + title: "title", + description: "description", + scheduled_at: "scheduled_at", + public_url: "https://squareup.com/pay-invoice/invtmp:5e22a2c2-47c1-46d6-b061-808764dfe2b9", + next_payment_amount_money: { amount: BigInt(3000), currency: "USD" }, + status: "PARTIALLY_PAID", + timezone: "America/Los_Angeles", + created_at: "2021-01-23T15:29:12Z", + updated_at: "2021-01-23T15:29:56Z", + accepted_payment_methods: { + card: true, + square_gift_card: true, + bank_account: false, + buy_now_pay_later: false, + cash_app_pay: false, + }, + custom_fields: [{}], + subscription_id: "subscription_id", + sale_or_service_date: "2030-01-24", + payment_conditions: "payment_conditions", + store_payment_method_enabled: false, + attachments: [{}], + creator_team_member_id: "creator_team_member_id", + }, + ], + cursor: "ChoIDhIWVm54ZVRhLXhySFBOejBBM2xJb2daUQoFCI4IGAE", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/invoices/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.invoices.search({ + query: { + filter: { + locationIds: ["ES0RJRZYEC39A"], + customerIds: ["JDKYHBWT1D4F8MFH63DBMEN8Y4"], + }, + sort: { + field: "INVOICE_SORT_DATE", + order: "DESC", + }, + }, + limit: 100, + }); + expect(response).toEqual({ + invoices: [ + { + id: "inv:0-ChCHu2mZEabLeeHahQnXDjZQECY", + version: 0, + locationId: "ES0RJRZYEC39A", + orderId: "CAISENgvlJ6jLWAzERDzjyHVybY", + primaryRecipient: { + customerId: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + givenName: "Amelia", + familyName: "Earhart", + emailAddress: "Amelia.Earhart@example.com", + phoneNumber: "1-212-555-4240", + }, + paymentRequests: [ + { + uid: "2da7964f-f3d2-4f43-81e8-5aa220bf3355", + requestType: "BALANCE", + dueDate: "2030-01-24", + tippingEnabled: true, + automaticPaymentSource: "NONE", + reminders: [ + { + uid: "beebd363-e47f-4075-8785-c235aaa7df11", + relativeScheduledDays: -1, + message: "Your invoice is due tomorrow", + status: "PENDING", + }, + ], + computedAmountMoney: { + amount: BigInt("10000"), + currency: "USD", + }, + totalCompletedAmountMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + ], + deliveryMethod: "EMAIL", + invoiceNumber: "inv-100", + title: "Event Planning Services", + description: "We appreciate your business!", + scheduledAt: "2030-01-13T10:00:00Z", + publicUrl: "public_url", + status: "DRAFT", + timezone: "America/Los_Angeles", + createdAt: "2020-06-18T17:45:13Z", + updatedAt: "2020-06-18T17:45:13Z", + acceptedPaymentMethods: { + card: true, + squareGiftCard: false, + bankAccount: false, + buyNowPayLater: false, + cashAppPay: false, + }, + customFields: [ + { + label: "Event Reference Number", + value: "Ref. #1234", + placement: "ABOVE_LINE_ITEMS", + }, + { + label: "Terms of Service", + value: "The terms of service are...", + placement: "BELOW_LINE_ITEMS", + }, + ], + subscriptionId: "subscription_id", + saleOrServiceDate: "2030-01-24", + paymentConditions: "payment_conditions", + storePaymentMethodEnabled: false, + attachments: [{}], + creatorTeamMemberId: "creator_team_member_id", + }, + { + id: "inv:0-ChC366qAfskpGrBI_1bozs9mEA3", + version: 3, + locationId: "ES0RJRZYEC39A", + orderId: "a65jnS8NXbfprvGJzY9F4fQTuaB", + primaryRecipient: { + customerId: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + givenName: "Amelia", + familyName: "Earhart", + emailAddress: "Amelia.Earhart@example.com", + phoneNumber: "1-212-555-4240", + }, + paymentRequests: [ + { + uid: "66c3bdfd-5090-4ff9-a8a0-c1e1a2ffa176", + requestType: "DEPOSIT", + dueDate: "2021-01-23", + percentageRequested: "25", + tippingEnabled: false, + automaticPaymentSource: "CARD_ON_FILE", + cardId: "ccof:IkWfpLj4tNHMyFii3GB", + computedAmountMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + totalCompletedAmountMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + }, + { + uid: "120c5e18-4f80-4f6b-b159-774cb9bf8f99", + requestType: "BALANCE", + dueDate: "2021-06-15", + tippingEnabled: false, + automaticPaymentSource: "CARD_ON_FILE", + cardId: "ccof:IkWfpLj4tNHMyFii3GB", + computedAmountMoney: { + amount: BigInt("3000"), + currency: "USD", + }, + totalCompletedAmountMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + ], + deliveryMethod: "EMAIL", + invoiceNumber: "inv-455", + title: "title", + description: "description", + scheduledAt: "scheduled_at", + publicUrl: "https://squareup.com/pay-invoice/invtmp:5e22a2c2-47c1-46d6-b061-808764dfe2b9", + nextPaymentAmountMoney: { + amount: BigInt("3000"), + currency: "USD", + }, + status: "PARTIALLY_PAID", + timezone: "America/Los_Angeles", + createdAt: "2021-01-23T15:29:12Z", + updatedAt: "2021-01-23T15:29:56Z", + acceptedPaymentMethods: { + card: true, + squareGiftCard: true, + bankAccount: false, + buyNowPayLater: false, + cashAppPay: false, + }, + customFields: [{}], + subscriptionId: "subscription_id", + saleOrServiceDate: "2030-01-24", + paymentConditions: "payment_conditions", + storePaymentMethodEnabled: false, + attachments: [{}], + creatorTeamMemberId: "creator_team_member_id", + }, + ], + cursor: "ChoIDhIWVm54ZVRhLXhySFBOejBBM2xJb2daUQoFCI4IGAE", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + invoice: { + id: "inv:0-ChCHu2mZEabLeeHahQnXDjZQECY", + version: 0, + location_id: "ES0RJRZYEC39A", + order_id: "CAISENgvlJ6jLWAzERDzjyHVybY", + primary_recipient: { + customer_id: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + given_name: "Amelia", + family_name: "Earhart", + email_address: "Amelia.Earhart@example.com", + phone_number: "1-212-555-4240", + company_name: "company_name", + }, + payment_requests: [ + { + uid: "2da7964f-f3d2-4f43-81e8-5aa220bf3355", + request_type: "BALANCE", + due_date: "2030-01-24", + tipping_enabled: true, + automatic_payment_source: "NONE", + reminders: [ + { + uid: "beebd363-e47f-4075-8785-c235aaa7df11", + relative_scheduled_days: -1, + message: "Your invoice is due tomorrow", + status: "PENDING", + }, + ], + computed_amount_money: { amount: BigInt(10000), currency: "USD" }, + total_completed_amount_money: { amount: BigInt(0), currency: "USD" }, + }, + ], + delivery_method: "EMAIL", + invoice_number: "inv-100", + title: "Event Planning Services", + description: "We appreciate your business!", + scheduled_at: "2030-01-13T10:00:00Z", + public_url: "public_url", + next_payment_amount_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + status: "DRAFT", + timezone: "America/Los_Angeles", + created_at: "2020-06-18T17:45:13Z", + updated_at: "2020-06-18T17:45:13Z", + accepted_payment_methods: { + card: true, + square_gift_card: false, + bank_account: false, + buy_now_pay_later: false, + cash_app_pay: false, + }, + custom_fields: [ + { label: "Event Reference Number", value: "Ref. #1234", placement: "ABOVE_LINE_ITEMS" }, + { label: "Terms of Service", value: "The terms of service are...", placement: "BELOW_LINE_ITEMS" }, + ], + subscription_id: "subscription_id", + sale_or_service_date: "2030-01-24", + payment_conditions: "payment_conditions", + store_payment_method_enabled: false, + attachments: [{}], + creator_team_member_id: "creator_team_member_id", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/invoices/invoice_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.invoices.get({ + invoiceId: "invoice_id", + }); + expect(response).toEqual({ + invoice: { + id: "inv:0-ChCHu2mZEabLeeHahQnXDjZQECY", + version: 0, + locationId: "ES0RJRZYEC39A", + orderId: "CAISENgvlJ6jLWAzERDzjyHVybY", + primaryRecipient: { + customerId: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + givenName: "Amelia", + familyName: "Earhart", + emailAddress: "Amelia.Earhart@example.com", + phoneNumber: "1-212-555-4240", + companyName: "company_name", + }, + paymentRequests: [ + { + uid: "2da7964f-f3d2-4f43-81e8-5aa220bf3355", + requestType: "BALANCE", + dueDate: "2030-01-24", + tippingEnabled: true, + automaticPaymentSource: "NONE", + reminders: [ + { + uid: "beebd363-e47f-4075-8785-c235aaa7df11", + relativeScheduledDays: -1, + message: "Your invoice is due tomorrow", + status: "PENDING", + }, + ], + computedAmountMoney: { + amount: BigInt("10000"), + currency: "USD", + }, + totalCompletedAmountMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + ], + deliveryMethod: "EMAIL", + invoiceNumber: "inv-100", + title: "Event Planning Services", + description: "We appreciate your business!", + scheduledAt: "2030-01-13T10:00:00Z", + publicUrl: "public_url", + nextPaymentAmountMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + status: "DRAFT", + timezone: "America/Los_Angeles", + createdAt: "2020-06-18T17:45:13Z", + updatedAt: "2020-06-18T17:45:13Z", + acceptedPaymentMethods: { + card: true, + squareGiftCard: false, + bankAccount: false, + buyNowPayLater: false, + cashAppPay: false, + }, + customFields: [ + { + label: "Event Reference Number", + value: "Ref. #1234", + placement: "ABOVE_LINE_ITEMS", + }, + { + label: "Terms of Service", + value: "The terms of service are...", + placement: "BELOW_LINE_ITEMS", + }, + ], + subscriptionId: "subscription_id", + saleOrServiceDate: "2030-01-24", + paymentConditions: "payment_conditions", + storePaymentMethodEnabled: false, + attachments: [{}], + creatorTeamMemberId: "creator_team_member_id", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + invoice: { + version: 1, + payment_requests: [{ uid: "2da7964f-f3d2-4f43-81e8-5aa220bf3355", tipping_enabled: false }], + }, + idempotency_key: "4ee82288-0910-499e-ab4c-5d0071dad1be", + }; + const rawResponseBody = { + invoice: { + id: "inv:0-ChCHu2mZEabLeeHahQnXDjZQECY", + version: 2, + location_id: "ES0RJRZYEC39A", + order_id: "CAISENgvlJ6jLWAzERDzjyHVybY", + primary_recipient: { + customer_id: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + given_name: "Amelia", + family_name: "Earhart", + email_address: "Amelia.Earhart@example.com", + phone_number: "1-212-555-4240", + company_name: "company_name", + }, + payment_requests: [ + { + uid: "2da7964f-f3d2-4f43-81e8-5aa220bf3355", + request_type: "BALANCE", + due_date: "2030-01-24", + tipping_enabled: false, + automatic_payment_source: "NONE", + computed_amount_money: { amount: BigInt(10000), currency: "USD" }, + total_completed_amount_money: { amount: BigInt(0), currency: "USD" }, + }, + ], + delivery_method: "EMAIL", + invoice_number: "inv-100", + title: "Event Planning Services", + description: "We appreciate your business!", + scheduled_at: "2030-01-13T10:00:00Z", + public_url: "public_url", + next_payment_amount_money: { amount: BigInt(10000), currency: "USD" }, + status: "UNPAID", + timezone: "America/Los_Angeles", + created_at: "2020-06-18T17:45:13Z", + updated_at: "2020-06-18T18:23:11Z", + accepted_payment_methods: { + card: true, + square_gift_card: false, + bank_account: false, + buy_now_pay_later: false, + cash_app_pay: false, + }, + custom_fields: [ + { label: "Event Reference Number", value: "Ref. #1234", placement: "ABOVE_LINE_ITEMS" }, + { label: "Terms of Service", value: "The terms of service are...", placement: "BELOW_LINE_ITEMS" }, + ], + subscription_id: "subscription_id", + sale_or_service_date: "2030-01-24", + payment_conditions: "payment_conditions", + store_payment_method_enabled: false, + attachments: [{}], + creator_team_member_id: "creator_team_member_id", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .put("/v2/invoices/invoice_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.invoices.update({ + invoiceId: "invoice_id", + invoice: { + version: 1, + paymentRequests: [ + { + uid: "2da7964f-f3d2-4f43-81e8-5aa220bf3355", + tippingEnabled: false, + }, + ], + }, + idempotencyKey: "4ee82288-0910-499e-ab4c-5d0071dad1be", + }); + expect(response).toEqual({ + invoice: { + id: "inv:0-ChCHu2mZEabLeeHahQnXDjZQECY", + version: 2, + locationId: "ES0RJRZYEC39A", + orderId: "CAISENgvlJ6jLWAzERDzjyHVybY", + primaryRecipient: { + customerId: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + givenName: "Amelia", + familyName: "Earhart", + emailAddress: "Amelia.Earhart@example.com", + phoneNumber: "1-212-555-4240", + companyName: "company_name", + }, + paymentRequests: [ + { + uid: "2da7964f-f3d2-4f43-81e8-5aa220bf3355", + requestType: "BALANCE", + dueDate: "2030-01-24", + tippingEnabled: false, + automaticPaymentSource: "NONE", + computedAmountMoney: { + amount: BigInt("10000"), + currency: "USD", + }, + totalCompletedAmountMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + ], + deliveryMethod: "EMAIL", + invoiceNumber: "inv-100", + title: "Event Planning Services", + description: "We appreciate your business!", + scheduledAt: "2030-01-13T10:00:00Z", + publicUrl: "public_url", + nextPaymentAmountMoney: { + amount: BigInt("10000"), + currency: "USD", + }, + status: "UNPAID", + timezone: "America/Los_Angeles", + createdAt: "2020-06-18T17:45:13Z", + updatedAt: "2020-06-18T18:23:11Z", + acceptedPaymentMethods: { + card: true, + squareGiftCard: false, + bankAccount: false, + buyNowPayLater: false, + cashAppPay: false, + }, + customFields: [ + { + label: "Event Reference Number", + value: "Ref. #1234", + placement: "ABOVE_LINE_ITEMS", + }, + { + label: "Terms of Service", + value: "The terms of service are...", + placement: "BELOW_LINE_ITEMS", + }, + ], + subscriptionId: "subscription_id", + saleOrServiceDate: "2030-01-24", + paymentConditions: "payment_conditions", + storePaymentMethodEnabled: false, + attachments: [{}], + creatorTeamMemberId: "creator_team_member_id", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/invoices/invoice_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.invoices.delete({ + invoiceId: "invoice_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("DeleteInvoiceAttachment", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/invoices/invoice_id/attachments/attachment_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.invoices.deleteInvoiceAttachment({ + invoiceId: "invoice_id", + attachmentId: "attachment_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("cancel", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { version: 0 }; + const rawResponseBody = { + invoice: { + id: "inv:0-ChCHu2mZEabLeeHahQnXDjZQECY", + version: 1, + location_id: "ES0RJRZYEC39A", + order_id: "CAISENgvlJ6jLWAzERDzjyHVybY", + primary_recipient: { + customer_id: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + given_name: "Amelia", + family_name: "Earhart", + email_address: "Amelia.Earhart@example.com", + phone_number: "1-212-555-4240", + company_name: "company_name", + }, + payment_requests: [ + { + uid: "2da7964f-f3d2-4f43-81e8-5aa220bf3355", + request_type: "BALANCE", + due_date: "2030-01-24", + tipping_enabled: true, + automatic_payment_source: "NONE", + reminders: [ + { + uid: "beebd363-e47f-4075-8785-c235aaa7df11", + relative_scheduled_days: -1, + message: "Your invoice is due tomorrow", + status: "PENDING", + }, + ], + computed_amount_money: { amount: BigInt(10000), currency: "USD" }, + total_completed_amount_money: { amount: BigInt(0), currency: "USD" }, + }, + ], + delivery_method: "EMAIL", + invoice_number: "inv-100", + title: "Event Planning Services", + description: "We appreciate your business!", + scheduled_at: "2030-01-13T10:00:00Z", + public_url: "public_url", + next_payment_amount_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + status: "CANCELED", + timezone: "America/Los_Angeles", + created_at: "2020-06-18T17:45:13Z", + updated_at: "2020-06-18T18:23:11Z", + accepted_payment_methods: { + card: true, + square_gift_card: false, + bank_account: false, + buy_now_pay_later: false, + cash_app_pay: false, + }, + custom_fields: [ + { label: "Event Reference Number", value: "Ref. #1234", placement: "ABOVE_LINE_ITEMS" }, + { label: "Terms of Service", value: "The terms of service are...", placement: "BELOW_LINE_ITEMS" }, + ], + subscription_id: "subscription_id", + sale_or_service_date: "2030-01-24", + payment_conditions: "payment_conditions", + store_payment_method_enabled: false, + attachments: [{}], + creator_team_member_id: "creator_team_member_id", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/invoices/invoice_id/cancel") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.invoices.cancel({ + invoiceId: "invoice_id", + version: 0, + }); + expect(response).toEqual({ + invoice: { + id: "inv:0-ChCHu2mZEabLeeHahQnXDjZQECY", + version: 1, + locationId: "ES0RJRZYEC39A", + orderId: "CAISENgvlJ6jLWAzERDzjyHVybY", + primaryRecipient: { + customerId: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + givenName: "Amelia", + familyName: "Earhart", + emailAddress: "Amelia.Earhart@example.com", + phoneNumber: "1-212-555-4240", + companyName: "company_name", + }, + paymentRequests: [ + { + uid: "2da7964f-f3d2-4f43-81e8-5aa220bf3355", + requestType: "BALANCE", + dueDate: "2030-01-24", + tippingEnabled: true, + automaticPaymentSource: "NONE", + reminders: [ + { + uid: "beebd363-e47f-4075-8785-c235aaa7df11", + relativeScheduledDays: -1, + message: "Your invoice is due tomorrow", + status: "PENDING", + }, + ], + computedAmountMoney: { + amount: BigInt("10000"), + currency: "USD", + }, + totalCompletedAmountMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + ], + deliveryMethod: "EMAIL", + invoiceNumber: "inv-100", + title: "Event Planning Services", + description: "We appreciate your business!", + scheduledAt: "2030-01-13T10:00:00Z", + publicUrl: "public_url", + nextPaymentAmountMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + status: "CANCELED", + timezone: "America/Los_Angeles", + createdAt: "2020-06-18T17:45:13Z", + updatedAt: "2020-06-18T18:23:11Z", + acceptedPaymentMethods: { + card: true, + squareGiftCard: false, + bankAccount: false, + buyNowPayLater: false, + cashAppPay: false, + }, + customFields: [ + { + label: "Event Reference Number", + value: "Ref. #1234", + placement: "ABOVE_LINE_ITEMS", + }, + { + label: "Terms of Service", + value: "The terms of service are...", + placement: "BELOW_LINE_ITEMS", + }, + ], + subscriptionId: "subscription_id", + saleOrServiceDate: "2030-01-24", + paymentConditions: "payment_conditions", + storePaymentMethodEnabled: false, + attachments: [{}], + creatorTeamMemberId: "creator_team_member_id", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("publish", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { version: 1, idempotency_key: "32da42d0-1997-41b0-826b-f09464fc2c2e" }; + const rawResponseBody = { + invoice: { + id: "inv:0-ChCHu2mZEabLeeHahQnXDjZQECY", + version: 1, + location_id: "ES0RJRZYEC39A", + order_id: "CAISENgvlJ6jLWAzERDzjyHVybY", + primary_recipient: { + customer_id: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + given_name: "Amelia", + family_name: "Earhart", + email_address: "Amelia.Earhart@example.com", + phone_number: "1-212-555-4240", + company_name: "company_name", + }, + payment_requests: [ + { + uid: "2da7964f-f3d2-4f43-81e8-5aa220bf3355", + request_type: "BALANCE", + due_date: "2030-01-24", + tipping_enabled: true, + automatic_payment_source: "NONE", + reminders: [ + { + uid: "beebd363-e47f-4075-8785-c235aaa7df11", + relative_scheduled_days: -1, + message: "Your invoice is due tomorrow", + status: "PENDING", + }, + ], + computed_amount_money: { amount: BigInt(10000), currency: "USD" }, + total_completed_amount_money: { amount: BigInt(0), currency: "USD" }, + }, + ], + delivery_method: "EMAIL", + invoice_number: "inv-100", + title: "Event Planning Services", + description: "We appreciate your business!", + scheduled_at: "2030-01-13T10:00:00Z", + public_url: "https://squareup.com/pay-invoice/invtmp:5e22a2c2-47c1-46d6-b061-808764dfe2b9", + next_payment_amount_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + status: "SCHEDULED", + timezone: "America/Los_Angeles", + created_at: "2020-06-18T17:45:13Z", + updated_at: "2020-06-18T18:23:11Z", + accepted_payment_methods: { + card: true, + square_gift_card: false, + bank_account: false, + buy_now_pay_later: false, + cash_app_pay: false, + }, + custom_fields: [ + { label: "Event Reference Number", value: "Ref. #1234", placement: "ABOVE_LINE_ITEMS" }, + { label: "Terms of Service", value: "The terms of service are...", placement: "BELOW_LINE_ITEMS" }, + ], + subscription_id: "subscription_id", + sale_or_service_date: "2030-01-24", + payment_conditions: "payment_conditions", + store_payment_method_enabled: false, + attachments: [{}], + creator_team_member_id: "creator_team_member_id", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/invoices/invoice_id/publish") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.invoices.publish({ + invoiceId: "invoice_id", + version: 1, + idempotencyKey: "32da42d0-1997-41b0-826b-f09464fc2c2e", + }); + expect(response).toEqual({ + invoice: { + id: "inv:0-ChCHu2mZEabLeeHahQnXDjZQECY", + version: 1, + locationId: "ES0RJRZYEC39A", + orderId: "CAISENgvlJ6jLWAzERDzjyHVybY", + primaryRecipient: { + customerId: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + givenName: "Amelia", + familyName: "Earhart", + emailAddress: "Amelia.Earhart@example.com", + phoneNumber: "1-212-555-4240", + companyName: "company_name", + }, + paymentRequests: [ + { + uid: "2da7964f-f3d2-4f43-81e8-5aa220bf3355", + requestType: "BALANCE", + dueDate: "2030-01-24", + tippingEnabled: true, + automaticPaymentSource: "NONE", + reminders: [ + { + uid: "beebd363-e47f-4075-8785-c235aaa7df11", + relativeScheduledDays: -1, + message: "Your invoice is due tomorrow", + status: "PENDING", + }, + ], + computedAmountMoney: { + amount: BigInt("10000"), + currency: "USD", + }, + totalCompletedAmountMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + ], + deliveryMethod: "EMAIL", + invoiceNumber: "inv-100", + title: "Event Planning Services", + description: "We appreciate your business!", + scheduledAt: "2030-01-13T10:00:00Z", + publicUrl: "https://squareup.com/pay-invoice/invtmp:5e22a2c2-47c1-46d6-b061-808764dfe2b9", + nextPaymentAmountMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + status: "SCHEDULED", + timezone: "America/Los_Angeles", + createdAt: "2020-06-18T17:45:13Z", + updatedAt: "2020-06-18T18:23:11Z", + acceptedPaymentMethods: { + card: true, + squareGiftCard: false, + bankAccount: false, + buyNowPayLater: false, + cashAppPay: false, + }, + customFields: [ + { + label: "Event Reference Number", + value: "Ref. #1234", + placement: "ABOVE_LINE_ITEMS", + }, + { + label: "Terms of Service", + value: "The terms of service are...", + placement: "BELOW_LINE_ITEMS", + }, + ], + subscriptionId: "subscription_id", + saleOrServiceDate: "2030-01-24", + paymentConditions: "payment_conditions", + storePaymentMethodEnabled: false, + attachments: [{}], + creatorTeamMemberId: "creator_team_member_id", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/labor.test.ts b/tests/wire/labor.test.ts new file mode 100644 index 000000000..5429ecddd --- /dev/null +++ b/tests/wire/labor.test.ts @@ -0,0 +1,1234 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Labor", () => { + test("CreateScheduledShift", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "HIDSNG5KS478L", + scheduled_shift: { + draft_shift_details: { + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + location_id: "PAA1RJZZKXBFG", + job_id: "FzbJAtt9qEWncK1BWgVCxQ6M", + start_at: "2019-01-25T03:11:00-05:00", + end_at: "2019-01-25T13:11:00-05:00", + notes: "Dont forget to prep the vegetables", + is_deleted: false, + }, + }, + }; + const rawResponseBody = { + scheduled_shift: { + id: "K0YH4CV5462JB", + draft_shift_details: { + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + location_id: "PAA1RJZZKXBFG", + job_id: "FzbJAtt9qEWncK1BWgVCxQ6M", + start_at: "2019-01-25T03:11:00-05:00", + end_at: "2019-01-25T13:11:00-05:00", + notes: "Dont forget to prep the vegetables", + is_deleted: false, + timezone: "America/New_York", + }, + published_shift_details: { + team_member_id: "team_member_id", + location_id: "location_id", + job_id: "job_id", + start_at: "start_at", + end_at: "end_at", + notes: "notes", + is_deleted: true, + timezone: "timezone", + }, + version: 1, + created_at: "2019-02-25T03:11:00-05:00", + updated_at: "2019-02-25T03:11:00-05:00", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/labor/scheduled-shifts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.createScheduledShift({ + idempotencyKey: "HIDSNG5KS478L", + scheduledShift: { + draftShiftDetails: { + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + locationId: "PAA1RJZZKXBFG", + jobId: "FzbJAtt9qEWncK1BWgVCxQ6M", + startAt: "2019-01-25T03:11:00-05:00", + endAt: "2019-01-25T13:11:00-05:00", + notes: "Dont forget to prep the vegetables", + isDeleted: false, + }, + }, + }); + expect(response).toEqual({ + scheduledShift: { + id: "K0YH4CV5462JB", + draftShiftDetails: { + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + locationId: "PAA1RJZZKXBFG", + jobId: "FzbJAtt9qEWncK1BWgVCxQ6M", + startAt: "2019-01-25T03:11:00-05:00", + endAt: "2019-01-25T13:11:00-05:00", + notes: "Dont forget to prep the vegetables", + isDeleted: false, + timezone: "America/New_York", + }, + publishedShiftDetails: { + teamMemberId: "team_member_id", + locationId: "location_id", + jobId: "job_id", + startAt: "start_at", + endAt: "end_at", + notes: "notes", + isDeleted: true, + timezone: "timezone", + }, + version: 1, + createdAt: "2019-02-25T03:11:00-05:00", + updatedAt: "2019-02-25T03:11:00-05:00", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("BulkPublishScheduledShifts", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { scheduled_shifts: { key: {} }, scheduled_shift_notification_audience: "AFFECTED" }; + const rawResponseBody = { + responses: { + idp_key_1: { + scheduled_shift: { + id: "K0YH4CV5462JB", + draft_shift_details: { + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + location_id: "PAA1RJZZKXBFG", + job_id: "FzbJAtt9qEWncK1BWgVCxQ6M", + start_at: "2019-03-25T03:11:00-05:00", + end_at: "2019-03-25T13:18:00-05:00", + notes: "Don't forget to prep the vegetables", + is_deleted: false, + timezone: "America/New_York", + }, + published_shift_details: { + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + location_id: "PAA1RJZZKXBFG", + job_id: "FzbJAtt9qEWncK1BWgVCxQ6M", + start_at: "2019-03-25T03:11:00-05:00", + end_at: "2019-03-25T13:18:00-05:00", + notes: "Don't forget to prep the vegetables", + is_deleted: false, + timezone: "America/New_York", + }, + version: 3, + created_at: "2019-02-25T03:11:00-05:00", + updated_at: "2019-02-25T03:11:15-05:00", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + idp_key_2: { + errors: [ + { + category: "INVALID_REQUEST_ERROR", + code: "INVALID_VALUE", + detail: "Scheduled shift with id 'scheduled-shift-2' not found", + field: "scheduled-shifts.scheduled-shift-2", + }, + ], + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/labor/scheduled-shifts/bulk-publish") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.bulkPublishScheduledShifts({ + scheduledShifts: { + key: {}, + }, + scheduledShiftNotificationAudience: "AFFECTED", + }); + expect(response).toEqual({ + responses: { + idp_key_1: { + scheduledShift: { + id: "K0YH4CV5462JB", + draftShiftDetails: { + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + locationId: "PAA1RJZZKXBFG", + jobId: "FzbJAtt9qEWncK1BWgVCxQ6M", + startAt: "2019-03-25T03:11:00-05:00", + endAt: "2019-03-25T13:18:00-05:00", + notes: "Don't forget to prep the vegetables", + isDeleted: false, + timezone: "America/New_York", + }, + publishedShiftDetails: { + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + locationId: "PAA1RJZZKXBFG", + jobId: "FzbJAtt9qEWncK1BWgVCxQ6M", + startAt: "2019-03-25T03:11:00-05:00", + endAt: "2019-03-25T13:18:00-05:00", + notes: "Don't forget to prep the vegetables", + isDeleted: false, + timezone: "America/New_York", + }, + version: 3, + createdAt: "2019-02-25T03:11:00-05:00", + updatedAt: "2019-02-25T03:11:15-05:00", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + idp_key_2: { + errors: [ + { + category: "INVALID_REQUEST_ERROR", + code: "INVALID_VALUE", + detail: "Scheduled shift with id 'scheduled-shift-2' not found", + field: "scheduled-shifts.scheduled-shift-2", + }, + ], + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("SearchScheduledShifts", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + query: { filter: { assignment_status: "ASSIGNED" }, sort: { field: "CREATED_AT", order: "ASC" } }, + limit: 2, + cursor: "xoxp-1234-5678-90123", + }; + const rawResponseBody = { + scheduled_shifts: [ + { + id: "K0YH4CV5462JB", + draft_shift_details: { + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + location_id: "PAA1RJZZKXBFG", + job_id: "FzbJAtt9qEWncK1BWgVCxQ6M", + start_at: "2019-01-25T03:11:00-05:00", + end_at: "2019-01-25T13:11:00-05:00", + notes: "Dont forget to prep the vegetables", + is_deleted: false, + timezone: "America/New_York", + }, + version: 1, + created_at: "2019-02-25T03:11:00-05:00", + updated_at: "2019-02-25T03:11:00-05:00", + }, + ], + cursor: "xoxp-123-2123-123232", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/labor/scheduled-shifts/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.searchScheduledShifts({ + query: { + filter: { + assignmentStatus: "ASSIGNED", + }, + sort: { + field: "CREATED_AT", + order: "ASC", + }, + }, + limit: 2, + cursor: "xoxp-1234-5678-90123", + }); + expect(response).toEqual({ + scheduledShifts: [ + { + id: "K0YH4CV5462JB", + draftShiftDetails: { + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + locationId: "PAA1RJZZKXBFG", + jobId: "FzbJAtt9qEWncK1BWgVCxQ6M", + startAt: "2019-01-25T03:11:00-05:00", + endAt: "2019-01-25T13:11:00-05:00", + notes: "Dont forget to prep the vegetables", + isDeleted: false, + timezone: "America/New_York", + }, + version: 1, + createdAt: "2019-02-25T03:11:00-05:00", + updatedAt: "2019-02-25T03:11:00-05:00", + }, + ], + cursor: "xoxp-123-2123-123232", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("RetrieveScheduledShift", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + scheduled_shift: { + id: "K0YH4CV5462JB", + draft_shift_details: { + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + location_id: "PAA1RJZZKXBFG", + job_id: "FzbJAtt9qEWncK1BWgVCxQ6M", + start_at: "2019-03-25T03:11:00-05:00", + end_at: "2019-03-25T13:18:00-05:00", + notes: "Don't forget to prep the vegetables", + is_deleted: false, + timezone: "America/New_York", + }, + published_shift_details: { + team_member_id: "team_member_id", + location_id: "location_id", + job_id: "job_id", + start_at: "start_at", + end_at: "end_at", + notes: "notes", + is_deleted: true, + timezone: "timezone", + }, + version: 2, + created_at: "2019-02-25T03:11:00-05:00", + updated_at: "2019-02-25T03:11:15-05:00", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/labor/scheduled-shifts/id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.retrieveScheduledShift({ + id: "id", + }); + expect(response).toEqual({ + scheduledShift: { + id: "K0YH4CV5462JB", + draftShiftDetails: { + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + locationId: "PAA1RJZZKXBFG", + jobId: "FzbJAtt9qEWncK1BWgVCxQ6M", + startAt: "2019-03-25T03:11:00-05:00", + endAt: "2019-03-25T13:18:00-05:00", + notes: "Don't forget to prep the vegetables", + isDeleted: false, + timezone: "America/New_York", + }, + publishedShiftDetails: { + teamMemberId: "team_member_id", + locationId: "location_id", + jobId: "job_id", + startAt: "start_at", + endAt: "end_at", + notes: "notes", + isDeleted: true, + timezone: "timezone", + }, + version: 2, + createdAt: "2019-02-25T03:11:00-05:00", + updatedAt: "2019-02-25T03:11:15-05:00", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("UpdateScheduledShift", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + scheduled_shift: { + draft_shift_details: { + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + location_id: "PAA1RJZZKXBFG", + job_id: "FzbJAtt9qEWncK1BWgVCxQ6M", + start_at: "2019-03-25T03:11:00-05:00", + end_at: "2019-03-25T13:18:00-05:00", + notes: "Dont forget to prep the vegetables", + is_deleted: false, + }, + version: 1, + }, + }; + const rawResponseBody = { + scheduled_shift: { + id: "K0YH4CV5462JB", + draft_shift_details: { + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + location_id: "PAA1RJZZKXBFG", + job_id: "FzbJAtt9qEWncK1BWgVCxQ6M", + start_at: "2019-03-25T03:11:00-05:00", + end_at: "2019-03-25T13:18:00-05:00", + notes: "Dont forget to prep the vegetables", + is_deleted: false, + timezone: "America/New_York", + }, + published_shift_details: { + team_member_id: "team_member_id", + location_id: "location_id", + job_id: "job_id", + start_at: "start_at", + end_at: "end_at", + notes: "notes", + is_deleted: true, + timezone: "timezone", + }, + version: 2, + created_at: "2019-02-25T03:11:00-05:00", + updated_at: "2019-02-25T03:11:15-05:00", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .put("/v2/labor/scheduled-shifts/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.updateScheduledShift({ + id: "id", + scheduledShift: { + draftShiftDetails: { + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + locationId: "PAA1RJZZKXBFG", + jobId: "FzbJAtt9qEWncK1BWgVCxQ6M", + startAt: "2019-03-25T03:11:00-05:00", + endAt: "2019-03-25T13:18:00-05:00", + notes: "Dont forget to prep the vegetables", + isDeleted: false, + }, + version: 1, + }, + }); + expect(response).toEqual({ + scheduledShift: { + id: "K0YH4CV5462JB", + draftShiftDetails: { + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + locationId: "PAA1RJZZKXBFG", + jobId: "FzbJAtt9qEWncK1BWgVCxQ6M", + startAt: "2019-03-25T03:11:00-05:00", + endAt: "2019-03-25T13:18:00-05:00", + notes: "Dont forget to prep the vegetables", + isDeleted: false, + timezone: "America/New_York", + }, + publishedShiftDetails: { + teamMemberId: "team_member_id", + locationId: "location_id", + jobId: "job_id", + startAt: "start_at", + endAt: "end_at", + notes: "notes", + isDeleted: true, + timezone: "timezone", + }, + version: 2, + createdAt: "2019-02-25T03:11:00-05:00", + updatedAt: "2019-02-25T03:11:15-05:00", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("PublishScheduledShift", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "HIDSNG5KS478L", + version: 2, + scheduled_shift_notification_audience: "ALL", + }; + const rawResponseBody = { + scheduled_shift: { + id: "K0YH4CV5462JB", + draft_shift_details: { + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + location_id: "PAA1RJZZKXBFG", + job_id: "FzbJAtt9qEWncK1BWgVCxQ6M", + start_at: "2019-01-25T03:11:00-05:00", + end_at: "2019-01-25T13:11:00-05:00", + notes: "Dont forget to prep the vegetables", + is_deleted: false, + timezone: "America/New_York", + }, + published_shift_details: { + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + location_id: "PAA1RJZZKXBFG", + job_id: "FzbJAtt9qEWncK1BWgVCxQ6M", + start_at: "2019-01-25T03:11:00-05:00", + end_at: "2019-01-25T13:11:00-05:00", + notes: "Dont forget to prep the vegetables", + is_deleted: false, + timezone: "America/New_York", + }, + version: 2, + created_at: "2019-02-25T03:11:00-05:00", + updated_at: "2019-02-25T03:11:00-05:00", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/labor/scheduled-shifts/id/publish") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.publishScheduledShift({ + id: "id", + idempotencyKey: "HIDSNG5KS478L", + version: 2, + scheduledShiftNotificationAudience: "ALL", + }); + expect(response).toEqual({ + scheduledShift: { + id: "K0YH4CV5462JB", + draftShiftDetails: { + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + locationId: "PAA1RJZZKXBFG", + jobId: "FzbJAtt9qEWncK1BWgVCxQ6M", + startAt: "2019-01-25T03:11:00-05:00", + endAt: "2019-01-25T13:11:00-05:00", + notes: "Dont forget to prep the vegetables", + isDeleted: false, + timezone: "America/New_York", + }, + publishedShiftDetails: { + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + locationId: "PAA1RJZZKXBFG", + jobId: "FzbJAtt9qEWncK1BWgVCxQ6M", + startAt: "2019-01-25T03:11:00-05:00", + endAt: "2019-01-25T13:11:00-05:00", + notes: "Dont forget to prep the vegetables", + isDeleted: false, + timezone: "America/New_York", + }, + version: 2, + createdAt: "2019-02-25T03:11:00-05:00", + updatedAt: "2019-02-25T03:11:00-05:00", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("CreateTimecard", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "HIDSNG5KS478L", + timecard: { + location_id: "PAA1RJZZKXBFG", + start_at: "2019-01-25T03:11:00-05:00", + end_at: "2019-01-25T13:11:00-05:00", + wage: { title: "Barista", hourly_rate: { amount: BigInt(1100), currency: "USD" }, tip_eligible: true }, + breaks: [ + { + start_at: "2019-01-25T06:11:00-05:00", + end_at: "2019-01-25T06:16:00-05:00", + break_type_id: "REGS1EQR1TPZ5", + name: "Tea Break", + expected_duration: "PT5M", + is_paid: true, + }, + ], + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + declared_cash_tip_money: { amount: BigInt(500), currency: "USD" }, + }, + }; + const rawResponseBody = { + timecard: { + id: "K0YH4CV5462JB", + location_id: "PAA1RJZZKXBFG", + timezone: "America/New_York", + start_at: "2019-01-25T03:11:00-05:00", + end_at: "2019-01-25T13:11:00-05:00", + wage: { + title: "Barista", + hourly_rate: { amount: BigInt(1100), currency: "USD" }, + job_id: "FzbJAtt9qEWncK1BWgVCxQ6M", + tip_eligible: true, + }, + breaks: [ + { + id: "X7GAQYVVRRG6P", + start_at: "2019-01-25T06:11:00-05:00", + end_at: "2019-01-25T06:16:00-05:00", + break_type_id: "REGS1EQR1TPZ5", + name: "Tea Break", + expected_duration: "PT5M", + is_paid: true, + }, + ], + status: "CLOSED", + version: 1, + created_at: "2019-02-28T00:39:02Z", + updated_at: "2019-02-28T00:39:02Z", + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + declared_cash_tip_money: { amount: BigInt(500), currency: "USD" }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/labor/timecards") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.createTimecard({ + idempotencyKey: "HIDSNG5KS478L", + timecard: { + locationId: "PAA1RJZZKXBFG", + startAt: "2019-01-25T03:11:00-05:00", + endAt: "2019-01-25T13:11:00-05:00", + wage: { + title: "Barista", + hourlyRate: { + amount: BigInt("1100"), + currency: "USD", + }, + tipEligible: true, + }, + breaks: [ + { + startAt: "2019-01-25T06:11:00-05:00", + endAt: "2019-01-25T06:16:00-05:00", + breakTypeId: "REGS1EQR1TPZ5", + name: "Tea Break", + expectedDuration: "PT5M", + isPaid: true, + }, + ], + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + declaredCashTipMoney: { + amount: BigInt("500"), + currency: "USD", + }, + }, + }); + expect(response).toEqual({ + timecard: { + id: "K0YH4CV5462JB", + locationId: "PAA1RJZZKXBFG", + timezone: "America/New_York", + startAt: "2019-01-25T03:11:00-05:00", + endAt: "2019-01-25T13:11:00-05:00", + wage: { + title: "Barista", + hourlyRate: { + amount: BigInt("1100"), + currency: "USD", + }, + jobId: "FzbJAtt9qEWncK1BWgVCxQ6M", + tipEligible: true, + }, + breaks: [ + { + id: "X7GAQYVVRRG6P", + startAt: "2019-01-25T06:11:00-05:00", + endAt: "2019-01-25T06:16:00-05:00", + breakTypeId: "REGS1EQR1TPZ5", + name: "Tea Break", + expectedDuration: "PT5M", + isPaid: true, + }, + ], + status: "CLOSED", + version: 1, + createdAt: "2019-02-28T00:39:02Z", + updatedAt: "2019-02-28T00:39:02Z", + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + declaredCashTipMoney: { + amount: BigInt("500"), + currency: "USD", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("SearchTimecards", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + query: { + filter: { + workday: { + date_range: { start_date: "2019-01-20", end_date: "2019-02-03" }, + match_timecards_by: "START_AT", + default_timezone: "America/Los_Angeles", + }, + }, + }, + limit: 100, + }; + const rawResponseBody = { + timecards: [ + { + id: "X714F3HA6D1PT", + location_id: "PAA1RJZZKXBFG", + timezone: "America/New_York", + start_at: "2019-01-21T03:11:00-05:00", + end_at: "2019-01-21T13:11:00-05:00", + wage: { + title: "Barista", + hourly_rate: { amount: BigInt(1100), currency: "USD" }, + job_id: "FzbJAtt9qEWncK1BWgVCxQ6M", + tip_eligible: true, + }, + breaks: [ + { + id: "SJW7X6AKEJQ65", + start_at: "2019-01-21T06:11:00-05:00", + end_at: "2019-01-21T06:11:00-05:00", + break_type_id: "REGS1EQR1TPZ5", + name: "Tea Break", + expected_duration: "PT10M", + is_paid: true, + }, + ], + status: "CLOSED", + version: 6, + created_at: "2019-01-24T01:12:03Z", + updated_at: "2019-02-07T22:21:08Z", + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + declared_cash_tip_money: { amount: BigInt(500), currency: "USD" }, + }, + { + id: "GDHYBZYWK0P2V", + location_id: "PAA1RJZZKXBFG", + timezone: "America/New_York", + start_at: "2019-01-22T12:02:00-05:00", + end_at: "2019-01-22T13:02:00-05:00", + wage: { + title: "Cook", + hourly_rate: { amount: BigInt(1600), currency: "USD" }, + job_id: "gcbz15vKGnMKmaWJJ152kjim", + tip_eligible: true, + }, + breaks: [ + { + id: "BKS6VR7WR748A", + start_at: "2019-01-22T14:30:00-05:00", + end_at: "2019-01-22T14:40:00-05:00", + break_type_id: "WQX00VR99F53J", + name: "Tea Break", + expected_duration: "PT10M", + is_paid: true, + }, + { + id: "BQFEZSHFZSC51", + start_at: "2019-01-22T12:30:00-05:00", + end_at: "2019-01-22T12:44:00-05:00", + break_type_id: "P6Q468ZFRN1AC", + name: "Coffee Break", + expected_duration: "PT15M", + is_paid: false, + }, + ], + status: "CLOSED", + version: 16, + created_at: "2019-01-23T23:32:45Z", + updated_at: "2019-01-24T00:56:25Z", + team_member_id: "33fJchumvVdJwxV0H6L9", + declared_cash_tip_money: { amount: BigInt(0), currency: "USD" }, + }, + ], + cursor: "cursor", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/labor/timecards/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.searchTimecards({ + query: { + filter: { + workday: { + dateRange: { + startDate: "2019-01-20", + endDate: "2019-02-03", + }, + matchTimecardsBy: "START_AT", + defaultTimezone: "America/Los_Angeles", + }, + }, + }, + limit: 100, + }); + expect(response).toEqual({ + timecards: [ + { + id: "X714F3HA6D1PT", + locationId: "PAA1RJZZKXBFG", + timezone: "America/New_York", + startAt: "2019-01-21T03:11:00-05:00", + endAt: "2019-01-21T13:11:00-05:00", + wage: { + title: "Barista", + hourlyRate: { + amount: BigInt("1100"), + currency: "USD", + }, + jobId: "FzbJAtt9qEWncK1BWgVCxQ6M", + tipEligible: true, + }, + breaks: [ + { + id: "SJW7X6AKEJQ65", + startAt: "2019-01-21T06:11:00-05:00", + endAt: "2019-01-21T06:11:00-05:00", + breakTypeId: "REGS1EQR1TPZ5", + name: "Tea Break", + expectedDuration: "PT10M", + isPaid: true, + }, + ], + status: "CLOSED", + version: 6, + createdAt: "2019-01-24T01:12:03Z", + updatedAt: "2019-02-07T22:21:08Z", + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + declaredCashTipMoney: { + amount: BigInt("500"), + currency: "USD", + }, + }, + { + id: "GDHYBZYWK0P2V", + locationId: "PAA1RJZZKXBFG", + timezone: "America/New_York", + startAt: "2019-01-22T12:02:00-05:00", + endAt: "2019-01-22T13:02:00-05:00", + wage: { + title: "Cook", + hourlyRate: { + amount: BigInt("1600"), + currency: "USD", + }, + jobId: "gcbz15vKGnMKmaWJJ152kjim", + tipEligible: true, + }, + breaks: [ + { + id: "BKS6VR7WR748A", + startAt: "2019-01-22T14:30:00-05:00", + endAt: "2019-01-22T14:40:00-05:00", + breakTypeId: "WQX00VR99F53J", + name: "Tea Break", + expectedDuration: "PT10M", + isPaid: true, + }, + { + id: "BQFEZSHFZSC51", + startAt: "2019-01-22T12:30:00-05:00", + endAt: "2019-01-22T12:44:00-05:00", + breakTypeId: "P6Q468ZFRN1AC", + name: "Coffee Break", + expectedDuration: "PT15M", + isPaid: false, + }, + ], + status: "CLOSED", + version: 16, + createdAt: "2019-01-23T23:32:45Z", + updatedAt: "2019-01-24T00:56:25Z", + teamMemberId: "33fJchumvVdJwxV0H6L9", + declaredCashTipMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + ], + cursor: "cursor", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("RetrieveTimecard", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + timecard: { + id: "T35HMQSN89SV4", + location_id: "PAA1RJZZKXBFG", + timezone: "America/New_York", + start_at: "2019-02-23T18:00:00-05:00", + end_at: "2019-02-23T21:00:00-05:00", + wage: { + title: "Cashier", + hourly_rate: { amount: BigInt(1457), currency: "USD" }, + job_id: "N4YKVLzFj3oGtNocqoYHYpW3", + tip_eligible: true, + }, + breaks: [ + { + id: "M9BBKEPQAQD2T", + start_at: "2019-02-23T19:00:00-05:00", + end_at: "2019-02-23T20:00:00-05:00", + break_type_id: "92EPDRQKJ5088", + name: "Lunch Break", + expected_duration: "PT1H", + is_paid: true, + }, + ], + status: "CLOSED", + version: 1, + created_at: "2019-02-27T00:12:12Z", + updated_at: "2019-02-27T00:12:12Z", + team_member_id: "D71KRMQof6cXGUW0aAv7", + declared_cash_tip_money: { amount: BigInt(500), currency: "USD" }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/labor/timecards/id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.retrieveTimecard({ + id: "id", + }); + expect(response).toEqual({ + timecard: { + id: "T35HMQSN89SV4", + locationId: "PAA1RJZZKXBFG", + timezone: "America/New_York", + startAt: "2019-02-23T18:00:00-05:00", + endAt: "2019-02-23T21:00:00-05:00", + wage: { + title: "Cashier", + hourlyRate: { + amount: BigInt("1457"), + currency: "USD", + }, + jobId: "N4YKVLzFj3oGtNocqoYHYpW3", + tipEligible: true, + }, + breaks: [ + { + id: "M9BBKEPQAQD2T", + startAt: "2019-02-23T19:00:00-05:00", + endAt: "2019-02-23T20:00:00-05:00", + breakTypeId: "92EPDRQKJ5088", + name: "Lunch Break", + expectedDuration: "PT1H", + isPaid: true, + }, + ], + status: "CLOSED", + version: 1, + createdAt: "2019-02-27T00:12:12Z", + updatedAt: "2019-02-27T00:12:12Z", + teamMemberId: "D71KRMQof6cXGUW0aAv7", + declaredCashTipMoney: { + amount: BigInt("500"), + currency: "USD", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("UpdateTimecard", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + timecard: { + location_id: "PAA1RJZZKXBFG", + start_at: "2019-01-25T03:11:00-05:00", + end_at: "2019-01-25T13:11:00-05:00", + wage: { + title: "Bartender", + hourly_rate: { amount: BigInt(1500), currency: "USD" }, + tip_eligible: true, + }, + breaks: [ + { + id: "X7GAQYVVRRG6P", + start_at: "2019-01-25T06:11:00-05:00", + end_at: "2019-01-25T06:16:00-05:00", + break_type_id: "REGS1EQR1TPZ5", + name: "Tea Break", + expected_duration: "PT5M", + is_paid: true, + }, + ], + status: "CLOSED", + version: 1, + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + declared_cash_tip_money: { amount: BigInt(500), currency: "USD" }, + }, + }; + const rawResponseBody = { + timecard: { + id: "K0YH4CV5462JB", + location_id: "PAA1RJZZKXBFG", + timezone: "America/New_York", + start_at: "2019-01-25T03:11:00-05:00", + end_at: "2019-01-25T13:11:00-05:00", + wage: { + title: "Bartender", + hourly_rate: { amount: BigInt(1500), currency: "USD" }, + job_id: "dZtrPh5GSDGugyXGByesVp51", + tip_eligible: true, + }, + breaks: [ + { + id: "X7GAQYVVRRG6P", + start_at: "2019-01-25T06:11:00-05:00", + end_at: "2019-01-25T06:16:00-05:00", + break_type_id: "REGS1EQR1TPZ5", + name: "Tea Break", + expected_duration: "PT5M", + is_paid: true, + }, + ], + status: "CLOSED", + version: 2, + created_at: "2019-02-28T00:39:02Z", + updated_at: "2019-02-28T00:42:41Z", + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + declared_cash_tip_money: { amount: BigInt(500), currency: "USD" }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .put("/v2/labor/timecards/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.updateTimecard({ + id: "id", + timecard: { + locationId: "PAA1RJZZKXBFG", + startAt: "2019-01-25T03:11:00-05:00", + endAt: "2019-01-25T13:11:00-05:00", + wage: { + title: "Bartender", + hourlyRate: { + amount: BigInt("1500"), + currency: "USD", + }, + tipEligible: true, + }, + breaks: [ + { + id: "X7GAQYVVRRG6P", + startAt: "2019-01-25T06:11:00-05:00", + endAt: "2019-01-25T06:16:00-05:00", + breakTypeId: "REGS1EQR1TPZ5", + name: "Tea Break", + expectedDuration: "PT5M", + isPaid: true, + }, + ], + status: "CLOSED", + version: 1, + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + declaredCashTipMoney: { + amount: BigInt("500"), + currency: "USD", + }, + }, + }); + expect(response).toEqual({ + timecard: { + id: "K0YH4CV5462JB", + locationId: "PAA1RJZZKXBFG", + timezone: "America/New_York", + startAt: "2019-01-25T03:11:00-05:00", + endAt: "2019-01-25T13:11:00-05:00", + wage: { + title: "Bartender", + hourlyRate: { + amount: BigInt("1500"), + currency: "USD", + }, + jobId: "dZtrPh5GSDGugyXGByesVp51", + tipEligible: true, + }, + breaks: [ + { + id: "X7GAQYVVRRG6P", + startAt: "2019-01-25T06:11:00-05:00", + endAt: "2019-01-25T06:16:00-05:00", + breakTypeId: "REGS1EQR1TPZ5", + name: "Tea Break", + expectedDuration: "PT5M", + isPaid: true, + }, + ], + status: "CLOSED", + version: 2, + createdAt: "2019-02-28T00:39:02Z", + updatedAt: "2019-02-28T00:42:41Z", + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + declaredCashTipMoney: { + amount: BigInt("500"), + currency: "USD", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("DeleteTimecard", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/labor/timecards/id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.deleteTimecard({ + id: "id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/labor/breakTypes.test.ts b/tests/wire/labor/breakTypes.test.ts new file mode 100644 index 000000000..6f5e31b29 --- /dev/null +++ b/tests/wire/labor/breakTypes.test.ts @@ -0,0 +1,219 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("BreakTypes", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "PAD3NG5KSN2GL", + break_type: { + location_id: "CGJN03P1D08GF", + break_name: "Lunch Break", + expected_duration: "PT30M", + is_paid: true, + }, + }; + const rawResponseBody = { + break_type: { + id: "49SSVDJG76WF3", + location_id: "CGJN03P1D08GF", + break_name: "Lunch Break", + expected_duration: "PT30M", + is_paid: true, + version: 1, + created_at: "2019-02-26T22:42:54Z", + updated_at: "2019-02-26T22:42:54Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/labor/break-types") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.breakTypes.create({ + idempotencyKey: "PAD3NG5KSN2GL", + breakType: { + locationId: "CGJN03P1D08GF", + breakName: "Lunch Break", + expectedDuration: "PT30M", + isPaid: true, + }, + }); + expect(response).toEqual({ + breakType: { + id: "49SSVDJG76WF3", + locationId: "CGJN03P1D08GF", + breakName: "Lunch Break", + expectedDuration: "PT30M", + isPaid: true, + version: 1, + createdAt: "2019-02-26T22:42:54Z", + updatedAt: "2019-02-26T22:42:54Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + break_type: { + id: "lA0mj_RSOprNPwMUXdYp", + location_id: "059SB0E0WCNWS", + break_name: "Lunch Break", + expected_duration: "PT30M", + is_paid: true, + version: 1, + created_at: "2019-02-21T17:50:00Z", + updated_at: "2019-02-21T17:50:00Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/labor/break-types/id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.breakTypes.get({ + id: "id", + }); + expect(response).toEqual({ + breakType: { + id: "lA0mj_RSOprNPwMUXdYp", + locationId: "059SB0E0WCNWS", + breakName: "Lunch Break", + expectedDuration: "PT30M", + isPaid: true, + version: 1, + createdAt: "2019-02-21T17:50:00Z", + updatedAt: "2019-02-21T17:50:00Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + break_type: { + location_id: "26M7H24AZ9N6R", + break_name: "Lunch", + expected_duration: "PT50M", + is_paid: true, + version: 1, + }, + }; + const rawResponseBody = { + break_type: { + id: "Q6JSJS6D4DBCH", + location_id: "26M7H24AZ9N6R", + break_name: "Lunch", + expected_duration: "PT50M", + is_paid: true, + version: 2, + created_at: "2018-06-12T20:19:12Z", + updated_at: "2019-02-26T23:12:59Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .put("/v2/labor/break-types/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.breakTypes.update({ + id: "id", + breakType: { + locationId: "26M7H24AZ9N6R", + breakName: "Lunch", + expectedDuration: "PT50M", + isPaid: true, + version: 1, + }, + }); + expect(response).toEqual({ + breakType: { + id: "Q6JSJS6D4DBCH", + locationId: "26M7H24AZ9N6R", + breakName: "Lunch", + expectedDuration: "PT50M", + isPaid: true, + version: 2, + createdAt: "2018-06-12T20:19:12Z", + updatedAt: "2019-02-26T23:12:59Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/labor/break-types/id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.breakTypes.delete({ + id: "id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/labor/employeeWages.test.ts b/tests/wire/labor/employeeWages.test.ts new file mode 100644 index 000000000..84b376a06 --- /dev/null +++ b/tests/wire/labor/employeeWages.test.ts @@ -0,0 +1,53 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("EmployeeWages", () => { + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + employee_wage: { + id: "pXS3qCv7BERPnEGedM4S8mhm", + employee_id: "33fJchumvVdJwxV0H6L9", + title: "Manager", + hourly_rate: { amount: BigInt(2000), currency: "USD" }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/labor/employee-wages/id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.employeeWages.get({ + id: "id", + }); + expect(response).toEqual({ + employeeWage: { + id: "pXS3qCv7BERPnEGedM4S8mhm", + employeeId: "33fJchumvVdJwxV0H6L9", + title: "Manager", + hourlyRate: { + amount: BigInt("2000"), + currency: "USD", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/labor/shifts.test.ts b/tests/wire/labor/shifts.test.ts new file mode 100644 index 000000000..e614b9e17 --- /dev/null +++ b/tests/wire/labor/shifts.test.ts @@ -0,0 +1,651 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("Shifts", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "HIDSNG5KS478L", + shift: { + location_id: "PAA1RJZZKXBFG", + start_at: "2019-01-25T03:11:00-05:00", + end_at: "2019-01-25T13:11:00-05:00", + wage: { title: "Barista", hourly_rate: { amount: BigInt(1100), currency: "USD" }, tip_eligible: true }, + breaks: [ + { + start_at: "2019-01-25T06:11:00-05:00", + end_at: "2019-01-25T06:16:00-05:00", + break_type_id: "REGS1EQR1TPZ5", + name: "Tea Break", + expected_duration: "PT5M", + is_paid: true, + }, + ], + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + declared_cash_tip_money: { amount: BigInt(500), currency: "USD" }, + }, + }; + const rawResponseBody = { + shift: { + id: "K0YH4CV5462JB", + employee_id: "ormj0jJJZ5OZIzxrZYJI", + location_id: "PAA1RJZZKXBFG", + timezone: "America/New_York", + start_at: "2019-01-25T03:11:00-05:00", + end_at: "2019-01-25T13:11:00-05:00", + wage: { + title: "Barista", + hourly_rate: { amount: BigInt(1100), currency: "USD" }, + job_id: "FzbJAtt9qEWncK1BWgVCxQ6M", + tip_eligible: true, + }, + breaks: [ + { + id: "X7GAQYVVRRG6P", + start_at: "2019-01-25T06:11:00-05:00", + end_at: "2019-01-25T06:16:00-05:00", + break_type_id: "REGS1EQR1TPZ5", + name: "Tea Break", + expected_duration: "PT5M", + is_paid: true, + }, + ], + status: "CLOSED", + version: 1, + created_at: "2019-02-28T00:39:02Z", + updated_at: "2019-02-28T00:39:02Z", + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + declared_cash_tip_money: { amount: BigInt(500), currency: "USD" }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/labor/shifts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.shifts.create({ + idempotencyKey: "HIDSNG5KS478L", + shift: { + locationId: "PAA1RJZZKXBFG", + startAt: "2019-01-25T03:11:00-05:00", + endAt: "2019-01-25T13:11:00-05:00", + wage: { + title: "Barista", + hourlyRate: { + amount: BigInt("1100"), + currency: "USD", + }, + tipEligible: true, + }, + breaks: [ + { + startAt: "2019-01-25T06:11:00-05:00", + endAt: "2019-01-25T06:16:00-05:00", + breakTypeId: "REGS1EQR1TPZ5", + name: "Tea Break", + expectedDuration: "PT5M", + isPaid: true, + }, + ], + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + declaredCashTipMoney: { + amount: BigInt("500"), + currency: "USD", + }, + }, + }); + expect(response).toEqual({ + shift: { + id: "K0YH4CV5462JB", + employeeId: "ormj0jJJZ5OZIzxrZYJI", + locationId: "PAA1RJZZKXBFG", + timezone: "America/New_York", + startAt: "2019-01-25T03:11:00-05:00", + endAt: "2019-01-25T13:11:00-05:00", + wage: { + title: "Barista", + hourlyRate: { + amount: BigInt("1100"), + currency: "USD", + }, + jobId: "FzbJAtt9qEWncK1BWgVCxQ6M", + tipEligible: true, + }, + breaks: [ + { + id: "X7GAQYVVRRG6P", + startAt: "2019-01-25T06:11:00-05:00", + endAt: "2019-01-25T06:16:00-05:00", + breakTypeId: "REGS1EQR1TPZ5", + name: "Tea Break", + expectedDuration: "PT5M", + isPaid: true, + }, + ], + status: "CLOSED", + version: 1, + createdAt: "2019-02-28T00:39:02Z", + updatedAt: "2019-02-28T00:39:02Z", + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + declaredCashTipMoney: { + amount: BigInt("500"), + currency: "USD", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("search", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + query: { + filter: { + workday: { + date_range: { start_date: "2019-01-20", end_date: "2019-02-03" }, + match_shifts_by: "START_AT", + default_timezone: "America/Los_Angeles", + }, + }, + }, + limit: 100, + }; + const rawResponseBody = { + shifts: [ + { + id: "X714F3HA6D1PT", + employee_id: "ormj0jJJZ5OZIzxrZYJI", + location_id: "PAA1RJZZKXBFG", + timezone: "America/New_York", + start_at: "2019-01-21T03:11:00-05:00", + end_at: "2019-01-21T13:11:00-05:00", + wage: { + title: "Barista", + hourly_rate: { amount: BigInt(1100), currency: "USD" }, + job_id: "FzbJAtt9qEWncK1BWgVCxQ6M", + tip_eligible: true, + }, + breaks: [ + { + id: "SJW7X6AKEJQ65", + start_at: "2019-01-21T06:11:00-05:00", + end_at: "2019-01-21T06:11:00-05:00", + break_type_id: "REGS1EQR1TPZ5", + name: "Tea Break", + expected_duration: "PT10M", + is_paid: true, + }, + ], + status: "CLOSED", + version: 6, + created_at: "2019-01-24T01:12:03Z", + updated_at: "2019-02-07T22:21:08Z", + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + declared_cash_tip_money: { amount: BigInt(500), currency: "USD" }, + }, + { + id: "GDHYBZYWK0P2V", + employee_id: "33fJchumvVdJwxV0H6L9", + location_id: "PAA1RJZZKXBFG", + timezone: "America/New_York", + start_at: "2019-01-22T12:02:00-05:00", + end_at: "2019-01-22T13:02:00-05:00", + wage: { + title: "Cook", + hourly_rate: { amount: BigInt(1600), currency: "USD" }, + job_id: "gcbz15vKGnMKmaWJJ152kjim", + tip_eligible: true, + }, + breaks: [ + { + id: "BKS6VR7WR748A", + start_at: "2019-01-23T14:30:00-05:00", + end_at: "2019-01-23T14:40:00-05:00", + break_type_id: "WQX00VR99F53J", + name: "Tea Break", + expected_duration: "PT10M", + is_paid: true, + }, + { + id: "BQFEZSHFZSC51", + start_at: "2019-01-22T12:30:00-05:00", + end_at: "2019-01-22T12:44:00-05:00", + break_type_id: "P6Q468ZFRN1AC", + name: "Coffee Break", + expected_duration: "PT15M", + is_paid: false, + }, + ], + status: "CLOSED", + version: 16, + created_at: "2019-01-23T23:32:45Z", + updated_at: "2019-01-24T00:56:25Z", + team_member_id: "33fJchumvVdJwxV0H6L9", + declared_cash_tip_money: { amount: BigInt(0), currency: "USD" }, + }, + ], + cursor: "cursor", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/labor/shifts/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.shifts.search({ + query: { + filter: { + workday: { + dateRange: { + startDate: "2019-01-20", + endDate: "2019-02-03", + }, + matchShiftsBy: "START_AT", + defaultTimezone: "America/Los_Angeles", + }, + }, + }, + limit: 100, + }); + expect(response).toEqual({ + shifts: [ + { + id: "X714F3HA6D1PT", + employeeId: "ormj0jJJZ5OZIzxrZYJI", + locationId: "PAA1RJZZKXBFG", + timezone: "America/New_York", + startAt: "2019-01-21T03:11:00-05:00", + endAt: "2019-01-21T13:11:00-05:00", + wage: { + title: "Barista", + hourlyRate: { + amount: BigInt("1100"), + currency: "USD", + }, + jobId: "FzbJAtt9qEWncK1BWgVCxQ6M", + tipEligible: true, + }, + breaks: [ + { + id: "SJW7X6AKEJQ65", + startAt: "2019-01-21T06:11:00-05:00", + endAt: "2019-01-21T06:11:00-05:00", + breakTypeId: "REGS1EQR1TPZ5", + name: "Tea Break", + expectedDuration: "PT10M", + isPaid: true, + }, + ], + status: "CLOSED", + version: 6, + createdAt: "2019-01-24T01:12:03Z", + updatedAt: "2019-02-07T22:21:08Z", + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + declaredCashTipMoney: { + amount: BigInt("500"), + currency: "USD", + }, + }, + { + id: "GDHYBZYWK0P2V", + employeeId: "33fJchumvVdJwxV0H6L9", + locationId: "PAA1RJZZKXBFG", + timezone: "America/New_York", + startAt: "2019-01-22T12:02:00-05:00", + endAt: "2019-01-22T13:02:00-05:00", + wage: { + title: "Cook", + hourlyRate: { + amount: BigInt("1600"), + currency: "USD", + }, + jobId: "gcbz15vKGnMKmaWJJ152kjim", + tipEligible: true, + }, + breaks: [ + { + id: "BKS6VR7WR748A", + startAt: "2019-01-23T14:30:00-05:00", + endAt: "2019-01-23T14:40:00-05:00", + breakTypeId: "WQX00VR99F53J", + name: "Tea Break", + expectedDuration: "PT10M", + isPaid: true, + }, + { + id: "BQFEZSHFZSC51", + startAt: "2019-01-22T12:30:00-05:00", + endAt: "2019-01-22T12:44:00-05:00", + breakTypeId: "P6Q468ZFRN1AC", + name: "Coffee Break", + expectedDuration: "PT15M", + isPaid: false, + }, + ], + status: "CLOSED", + version: 16, + createdAt: "2019-01-23T23:32:45Z", + updatedAt: "2019-01-24T00:56:25Z", + teamMemberId: "33fJchumvVdJwxV0H6L9", + declaredCashTipMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + ], + cursor: "cursor", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + shift: { + id: "T35HMQSN89SV4", + employee_id: "D71KRMQof6cXGUW0aAv7", + location_id: "PAA1RJZZKXBFG", + timezone: "America/New_York", + start_at: "2019-02-23T18:00:00-05:00", + end_at: "2019-02-23T21:00:00-05:00", + wage: { + title: "Cashier", + hourly_rate: { amount: BigInt(1457), currency: "USD" }, + job_id: "N4YKVLzFj3oGtNocqoYHYpW3", + tip_eligible: true, + }, + breaks: [ + { + id: "M9BBKEPQAQD2T", + start_at: "2019-02-23T19:00:00-05:00", + end_at: "2019-02-23T20:00:00-05:00", + break_type_id: "92EPDRQKJ5088", + name: "Lunch Break", + expected_duration: "PT1H", + is_paid: true, + }, + ], + status: "CLOSED", + version: 1, + created_at: "2019-02-27T00:12:12Z", + updated_at: "2019-02-27T00:12:12Z", + team_member_id: "D71KRMQof6cXGUW0aAv7", + declared_cash_tip_money: { amount: BigInt(500), currency: "USD" }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/labor/shifts/id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.shifts.get({ + id: "id", + }); + expect(response).toEqual({ + shift: { + id: "T35HMQSN89SV4", + employeeId: "D71KRMQof6cXGUW0aAv7", + locationId: "PAA1RJZZKXBFG", + timezone: "America/New_York", + startAt: "2019-02-23T18:00:00-05:00", + endAt: "2019-02-23T21:00:00-05:00", + wage: { + title: "Cashier", + hourlyRate: { + amount: BigInt("1457"), + currency: "USD", + }, + jobId: "N4YKVLzFj3oGtNocqoYHYpW3", + tipEligible: true, + }, + breaks: [ + { + id: "M9BBKEPQAQD2T", + startAt: "2019-02-23T19:00:00-05:00", + endAt: "2019-02-23T20:00:00-05:00", + breakTypeId: "92EPDRQKJ5088", + name: "Lunch Break", + expectedDuration: "PT1H", + isPaid: true, + }, + ], + status: "CLOSED", + version: 1, + createdAt: "2019-02-27T00:12:12Z", + updatedAt: "2019-02-27T00:12:12Z", + teamMemberId: "D71KRMQof6cXGUW0aAv7", + declaredCashTipMoney: { + amount: BigInt("500"), + currency: "USD", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + shift: { + location_id: "PAA1RJZZKXBFG", + start_at: "2019-01-25T03:11:00-05:00", + end_at: "2019-01-25T13:11:00-05:00", + wage: { + title: "Bartender", + hourly_rate: { amount: BigInt(1500), currency: "USD" }, + tip_eligible: true, + }, + breaks: [ + { + id: "X7GAQYVVRRG6P", + start_at: "2019-01-25T06:11:00-05:00", + end_at: "2019-01-25T06:16:00-05:00", + break_type_id: "REGS1EQR1TPZ5", + name: "Tea Break", + expected_duration: "PT5M", + is_paid: true, + }, + ], + version: 1, + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + declared_cash_tip_money: { amount: BigInt(500), currency: "USD" }, + }, + }; + const rawResponseBody = { + shift: { + id: "K0YH4CV5462JB", + employee_id: "ormj0jJJZ5OZIzxrZYJI", + location_id: "PAA1RJZZKXBFG", + timezone: "America/New_York", + start_at: "2019-01-25T03:11:00-05:00", + end_at: "2019-01-25T13:11:00-05:00", + wage: { + title: "Bartender", + hourly_rate: { amount: BigInt(1500), currency: "USD" }, + job_id: "dZtrPh5GSDGugyXGByesVp51", + tip_eligible: true, + }, + breaks: [ + { + id: "X7GAQYVVRRG6P", + start_at: "2019-01-25T06:11:00-05:00", + end_at: "2019-01-25T06:16:00-05:00", + break_type_id: "REGS1EQR1TPZ5", + name: "Tea Break", + expected_duration: "PT5M", + is_paid: true, + }, + ], + status: "CLOSED", + version: 2, + created_at: "2019-02-28T00:39:02Z", + updated_at: "2019-02-28T00:42:41Z", + team_member_id: "ormj0jJJZ5OZIzxrZYJI", + declared_cash_tip_money: { amount: BigInt(500), currency: "USD" }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .put("/v2/labor/shifts/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.shifts.update({ + id: "id", + shift: { + locationId: "PAA1RJZZKXBFG", + startAt: "2019-01-25T03:11:00-05:00", + endAt: "2019-01-25T13:11:00-05:00", + wage: { + title: "Bartender", + hourlyRate: { + amount: BigInt("1500"), + currency: "USD", + }, + tipEligible: true, + }, + breaks: [ + { + id: "X7GAQYVVRRG6P", + startAt: "2019-01-25T06:11:00-05:00", + endAt: "2019-01-25T06:16:00-05:00", + breakTypeId: "REGS1EQR1TPZ5", + name: "Tea Break", + expectedDuration: "PT5M", + isPaid: true, + }, + ], + version: 1, + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + declaredCashTipMoney: { + amount: BigInt("500"), + currency: "USD", + }, + }, + }); + expect(response).toEqual({ + shift: { + id: "K0YH4CV5462JB", + employeeId: "ormj0jJJZ5OZIzxrZYJI", + locationId: "PAA1RJZZKXBFG", + timezone: "America/New_York", + startAt: "2019-01-25T03:11:00-05:00", + endAt: "2019-01-25T13:11:00-05:00", + wage: { + title: "Bartender", + hourlyRate: { + amount: BigInt("1500"), + currency: "USD", + }, + jobId: "dZtrPh5GSDGugyXGByesVp51", + tipEligible: true, + }, + breaks: [ + { + id: "X7GAQYVVRRG6P", + startAt: "2019-01-25T06:11:00-05:00", + endAt: "2019-01-25T06:16:00-05:00", + breakTypeId: "REGS1EQR1TPZ5", + name: "Tea Break", + expectedDuration: "PT5M", + isPaid: true, + }, + ], + status: "CLOSED", + version: 2, + createdAt: "2019-02-28T00:39:02Z", + updatedAt: "2019-02-28T00:42:41Z", + teamMemberId: "ormj0jJJZ5OZIzxrZYJI", + declaredCashTipMoney: { + amount: BigInt("500"), + currency: "USD", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/labor/shifts/id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.shifts.delete({ + id: "id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/labor/teamMemberWages.test.ts b/tests/wire/labor/teamMemberWages.test.ts new file mode 100644 index 000000000..b1ccd8bd5 --- /dev/null +++ b/tests/wire/labor/teamMemberWages.test.ts @@ -0,0 +1,57 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("TeamMemberWages", () => { + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + team_member_wage: { + id: "pXS3qCv7BERPnEGedM4S8mhm", + team_member_id: "33fJchumvVdJwxV0H6L9", + title: "Manager", + hourly_rate: { amount: BigInt(2000), currency: "USD" }, + job_id: "jxJNN6eCJsLrhg5UFJrDWDGE", + tip_eligible: false, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/labor/team-member-wages/id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.teamMemberWages.get({ + id: "id", + }); + expect(response).toEqual({ + teamMemberWage: { + id: "pXS3qCv7BERPnEGedM4S8mhm", + teamMemberId: "33fJchumvVdJwxV0H6L9", + title: "Manager", + hourlyRate: { + amount: BigInt("2000"), + currency: "USD", + }, + jobId: "jxJNN6eCJsLrhg5UFJrDWDGE", + tipEligible: false, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/labor/workweekConfigs.test.ts b/tests/wire/labor/workweekConfigs.test.ts new file mode 100644 index 000000000..05e8a06e0 --- /dev/null +++ b/tests/wire/labor/workweekConfigs.test.ts @@ -0,0 +1,62 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("WorkweekConfigs", () => { + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + workweek_config: { start_of_week: "MON", start_of_day_local_time: "10:00", version: 10 }, + }; + const rawResponseBody = { + workweek_config: { + id: "FY4VCAQN700GM", + start_of_week: "MON", + start_of_day_local_time: "10:00", + version: 11, + created_at: "2016-02-04T00:58:24Z", + updated_at: "2019-02-28T01:04:35Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .put("/v2/labor/workweek-configs/id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.labor.workweekConfigs.get({ + id: "id", + workweekConfig: { + startOfWeek: "MON", + startOfDayLocalTime: "10:00", + version: 10, + }, + }); + expect(response).toEqual({ + workweekConfig: { + id: "FY4VCAQN700GM", + startOfWeek: "MON", + startOfDayLocalTime: "10:00", + version: 11, + createdAt: "2016-02-04T00:58:24Z", + updatedAt: "2019-02-28T01:04:35Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/locations.test.ts b/tests/wire/locations.test.ts new file mode 100644 index 000000000..2cde675ff --- /dev/null +++ b/tests/wire/locations.test.ts @@ -0,0 +1,1109 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Locations", () => { + test("list", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + locations: [ + { + id: "18YC4JDH91E1H", + name: "Grant Park", + address: { + address_line_1: "123 Main St", + locality: "San Francisco", + administrative_district_level_1: "CA", + postal_code: "94114", + country: "US", + }, + timezone: "America/Los_Angeles", + capabilities: ["CREDIT_CARD_PROCESSING"], + status: "ACTIVE", + created_at: "2016-09-19T17:33:12Z", + merchant_id: "3MYCJG5GVYQ8Q", + country: "US", + language_code: "en-US", + currency: "USD", + phone_number: "+1 650-354-7217", + business_name: "Jet Fuel Coffee", + type: "PHYSICAL", + website_url: "website_url", + business_email: "business_email", + description: "description", + twitter_username: "twitter_username", + instagram_username: "instagram_username", + facebook_url: "facebook_url", + logo_url: "logo_url", + pos_background_url: "pos_background_url", + mcc: "mcc", + full_format_logo_url: "full_format_logo_url", + }, + { + id: "3Z4V4WHQK64X9", + name: "Midtown", + address: { + address_line_1: "1234 Peachtree St. NE", + locality: "Atlanta", + administrative_district_level_1: "GA", + postal_code: "30309", + }, + timezone: "America/New_York", + capabilities: ["CREDIT_CARD_PROCESSING"], + status: "ACTIVE", + created_at: "2022-02-19T17:58:25Z", + merchant_id: "3MYCJG5GVYQ8Q", + country: "US", + language_code: "en-US", + currency: "USD", + phone_number: "phone_number", + business_name: "Jet Fuel Coffee", + type: "PHYSICAL", + website_url: "website_url", + business_email: "business_email", + description: "Midtown Atlanta store", + twitter_username: "twitter_username", + instagram_username: "instagram_username", + facebook_url: "facebook_url", + coordinates: { latitude: 33.7889, longitude: -84.3841 }, + logo_url: "logo_url", + pos_background_url: "pos_background_url", + mcc: "7299", + full_format_logo_url: "full_format_logo_url", + }, + ], + }; + server.mockEndpoint().get("/v2/locations").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.locations.list(); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + locations: [ + { + id: "18YC4JDH91E1H", + name: "Grant Park", + address: { + addressLine1: "123 Main St", + locality: "San Francisco", + administrativeDistrictLevel1: "CA", + postalCode: "94114", + country: "US", + }, + timezone: "America/Los_Angeles", + capabilities: ["CREDIT_CARD_PROCESSING"], + status: "ACTIVE", + createdAt: "2016-09-19T17:33:12Z", + merchantId: "3MYCJG5GVYQ8Q", + country: "US", + languageCode: "en-US", + currency: "USD", + phoneNumber: "+1 650-354-7217", + businessName: "Jet Fuel Coffee", + type: "PHYSICAL", + websiteUrl: "website_url", + businessEmail: "business_email", + description: "description", + twitterUsername: "twitter_username", + instagramUsername: "instagram_username", + facebookUrl: "facebook_url", + logoUrl: "logo_url", + posBackgroundUrl: "pos_background_url", + mcc: "mcc", + fullFormatLogoUrl: "full_format_logo_url", + }, + { + id: "3Z4V4WHQK64X9", + name: "Midtown", + address: { + addressLine1: "1234 Peachtree St. NE", + locality: "Atlanta", + administrativeDistrictLevel1: "GA", + postalCode: "30309", + }, + timezone: "America/New_York", + capabilities: ["CREDIT_CARD_PROCESSING"], + status: "ACTIVE", + createdAt: "2022-02-19T17:58:25Z", + merchantId: "3MYCJG5GVYQ8Q", + country: "US", + languageCode: "en-US", + currency: "USD", + phoneNumber: "phone_number", + businessName: "Jet Fuel Coffee", + type: "PHYSICAL", + websiteUrl: "website_url", + businessEmail: "business_email", + description: "Midtown Atlanta store", + twitterUsername: "twitter_username", + instagramUsername: "instagram_username", + facebookUrl: "facebook_url", + coordinates: { + latitude: 33.7889, + longitude: -84.3841, + }, + logoUrl: "logo_url", + posBackgroundUrl: "pos_background_url", + mcc: "7299", + fullFormatLogoUrl: "full_format_logo_url", + }, + ], + }); + }); + + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + location: { + name: "Midtown", + address: { + address_line_1: "1234 Peachtree St. NE", + locality: "Atlanta", + administrative_district_level_1: "GA", + postal_code: "30309", + }, + description: "Midtown Atlanta store", + }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + location: { + id: "3Z4V4WHQK64X9", + name: "Midtown", + address: { + address_line_1: "1234 Peachtree St. NE", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "Atlanta", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "GA", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "30309", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + timezone: "America/New_York", + capabilities: ["CREDIT_CARD_PROCESSING"], + status: "ACTIVE", + created_at: "2022-02-19T17:58:25Z", + merchant_id: "3MYCJG5GVYQ8Q", + country: "US", + language_code: "en-US", + currency: "USD", + phone_number: "phone_number", + business_name: "Jet Fuel Coffee", + type: "PHYSICAL", + website_url: "website_url", + business_hours: { periods: [{}] }, + business_email: "business_email", + description: "Midtown Atlanta store", + twitter_username: "twitter_username", + instagram_username: "instagram_username", + facebook_url: "facebook_url", + coordinates: { latitude: 33.7889, longitude: -84.3841 }, + logo_url: "logo_url", + pos_background_url: "pos_background_url", + mcc: "7299", + full_format_logo_url: "full_format_logo_url", + tax_ids: { + eu_vat: "eu_vat", + fr_siret: "fr_siret", + fr_naf: "fr_naf", + es_nif: "es_nif", + jp_qii: "jp_qii", + }, + }, + }; + server + .mockEndpoint() + .post("/v2/locations") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.locations.create({ + location: { + name: "Midtown", + address: { + addressLine1: "1234 Peachtree St. NE", + locality: "Atlanta", + administrativeDistrictLevel1: "GA", + postalCode: "30309", + }, + description: "Midtown Atlanta store", + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + location: { + id: "3Z4V4WHQK64X9", + name: "Midtown", + address: { + addressLine1: "1234 Peachtree St. NE", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "Atlanta", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "GA", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "30309", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + timezone: "America/New_York", + capabilities: ["CREDIT_CARD_PROCESSING"], + status: "ACTIVE", + createdAt: "2022-02-19T17:58:25Z", + merchantId: "3MYCJG5GVYQ8Q", + country: "US", + languageCode: "en-US", + currency: "USD", + phoneNumber: "phone_number", + businessName: "Jet Fuel Coffee", + type: "PHYSICAL", + websiteUrl: "website_url", + businessHours: { + periods: [{}], + }, + businessEmail: "business_email", + description: "Midtown Atlanta store", + twitterUsername: "twitter_username", + instagramUsername: "instagram_username", + facebookUrl: "facebook_url", + coordinates: { + latitude: 33.7889, + longitude: -84.3841, + }, + logoUrl: "logo_url", + posBackgroundUrl: "pos_background_url", + mcc: "7299", + fullFormatLogoUrl: "full_format_logo_url", + taxIds: { + euVat: "eu_vat", + frSiret: "fr_siret", + frNaf: "fr_naf", + esNif: "es_nif", + jpQii: "jp_qii", + }, + }, + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + location: { + id: "18YC4JDH91E1H", + name: "Grant Park", + address: { + address_line_1: "123 Main St", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "San Francisco", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "CA", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "94114", + country: "US", + first_name: "first_name", + last_name: "last_name", + }, + timezone: "America/Los_Angeles", + capabilities: ["CREDIT_CARD_PROCESSING"], + status: "ACTIVE", + created_at: "2016-09-19T17:33:12Z", + merchant_id: "3MYCJG5GVYQ8Q", + country: "US", + language_code: "en-US", + currency: "USD", + phone_number: "+1 650-354-7217", + business_name: "Jet Fuel Coffee", + type: "PHYSICAL", + website_url: "website_url", + business_hours: { periods: [{}] }, + business_email: "business_email", + description: "description", + twitter_username: "twitter_username", + instagram_username: "instagram_username", + facebook_url: "facebook_url", + coordinates: { latitude: 1.1, longitude: 1.1 }, + logo_url: "logo_url", + pos_background_url: "pos_background_url", + mcc: "mcc", + full_format_logo_url: "full_format_logo_url", + tax_ids: { + eu_vat: "eu_vat", + fr_siret: "fr_siret", + fr_naf: "fr_naf", + es_nif: "es_nif", + jp_qii: "jp_qii", + }, + }, + }; + server + .mockEndpoint() + .get("/v2/locations/location_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.locations.get({ + locationId: "location_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + location: { + id: "18YC4JDH91E1H", + name: "Grant Park", + address: { + addressLine1: "123 Main St", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "San Francisco", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "CA", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "94114", + country: "US", + firstName: "first_name", + lastName: "last_name", + }, + timezone: "America/Los_Angeles", + capabilities: ["CREDIT_CARD_PROCESSING"], + status: "ACTIVE", + createdAt: "2016-09-19T17:33:12Z", + merchantId: "3MYCJG5GVYQ8Q", + country: "US", + languageCode: "en-US", + currency: "USD", + phoneNumber: "+1 650-354-7217", + businessName: "Jet Fuel Coffee", + type: "PHYSICAL", + websiteUrl: "website_url", + businessHours: { + periods: [{}], + }, + businessEmail: "business_email", + description: "description", + twitterUsername: "twitter_username", + instagramUsername: "instagram_username", + facebookUrl: "facebook_url", + coordinates: { + latitude: 1.1, + longitude: 1.1, + }, + logoUrl: "logo_url", + posBackgroundUrl: "pos_background_url", + mcc: "mcc", + fullFormatLogoUrl: "full_format_logo_url", + taxIds: { + euVat: "eu_vat", + frSiret: "fr_siret", + frNaf: "fr_naf", + esNif: "es_nif", + jpQii: "jp_qii", + }, + }, + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + location: { + business_hours: { + periods: [ + { day_of_week: "FRI", start_local_time: "07:00", end_local_time: "18:00" }, + { day_of_week: "SAT", start_local_time: "07:00", end_local_time: "18:00" }, + { day_of_week: "SUN", start_local_time: "09:00", end_local_time: "15:00" }, + ], + }, + description: "Midtown Atlanta store - Open weekends", + }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + location: { + id: "3Z4V4WHQK64X9", + name: "Midtown", + address: { + address_line_1: "1234 Peachtree St. NE", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "Atlanta", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "GA", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "30309", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + timezone: "America/New_York", + capabilities: ["CREDIT_CARD_PROCESSING"], + status: "ACTIVE", + created_at: "2022-02-19T17:58:25Z", + merchant_id: "3MYCJG5GVYQ8Q", + country: "US", + language_code: "en-US", + currency: "USD", + phone_number: "phone_number", + business_name: "Jet Fuel Coffee", + type: "PHYSICAL", + website_url: "website_url", + business_hours: { + periods: [ + { day_of_week: "FRI", start_local_time: "07:00", end_local_time: "18:00" }, + { day_of_week: "SAT", start_local_time: "07:00", end_local_time: "18:00" }, + { day_of_week: "SUN", start_local_time: "09:00", end_local_time: "15:00" }, + ], + }, + business_email: "business_email", + description: "Midtown Atlanta store - Open weekends", + twitter_username: "twitter_username", + instagram_username: "instagram_username", + facebook_url: "facebook_url", + coordinates: { latitude: 33.7889, longitude: -84.3841 }, + logo_url: "logo_url", + pos_background_url: "pos_background_url", + mcc: "7299", + full_format_logo_url: "full_format_logo_url", + tax_ids: { + eu_vat: "eu_vat", + fr_siret: "fr_siret", + fr_naf: "fr_naf", + es_nif: "es_nif", + jp_qii: "jp_qii", + }, + }, + }; + server + .mockEndpoint() + .put("/v2/locations/location_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.locations.update({ + locationId: "location_id", + location: { + businessHours: { + periods: [ + { + dayOfWeek: "FRI", + startLocalTime: "07:00", + endLocalTime: "18:00", + }, + { + dayOfWeek: "SAT", + startLocalTime: "07:00", + endLocalTime: "18:00", + }, + { + dayOfWeek: "SUN", + startLocalTime: "09:00", + endLocalTime: "15:00", + }, + ], + }, + description: "Midtown Atlanta store - Open weekends", + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + location: { + id: "3Z4V4WHQK64X9", + name: "Midtown", + address: { + addressLine1: "1234 Peachtree St. NE", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "Atlanta", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "GA", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "30309", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + timezone: "America/New_York", + capabilities: ["CREDIT_CARD_PROCESSING"], + status: "ACTIVE", + createdAt: "2022-02-19T17:58:25Z", + merchantId: "3MYCJG5GVYQ8Q", + country: "US", + languageCode: "en-US", + currency: "USD", + phoneNumber: "phone_number", + businessName: "Jet Fuel Coffee", + type: "PHYSICAL", + websiteUrl: "website_url", + businessHours: { + periods: [ + { + dayOfWeek: "FRI", + startLocalTime: "07:00", + endLocalTime: "18:00", + }, + { + dayOfWeek: "SAT", + startLocalTime: "07:00", + endLocalTime: "18:00", + }, + { + dayOfWeek: "SUN", + startLocalTime: "09:00", + endLocalTime: "15:00", + }, + ], + }, + businessEmail: "business_email", + description: "Midtown Atlanta store - Open weekends", + twitterUsername: "twitter_username", + instagramUsername: "instagram_username", + facebookUrl: "facebook_url", + coordinates: { + latitude: 33.7889, + longitude: -84.3841, + }, + logoUrl: "logo_url", + posBackgroundUrl: "pos_background_url", + mcc: "7299", + fullFormatLogoUrl: "full_format_logo_url", + taxIds: { + euVat: "eu_vat", + frSiret: "fr_siret", + frNaf: "fr_naf", + esNif: "es_nif", + jpQii: "jp_qii", + }, + }, + }); + }); + + test("checkouts", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "86ae1696-b1e3-4328-af6d-f1e04d947ad6", + order: { + order: { + location_id: "location_id", + reference_id: "reference_id", + customer_id: "customer_id", + line_items: [ + { + name: "Printed T Shirt", + quantity: "2", + applied_taxes: [{ tax_uid: "38ze1696-z1e3-5628-af6d-f1e04d947fg3" }], + applied_discounts: [{ discount_uid: "56ae1696-z1e3-9328-af6d-f1e04d947gd4" }], + base_price_money: { amount: BigInt(1500), currency: "USD" }, + }, + { + name: "Slim Jeans", + quantity: "1", + base_price_money: { amount: BigInt(2500), currency: "USD" }, + }, + { + name: "Woven Sweater", + quantity: "3", + base_price_money: { amount: BigInt(3500), currency: "USD" }, + }, + ], + taxes: [ + { + uid: "38ze1696-z1e3-5628-af6d-f1e04d947fg3", + type: "INCLUSIVE", + percentage: "7.75", + scope: "LINE_ITEM", + }, + ], + discounts: [ + { + uid: "56ae1696-z1e3-9328-af6d-f1e04d947gd4", + type: "FIXED_AMOUNT", + amount_money: { amount: BigInt(100), currency: "USD" }, + scope: "LINE_ITEM", + }, + ], + }, + idempotency_key: "12ae1696-z1e3-4328-af6d-f1e04d947gd4", + }, + ask_for_shipping_address: true, + merchant_support_email: "merchant+support@website.com", + pre_populate_buyer_email: "example@email.com", + pre_populate_shipping_address: { + address_line_1: "1455 Market St.", + address_line_2: "Suite 600", + locality: "San Francisco", + administrative_district_level_1: "CA", + postal_code: "94103", + country: "US", + first_name: "Jane", + last_name: "Doe", + }, + redirect_url: "https://merchant.website.com/order-confirm", + additional_recipients: [ + { + location_id: "057P5VYJ4A5X1", + description: "Application fees", + amount_money: { amount: BigInt(60), currency: "USD" }, + }, + ], + }; + const rawResponseBody = { + checkout: { + id: "CAISEHGimXh-C3RIT4og1a6u1qw", + checkout_page_url: + "https://connect.squareup.com/v2/checkout?c=CAISEHGimXh-C3RIT4og1a6u1qw&l=CYTKRM7R7JMV8", + ask_for_shipping_address: true, + merchant_support_email: "merchant+support@website.com", + pre_populate_buyer_email: "example@email.com", + pre_populate_shipping_address: { + address_line_1: "1455 Market St.", + address_line_2: "Suite 600", + address_line_3: "address_line_3", + locality: "San Francisco", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "CA", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "94103", + country: "US", + first_name: "Jane", + last_name: "Doe", + }, + redirect_url: "https://merchant.website.com/order-confirm", + order: { + id: "id", + location_id: "location_id", + reference_id: "reference_id", + customer_id: "customer_id", + line_items: [ + { + name: "Printed T Shirt", + quantity: "2", + applied_taxes: [ + { + tax_uid: "38ze1696-z1e3-5628-af6d-f1e04d947fg3", + applied_money: { amount: BigInt(103), currency: "USD" }, + }, + ], + applied_discounts: [ + { + discount_uid: "56ae1696-z1e3-9328-af6d-f1e04d947gd4", + applied_money: { amount: BigInt(100), currency: "USD" }, + }, + ], + base_price_money: { amount: BigInt(1500), currency: "USD" }, + total_tax_money: { amount: BigInt(103), currency: "USD" }, + total_discount_money: { amount: BigInt(100), currency: "USD" }, + total_money: { amount: BigInt(1503), currency: "USD" }, + }, + { + name: "Slim Jeans", + quantity: "1", + base_price_money: { amount: BigInt(2500), currency: "USD" }, + total_money: { amount: BigInt(2500), currency: "USD" }, + }, + { + name: "Woven Sweater", + quantity: "3", + base_price_money: { amount: BigInt(3500), currency: "USD" }, + total_money: { amount: BigInt(10500), currency: "USD" }, + }, + ], + taxes: [ + { + uid: "38ze1696-z1e3-5628-af6d-f1e04d947fg3", + type: "INCLUSIVE", + percentage: "7.75", + scope: "LINE_ITEM", + }, + ], + discounts: [ + { + uid: "56ae1696-z1e3-9328-af6d-f1e04d947gd4", + type: "FIXED_AMOUNT", + amount_money: { amount: BigInt(100), currency: "USD" }, + applied_money: { amount: BigInt(100), currency: "USD" }, + scope: "LINE_ITEM", + }, + ], + service_charges: [{}], + fulfillments: [{}], + returns: [{}], + tenders: [{ type: "CARD" }], + refunds: [ + { id: "id", location_id: "location_id", reason: "reason", amount_money: {}, status: "PENDING" }, + ], + created_at: "created_at", + updated_at: "updated_at", + closed_at: "closed_at", + state: "OPEN", + version: 1, + total_money: { amount: BigInt(14503), currency: "USD" }, + total_tax_money: { amount: BigInt(103), currency: "USD" }, + total_discount_money: { amount: BigInt(100), currency: "USD" }, + ticket_name: "ticket_name", + rewards: [{ id: "id", reward_tier_id: "reward_tier_id" }], + }, + created_at: "2017-06-16T22:25:35Z", + additional_recipients: [ + { + location_id: "057P5VYJ4A5X1", + description: "Application fees", + amount_money: { amount: BigInt(60), currency: "USD" }, + }, + ], + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/locations/location_id/checkouts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.locations.checkouts({ + locationId: "location_id", + idempotencyKey: "86ae1696-b1e3-4328-af6d-f1e04d947ad6", + order: { + order: { + locationId: "location_id", + referenceId: "reference_id", + customerId: "customer_id", + lineItems: [ + { + name: "Printed T Shirt", + quantity: "2", + appliedTaxes: [ + { + taxUid: "38ze1696-z1e3-5628-af6d-f1e04d947fg3", + }, + ], + appliedDiscounts: [ + { + discountUid: "56ae1696-z1e3-9328-af6d-f1e04d947gd4", + }, + ], + basePriceMoney: { + amount: BigInt("1500"), + currency: "USD", + }, + }, + { + name: "Slim Jeans", + quantity: "1", + basePriceMoney: { + amount: BigInt("2500"), + currency: "USD", + }, + }, + { + name: "Woven Sweater", + quantity: "3", + basePriceMoney: { + amount: BigInt("3500"), + currency: "USD", + }, + }, + ], + taxes: [ + { + uid: "38ze1696-z1e3-5628-af6d-f1e04d947fg3", + type: "INCLUSIVE", + percentage: "7.75", + scope: "LINE_ITEM", + }, + ], + discounts: [ + { + uid: "56ae1696-z1e3-9328-af6d-f1e04d947gd4", + type: "FIXED_AMOUNT", + amountMoney: { + amount: BigInt("100"), + currency: "USD", + }, + scope: "LINE_ITEM", + }, + ], + }, + idempotencyKey: "12ae1696-z1e3-4328-af6d-f1e04d947gd4", + }, + askForShippingAddress: true, + merchantSupportEmail: "merchant+support@website.com", + prePopulateBuyerEmail: "example@email.com", + prePopulateShippingAddress: { + addressLine1: "1455 Market St.", + addressLine2: "Suite 600", + locality: "San Francisco", + administrativeDistrictLevel1: "CA", + postalCode: "94103", + country: "US", + firstName: "Jane", + lastName: "Doe", + }, + redirectUrl: "https://merchant.website.com/order-confirm", + additionalRecipients: [ + { + locationId: "057P5VYJ4A5X1", + description: "Application fees", + amountMoney: { + amount: BigInt("60"), + currency: "USD", + }, + }, + ], + }); + expect(response).toEqual({ + checkout: { + id: "CAISEHGimXh-C3RIT4og1a6u1qw", + checkoutPageUrl: + "https://connect.squareup.com/v2/checkout?c=CAISEHGimXh-C3RIT4og1a6u1qw&l=CYTKRM7R7JMV8", + askForShippingAddress: true, + merchantSupportEmail: "merchant+support@website.com", + prePopulateBuyerEmail: "example@email.com", + prePopulateShippingAddress: { + addressLine1: "1455 Market St.", + addressLine2: "Suite 600", + addressLine3: "address_line_3", + locality: "San Francisco", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "CA", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "94103", + country: "US", + firstName: "Jane", + lastName: "Doe", + }, + redirectUrl: "https://merchant.website.com/order-confirm", + order: { + id: "id", + locationId: "location_id", + referenceId: "reference_id", + customerId: "customer_id", + lineItems: [ + { + name: "Printed T Shirt", + quantity: "2", + appliedTaxes: [ + { + taxUid: "38ze1696-z1e3-5628-af6d-f1e04d947fg3", + appliedMoney: { + amount: BigInt("103"), + currency: "USD", + }, + }, + ], + appliedDiscounts: [ + { + discountUid: "56ae1696-z1e3-9328-af6d-f1e04d947gd4", + appliedMoney: { + amount: BigInt("100"), + currency: "USD", + }, + }, + ], + basePriceMoney: { + amount: BigInt("1500"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("103"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("100"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("1503"), + currency: "USD", + }, + }, + { + name: "Slim Jeans", + quantity: "1", + basePriceMoney: { + amount: BigInt("2500"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("2500"), + currency: "USD", + }, + }, + { + name: "Woven Sweater", + quantity: "3", + basePriceMoney: { + amount: BigInt("3500"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("10500"), + currency: "USD", + }, + }, + ], + taxes: [ + { + uid: "38ze1696-z1e3-5628-af6d-f1e04d947fg3", + type: "INCLUSIVE", + percentage: "7.75", + scope: "LINE_ITEM", + }, + ], + discounts: [ + { + uid: "56ae1696-z1e3-9328-af6d-f1e04d947gd4", + type: "FIXED_AMOUNT", + amountMoney: { + amount: BigInt("100"), + currency: "USD", + }, + appliedMoney: { + amount: BigInt("100"), + currency: "USD", + }, + scope: "LINE_ITEM", + }, + ], + serviceCharges: [{}], + fulfillments: [{}], + returns: [{}], + tenders: [ + { + type: "CARD", + }, + ], + refunds: [ + { + id: "id", + locationId: "location_id", + reason: "reason", + amountMoney: {}, + status: "PENDING", + }, + ], + createdAt: "created_at", + updatedAt: "updated_at", + closedAt: "closed_at", + state: "OPEN", + version: 1, + totalMoney: { + amount: BigInt("14503"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("103"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("100"), + currency: "USD", + }, + ticketName: "ticket_name", + rewards: [ + { + id: "id", + rewardTierId: "reward_tier_id", + }, + ], + }, + createdAt: "2017-06-16T22:25:35Z", + additionalRecipients: [ + { + locationId: "057P5VYJ4A5X1", + description: "Application fees", + amountMoney: { + amount: BigInt("60"), + currency: "USD", + }, + }, + ], + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/locations/customAttributeDefinitions.test.ts b/tests/wire/locations/customAttributeDefinitions.test.ts new file mode 100644 index 000000000..4f3852332 --- /dev/null +++ b/tests/wire/locations/customAttributeDefinitions.test.ts @@ -0,0 +1,229 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("CustomAttributeDefinitions", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + custom_attribute_definition: { + key: "bestseller", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Bestseller", + description: "Bestselling item at location", + visibility: "VISIBILITY_READ_WRITE_VALUES", + }, + }; + const rawResponseBody = { + custom_attribute_definition: { + key: "bestseller", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Bestseller", + description: "Bestselling item at location", + visibility: "VISIBILITY_READ_WRITE_VALUES", + version: 1, + updated_at: "2022-12-02T19:06:36.559Z", + created_at: "2022-12-02T19:06:36.559Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/locations/custom-attribute-definitions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.locations.customAttributeDefinitions.create({ + customAttributeDefinition: { + key: "bestseller", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Bestseller", + description: "Bestselling item at location", + visibility: "VISIBILITY_READ_WRITE_VALUES", + }, + }); + expect(response).toEqual({ + customAttributeDefinition: { + key: "bestseller", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Bestseller", + description: "Bestselling item at location", + visibility: "VISIBILITY_READ_WRITE_VALUES", + version: 1, + updatedAt: "2022-12-02T19:06:36.559Z", + createdAt: "2022-12-02T19:06:36.559Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + custom_attribute_definition: { + key: "bestseller", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Bestseller", + description: "Bestselling item at location", + visibility: "VISIBILITY_READ_WRITE_VALUES", + version: 1, + updated_at: "2022-12-02T19:06:36.559Z", + created_at: "2022-12-02T19:06:36.559Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/locations/custom-attribute-definitions/key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.locations.customAttributeDefinitions.get({ + key: "key", + }); + expect(response).toEqual({ + customAttributeDefinition: { + key: "bestseller", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Bestseller", + description: "Bestselling item at location", + visibility: "VISIBILITY_READ_WRITE_VALUES", + version: 1, + updatedAt: "2022-12-02T19:06:36.559Z", + createdAt: "2022-12-02T19:06:36.559Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + custom_attribute_definition: { + description: "Update the description as desired.", + visibility: "VISIBILITY_READ_ONLY", + }, + }; + const rawResponseBody = { + custom_attribute_definition: { + key: "bestseller", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Bestseller", + description: "Update the description as desired.", + visibility: "VISIBILITY_READ_ONLY", + version: 2, + updated_at: "2022-12-02T19:34:10.181Z", + created_at: "2022-12-02T19:06:36.559Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .put("/v2/locations/custom-attribute-definitions/key") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.locations.customAttributeDefinitions.update({ + key: "key", + customAttributeDefinition: { + description: "Update the description as desired.", + visibility: "VISIBILITY_READ_ONLY", + }, + }); + expect(response).toEqual({ + customAttributeDefinition: { + key: "bestseller", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Bestseller", + description: "Update the description as desired.", + visibility: "VISIBILITY_READ_ONLY", + version: 2, + updatedAt: "2022-12-02T19:34:10.181Z", + createdAt: "2022-12-02T19:06:36.559Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/locations/custom-attribute-definitions/key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.locations.customAttributeDefinitions.delete({ + key: "key", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/locations/customAttributes.test.ts b/tests/wire/locations/customAttributes.test.ts new file mode 100644 index 000000000..af23bcc83 --- /dev/null +++ b/tests/wire/locations/customAttributes.test.ts @@ -0,0 +1,417 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("CustomAttributes", () => { + test("batchDelete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + values: { id1: { key: "bestseller" }, id2: { key: "bestseller" }, id3: { key: "phone-number" } }, + }; + const rawResponseBody = { + values: { + id1: { + location_id: "L0TBCBTB7P8RQ", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + id2: { + location_id: "L9XMD04V3STJX", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + id3: { + location_id: "L0TBCBTB7P8RQ", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/locations/custom-attributes/bulk-delete") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.locations.customAttributes.batchDelete({ + values: { + id1: { + key: "bestseller", + }, + id2: { + key: "bestseller", + }, + id3: { + key: "phone-number", + }, + }, + }); + expect(response).toEqual({ + values: { + id1: { + locationId: "L0TBCBTB7P8RQ", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + id2: { + locationId: "L9XMD04V3STJX", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + id3: { + locationId: "L0TBCBTB7P8RQ", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("batchUpsert", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + values: { + id1: { location_id: "L0TBCBTB7P8RQ", custom_attribute: { key: "bestseller", value: "hot cocoa" } }, + id2: { location_id: "L9XMD04V3STJX", custom_attribute: { key: "bestseller", value: "berry smoothie" } }, + id3: { location_id: "L0TBCBTB7P8RQ", custom_attribute: { key: "phone-number", value: "+12223334444" } }, + }, + }; + const rawResponseBody = { + values: { + id1: { + location_id: "L0TBCBTB7P8RQ", + custom_attribute: { + key: "bestseller", + value: "hot cocoa", + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updated_at: "2023-01-09T19:21:04.551Z", + created_at: "2023-01-09T19:02:58.647Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + id2: { + location_id: "L9XMD04V3STJX", + custom_attribute: { + key: "bestseller", + value: "berry smoothie", + version: 1, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updated_at: "2023-01-09T19:21:04.551Z", + created_at: "2023-01-09T19:02:58.647Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + id3: { + location_id: "L0TBCBTB7P8RQ", + custom_attribute: { + key: "phone-number", + value: "+12239903892", + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updated_at: "2023-01-09T19:21:04.563Z", + created_at: "2023-01-09T19:04:57.985Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/locations/custom-attributes/bulk-upsert") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.locations.customAttributes.batchUpsert({ + values: { + id1: { + locationId: "L0TBCBTB7P8RQ", + customAttribute: { + key: "bestseller", + value: "hot cocoa", + }, + }, + id2: { + locationId: "L9XMD04V3STJX", + customAttribute: { + key: "bestseller", + value: "berry smoothie", + }, + }, + id3: { + locationId: "L0TBCBTB7P8RQ", + customAttribute: { + key: "phone-number", + value: "+12223334444", + }, + }, + }, + }); + expect(response).toEqual({ + values: { + id1: { + locationId: "L0TBCBTB7P8RQ", + customAttribute: { + key: "bestseller", + value: "hot cocoa", + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updatedAt: "2023-01-09T19:21:04.551Z", + createdAt: "2023-01-09T19:02:58.647Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + id2: { + locationId: "L9XMD04V3STJX", + customAttribute: { + key: "bestseller", + value: "berry smoothie", + version: 1, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updatedAt: "2023-01-09T19:21:04.551Z", + createdAt: "2023-01-09T19:02:58.647Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + id3: { + locationId: "L0TBCBTB7P8RQ", + customAttribute: { + key: "phone-number", + value: "+12239903892", + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updatedAt: "2023-01-09T19:21:04.563Z", + createdAt: "2023-01-09T19:04:57.985Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + custom_attribute: { + key: "bestseller", + value: "hot cocoa", + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + definition: { + key: "key", + schema: { key: "value" }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updated_at: "updated_at", + created_at: "created_at", + }, + updated_at: "2023-01-09T19:21:04.551Z", + created_at: "2023-01-09T19:02:58.647Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/locations/location_id/custom-attributes/key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.locations.customAttributes.get({ + locationId: "location_id", + key: "key", + }); + expect(response).toEqual({ + customAttribute: { + key: "bestseller", + value: "hot cocoa", + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + definition: { + key: "key", + schema: { + key: "value", + }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updatedAt: "updated_at", + createdAt: "created_at", + }, + updatedAt: "2023-01-09T19:21:04.551Z", + createdAt: "2023-01-09T19:02:58.647Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("upsert", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { custom_attribute: { value: "hot cocoa" } }; + const rawResponseBody = { + custom_attribute: { + key: "bestseller", + value: "hot cocoa", + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + definition: { + key: "key", + schema: { key: "value" }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updated_at: "updated_at", + created_at: "created_at", + }, + updated_at: "2023-01-09T19:21:04.551Z", + created_at: "2023-01-09T19:02:58.647Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/locations/location_id/custom-attributes/key") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.locations.customAttributes.upsert({ + locationId: "location_id", + key: "key", + customAttribute: { + value: "hot cocoa", + }, + }); + expect(response).toEqual({ + customAttribute: { + key: "bestseller", + value: "hot cocoa", + version: 2, + visibility: "VISIBILITY_READ_WRITE_VALUES", + definition: { + key: "key", + schema: { + key: "value", + }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updatedAt: "updated_at", + createdAt: "created_at", + }, + updatedAt: "2023-01-09T19:21:04.551Z", + createdAt: "2023-01-09T19:02:58.647Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/locations/location_id/custom-attributes/key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.locations.customAttributes.delete({ + locationId: "location_id", + key: "key", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/locations/transactions.test.ts b/tests/wire/locations/transactions.test.ts new file mode 100644 index 000000000..13055153c --- /dev/null +++ b/tests/wire/locations/transactions.test.ts @@ -0,0 +1,386 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("Transactions", () => { + test("list", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + transactions: [ + { + id: "KnL67ZIwXCPtzOrqj0HrkxMF", + location_id: "18YC4JDH91E1H", + created_at: "2016-01-20T22:57:56Z", + tenders: [ + { + id: "MtZRYYdDrYNQbOvV7nbuBvMF", + location_id: "18YC4JDH91E1H", + transaction_id: "KnL67ZIwXCPtzOrqj0HrkxMF", + created_at: "2016-01-20T22:57:56Z", + note: "some optional note", + amount_money: { amount: BigInt(5000), currency: "USD" }, + processing_fee_money: { amount: BigInt(138), currency: "USD" }, + type: "CARD", + card_details: { + status: "CAPTURED", + card: { card_brand: "VISA", last_4: "1111" }, + entry_method: "KEYED", + }, + additional_recipients: [ + { + location_id: "057P5VYJ4A5X1", + description: "Application fees", + amount_money: { amount: BigInt(20), currency: "USD" }, + }, + ], + }, + ], + refunds: [ + { + id: "7a5RcVI0CxbOcJ2wMOkE", + location_id: "18YC4JDH91E1H", + transaction_id: "KnL67ZIwXCPtzOrqj0HrkxMF", + tender_id: "MtZRYYdDrYNQbOvV7nbuBvMF", + created_at: "2016-01-20T22:59:20Z", + reason: "some reason why", + amount_money: { amount: BigInt(5000), currency: "USD" }, + status: "APPROVED", + processing_fee_money: { amount: BigInt(138), currency: "USD" }, + additional_recipients: [ + { + location_id: "057P5VYJ4A5X1", + description: "Application fees", + amount_money: { amount: BigInt(100), currency: "USD" }, + }, + ], + }, + ], + reference_id: "some optional reference id", + product: "EXTERNAL_API", + client_id: "client_id", + order_id: "order_id", + }, + ], + cursor: "cursor", + }; + server + .mockEndpoint() + .get("/v2/locations/location_id/transactions") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.locations.transactions.list({ + locationId: "location_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + transactions: [ + { + id: "KnL67ZIwXCPtzOrqj0HrkxMF", + locationId: "18YC4JDH91E1H", + createdAt: "2016-01-20T22:57:56Z", + tenders: [ + { + id: "MtZRYYdDrYNQbOvV7nbuBvMF", + locationId: "18YC4JDH91E1H", + transactionId: "KnL67ZIwXCPtzOrqj0HrkxMF", + createdAt: "2016-01-20T22:57:56Z", + note: "some optional note", + amountMoney: { + amount: BigInt("5000"), + currency: "USD", + }, + processingFeeMoney: { + amount: BigInt("138"), + currency: "USD", + }, + type: "CARD", + cardDetails: { + status: "CAPTURED", + card: { + cardBrand: "VISA", + last4: "1111", + }, + entryMethod: "KEYED", + }, + additionalRecipients: [ + { + locationId: "057P5VYJ4A5X1", + description: "Application fees", + amountMoney: { + amount: BigInt("20"), + currency: "USD", + }, + }, + ], + }, + ], + refunds: [ + { + id: "7a5RcVI0CxbOcJ2wMOkE", + locationId: "18YC4JDH91E1H", + transactionId: "KnL67ZIwXCPtzOrqj0HrkxMF", + tenderId: "MtZRYYdDrYNQbOvV7nbuBvMF", + createdAt: "2016-01-20T22:59:20Z", + reason: "some reason why", + amountMoney: { + amount: BigInt("5000"), + currency: "USD", + }, + status: "APPROVED", + processingFeeMoney: { + amount: BigInt("138"), + currency: "USD", + }, + additionalRecipients: [ + { + locationId: "057P5VYJ4A5X1", + description: "Application fees", + amountMoney: { + amount: BigInt("100"), + currency: "USD", + }, + }, + ], + }, + ], + referenceId: "some optional reference id", + product: "EXTERNAL_API", + clientId: "client_id", + orderId: "order_id", + }, + ], + cursor: "cursor", + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + transaction: { + id: "KnL67ZIwXCPtzOrqj0HrkxMF", + location_id: "18YC4JDH91E1H", + created_at: "2016-03-10T22:57:56Z", + tenders: [ + { + id: "MtZRYYdDrYNQbOvV7nbuBvMF", + location_id: "18YC4JDH91E1H", + transaction_id: "KnL67ZIwXCPtzOrqj0HrkxMF", + created_at: "2016-03-10T22:57:56Z", + note: "some optional note", + amount_money: { amount: BigInt(5000), currency: "USD" }, + processing_fee_money: { amount: BigInt(138), currency: "USD" }, + type: "CARD", + card_details: { + status: "CAPTURED", + card: { card_brand: "VISA", last_4: "1111" }, + entry_method: "KEYED", + }, + additional_recipients: [ + { + location_id: "057P5VYJ4A5X1", + description: "Application fees", + amount_money: { amount: BigInt(20), currency: "USD" }, + }, + ], + }, + ], + refunds: [ + { id: "id", location_id: "location_id", reason: "reason", amount_money: {}, status: "PENDING" }, + ], + reference_id: "some optional reference id", + product: "EXTERNAL_API", + client_id: "client_id", + shipping_address: { + address_line_1: "address_line_1", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "administrative_district_level_1", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "postal_code", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + order_id: "order_id", + }, + }; + server + .mockEndpoint() + .get("/v2/locations/location_id/transactions/transaction_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.locations.transactions.get({ + locationId: "location_id", + transactionId: "transaction_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + transaction: { + id: "KnL67ZIwXCPtzOrqj0HrkxMF", + locationId: "18YC4JDH91E1H", + createdAt: "2016-03-10T22:57:56Z", + tenders: [ + { + id: "MtZRYYdDrYNQbOvV7nbuBvMF", + locationId: "18YC4JDH91E1H", + transactionId: "KnL67ZIwXCPtzOrqj0HrkxMF", + createdAt: "2016-03-10T22:57:56Z", + note: "some optional note", + amountMoney: { + amount: BigInt("5000"), + currency: "USD", + }, + processingFeeMoney: { + amount: BigInt("138"), + currency: "USD", + }, + type: "CARD", + cardDetails: { + status: "CAPTURED", + card: { + cardBrand: "VISA", + last4: "1111", + }, + entryMethod: "KEYED", + }, + additionalRecipients: [ + { + locationId: "057P5VYJ4A5X1", + description: "Application fees", + amountMoney: { + amount: BigInt("20"), + currency: "USD", + }, + }, + ], + }, + ], + refunds: [ + { + id: "id", + locationId: "location_id", + reason: "reason", + amountMoney: {}, + status: "PENDING", + }, + ], + referenceId: "some optional reference id", + product: "EXTERNAL_API", + clientId: "client_id", + shippingAddress: { + addressLine1: "address_line_1", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "administrative_district_level_1", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "postal_code", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + orderId: "order_id", + }, + }); + }); + + test("capture", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/locations/location_id/transactions/transaction_id/capture") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.locations.transactions.capture({ + locationId: "location_id", + transactionId: "transaction_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("void", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/locations/location_id/transactions/transaction_id/void") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.locations.transactions.void({ + locationId: "location_id", + transactionId: "transaction_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/loyalty.test.ts b/tests/wire/loyalty.test.ts new file mode 100644 index 000000000..95b8cbc48 --- /dev/null +++ b/tests/wire/loyalty.test.ts @@ -0,0 +1,169 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Loyalty", () => { + test("searchEvents", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + query: { filter: { order_filter: { order_id: "PyATxhYLfsMqpVkcKJITPydgEYfZY" } } }, + limit: 30, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + events: [ + { + id: "c27c8465-806e-36f2-b4b3-71f5887b5ba8", + type: "ACCUMULATE_POINTS", + created_at: "2020-05-08T22:01:30Z", + accumulate_points: { + loyalty_program_id: "d619f755-2d17-41f3-990d-c04ecedd64dd", + points: 5, + order_id: "PyATxhYLfsMqpVkcKJITPydgEYfZY", + }, + adjust_points: { points: 1 }, + loyalty_account_id: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + location_id: "P034NEENMD09F", + source: "LOYALTY_API", + expire_points: { points: 1 }, + other_event: { points: 1 }, + }, + { + id: "e4a5cbc3-a4d0-3779-98e9-e578885d9430", + type: "REDEEM_REWARD", + created_at: "2020-05-08T22:01:15Z", + redeem_reward: { + loyalty_program_id: "d619f755-2d17-41f3-990d-c04ecedd64dd", + reward_id: "d03f79f4-815f-3500-b851-cc1e68a457f9", + order_id: "PyATxhYLfsMqpVkcKJITPydgEYfZY", + }, + adjust_points: { points: 1 }, + loyalty_account_id: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + location_id: "P034NEENMD09F", + source: "LOYALTY_API", + expire_points: { points: 1 }, + other_event: { points: 1 }, + }, + { + id: "5e127479-0b03-3671-ab1e-15faea8b7188", + type: "CREATE_REWARD", + created_at: "2020-05-08T22:00:44Z", + create_reward: { + loyalty_program_id: "d619f755-2d17-41f3-990d-c04ecedd64dd", + reward_id: "d03f79f4-815f-3500-b851-cc1e68a457f9", + points: -10, + }, + adjust_points: { points: 1 }, + loyalty_account_id: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + location_id: "location_id", + source: "LOYALTY_API", + expire_points: { points: 1 }, + other_event: { points: 1 }, + }, + ], + cursor: "cursor", + }; + server + .mockEndpoint() + .post("/v2/loyalty/events/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.loyalty.searchEvents({ + query: { + filter: { + orderFilter: { + orderId: "PyATxhYLfsMqpVkcKJITPydgEYfZY", + }, + }, + }, + limit: 30, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + events: [ + { + id: "c27c8465-806e-36f2-b4b3-71f5887b5ba8", + type: "ACCUMULATE_POINTS", + createdAt: "2020-05-08T22:01:30Z", + accumulatePoints: { + loyaltyProgramId: "d619f755-2d17-41f3-990d-c04ecedd64dd", + points: 5, + orderId: "PyATxhYLfsMqpVkcKJITPydgEYfZY", + }, + adjustPoints: { + points: 1, + }, + loyaltyAccountId: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + locationId: "P034NEENMD09F", + source: "LOYALTY_API", + expirePoints: { + points: 1, + }, + otherEvent: { + points: 1, + }, + }, + { + id: "e4a5cbc3-a4d0-3779-98e9-e578885d9430", + type: "REDEEM_REWARD", + createdAt: "2020-05-08T22:01:15Z", + redeemReward: { + loyaltyProgramId: "d619f755-2d17-41f3-990d-c04ecedd64dd", + rewardId: "d03f79f4-815f-3500-b851-cc1e68a457f9", + orderId: "PyATxhYLfsMqpVkcKJITPydgEYfZY", + }, + adjustPoints: { + points: 1, + }, + loyaltyAccountId: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + locationId: "P034NEENMD09F", + source: "LOYALTY_API", + expirePoints: { + points: 1, + }, + otherEvent: { + points: 1, + }, + }, + { + id: "5e127479-0b03-3671-ab1e-15faea8b7188", + type: "CREATE_REWARD", + createdAt: "2020-05-08T22:00:44Z", + createReward: { + loyaltyProgramId: "d619f755-2d17-41f3-990d-c04ecedd64dd", + rewardId: "d03f79f4-815f-3500-b851-cc1e68a457f9", + points: -10, + }, + adjustPoints: { + points: 1, + }, + loyaltyAccountId: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + locationId: "location_id", + source: "LOYALTY_API", + expirePoints: { + points: 1, + }, + otherEvent: { + points: 1, + }, + }, + ], + cursor: "cursor", + }); + }); +}); diff --git a/tests/wire/loyalty/accounts.test.ts b/tests/wire/loyalty/accounts.test.ts new file mode 100644 index 000000000..ff92ebe22 --- /dev/null +++ b/tests/wire/loyalty/accounts.test.ts @@ -0,0 +1,505 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("Accounts", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + loyalty_account: { + program_id: "d619f755-2d17-41f3-990d-c04ecedd64dd", + mapping: { phone_number: "+14155551234" }, + }, + idempotency_key: "ec78c477-b1c3-4899-a209-a4e71337c996", + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + loyalty_account: { + id: "79b807d2-d786-46a9-933b-918028d7a8c5", + program_id: "d619f755-2d17-41f3-990d-c04ecedd64dd", + balance: 0, + lifetime_points: 0, + customer_id: "QPTXM8PQNX3Q726ZYHPMNP46XC", + enrolled_at: "enrolled_at", + created_at: "2020-05-08T21:44:32Z", + updated_at: "2020-05-08T21:44:32Z", + mapping: { + id: "66aaab3f-da99-49ed-8b19-b87f851c844f", + created_at: "2020-05-08T21:44:32Z", + phone_number: "+14155551234", + }, + expiring_point_deadlines: [{ points: 1, expires_at: "expires_at" }], + }, + }; + server + .mockEndpoint() + .post("/v2/loyalty/accounts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.loyalty.accounts.create({ + loyaltyAccount: { + programId: "d619f755-2d17-41f3-990d-c04ecedd64dd", + mapping: { + phoneNumber: "+14155551234", + }, + }, + idempotencyKey: "ec78c477-b1c3-4899-a209-a4e71337c996", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + loyaltyAccount: { + id: "79b807d2-d786-46a9-933b-918028d7a8c5", + programId: "d619f755-2d17-41f3-990d-c04ecedd64dd", + balance: 0, + lifetimePoints: 0, + customerId: "QPTXM8PQNX3Q726ZYHPMNP46XC", + enrolledAt: "enrolled_at", + createdAt: "2020-05-08T21:44:32Z", + updatedAt: "2020-05-08T21:44:32Z", + mapping: { + id: "66aaab3f-da99-49ed-8b19-b87f851c844f", + createdAt: "2020-05-08T21:44:32Z", + phoneNumber: "+14155551234", + }, + expiringPointDeadlines: [ + { + points: 1, + expiresAt: "expires_at", + }, + ], + }, + }); + }); + + test("search", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { query: { mappings: [{ phone_number: "+14155551234" }] }, limit: 10 }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + loyalty_accounts: [ + { + id: "79b807d2-d786-46a9-933b-918028d7a8c5", + program_id: "d619f755-2d17-41f3-990d-c04ecedd64dd", + balance: 10, + lifetime_points: 20, + customer_id: "Q8002FAM9V1EZ0ADB2T5609X6NET1H0", + enrolled_at: "enrolled_at", + created_at: "2020-05-08T21:44:32Z", + updated_at: "2020-05-08T21:44:32Z", + mapping: { + id: "66aaab3f-da99-49ed-8b19-b87f851c844f", + created_at: "2020-05-08T21:44:32Z", + phone_number: "+14155551234", + }, + expiring_point_deadlines: [{ points: 1, expires_at: "expires_at" }], + }, + ], + cursor: "cursor", + }; + server + .mockEndpoint() + .post("/v2/loyalty/accounts/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.loyalty.accounts.search({ + query: { + mappings: [ + { + phoneNumber: "+14155551234", + }, + ], + }, + limit: 10, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + loyaltyAccounts: [ + { + id: "79b807d2-d786-46a9-933b-918028d7a8c5", + programId: "d619f755-2d17-41f3-990d-c04ecedd64dd", + balance: 10, + lifetimePoints: 20, + customerId: "Q8002FAM9V1EZ0ADB2T5609X6NET1H0", + enrolledAt: "enrolled_at", + createdAt: "2020-05-08T21:44:32Z", + updatedAt: "2020-05-08T21:44:32Z", + mapping: { + id: "66aaab3f-da99-49ed-8b19-b87f851c844f", + createdAt: "2020-05-08T21:44:32Z", + phoneNumber: "+14155551234", + }, + expiringPointDeadlines: [ + { + points: 1, + expiresAt: "expires_at", + }, + ], + }, + ], + cursor: "cursor", + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + loyalty_account: { + id: "79b807d2-d786-46a9-933b-918028d7a8c5", + program_id: "d619f755-2d17-41f3-990d-c04ecedd64dd", + balance: 10, + lifetime_points: 20, + customer_id: "Q8002FAM9V1EZ0ADB2T5609X6NET1H0", + enrolled_at: "enrolled_at", + created_at: "2020-05-08T21:44:32Z", + updated_at: "2020-05-08T21:44:32Z", + mapping: { + id: "66aaab3f-da99-49ed-8b19-b87f851c844f", + created_at: "2020-05-08T21:44:32Z", + phone_number: "+14155551234", + }, + expiring_point_deadlines: [{ points: 1, expires_at: "expires_at" }], + }, + }; + server + .mockEndpoint() + .get("/v2/loyalty/accounts/account_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.loyalty.accounts.get({ + accountId: "account_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + loyaltyAccount: { + id: "79b807d2-d786-46a9-933b-918028d7a8c5", + programId: "d619f755-2d17-41f3-990d-c04ecedd64dd", + balance: 10, + lifetimePoints: 20, + customerId: "Q8002FAM9V1EZ0ADB2T5609X6NET1H0", + enrolledAt: "enrolled_at", + createdAt: "2020-05-08T21:44:32Z", + updatedAt: "2020-05-08T21:44:32Z", + mapping: { + id: "66aaab3f-da99-49ed-8b19-b87f851c844f", + createdAt: "2020-05-08T21:44:32Z", + phoneNumber: "+14155551234", + }, + expiringPointDeadlines: [ + { + points: 1, + expiresAt: "expires_at", + }, + ], + }, + }); + }); + + test("accumulatePoints", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + accumulate_points: { order_id: "RFZfrdtm3mhO1oGzf5Cx7fEMsmGZY" }, + idempotency_key: "58b90739-c3e8-4b11-85f7-e636d48d72cb", + location_id: "P034NEENMD09F", + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + event: { + id: "id", + type: "ACCUMULATE_POINTS", + created_at: "created_at", + accumulate_points: { loyalty_program_id: "loyalty_program_id", points: 1, order_id: "order_id" }, + create_reward: { loyalty_program_id: "loyalty_program_id", reward_id: "reward_id", points: 1 }, + redeem_reward: { + loyalty_program_id: "loyalty_program_id", + reward_id: "reward_id", + order_id: "order_id", + }, + delete_reward: { loyalty_program_id: "loyalty_program_id", reward_id: "reward_id", points: 1 }, + adjust_points: { loyalty_program_id: "loyalty_program_id", points: 1, reason: "reason" }, + loyalty_account_id: "loyalty_account_id", + location_id: "location_id", + source: "SQUARE", + expire_points: { loyalty_program_id: "loyalty_program_id", points: 1 }, + other_event: { loyalty_program_id: "loyalty_program_id", points: 1 }, + accumulate_promotion_points: { + loyalty_program_id: "loyalty_program_id", + loyalty_promotion_id: "loyalty_promotion_id", + points: 1, + order_id: "order_id", + }, + }, + events: [ + { + id: "ee46aafd-1af6-3695-a385-276e2ef0be26", + type: "ACCUMULATE_POINTS", + created_at: "2020-05-08T21:41:12Z", + accumulate_points: { + loyalty_program_id: "d619f755-2d17-41f3-990d-c04ecedd64dd", + points: 6, + order_id: "RFZfrdtm3mhO1oGzf5Cx7fEMsmGZY", + }, + adjust_points: { points: 1 }, + loyalty_account_id: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + location_id: "P034NEENMD09F", + source: "LOYALTY_API", + expire_points: { points: 1 }, + other_event: { points: 1 }, + }, + ], + }; + server + .mockEndpoint() + .post("/v2/loyalty/accounts/account_id/accumulate") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.loyalty.accounts.accumulatePoints({ + accountId: "account_id", + accumulatePoints: { + orderId: "RFZfrdtm3mhO1oGzf5Cx7fEMsmGZY", + }, + idempotencyKey: "58b90739-c3e8-4b11-85f7-e636d48d72cb", + locationId: "P034NEENMD09F", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + event: { + id: "id", + type: "ACCUMULATE_POINTS", + createdAt: "created_at", + accumulatePoints: { + loyaltyProgramId: "loyalty_program_id", + points: 1, + orderId: "order_id", + }, + createReward: { + loyaltyProgramId: "loyalty_program_id", + rewardId: "reward_id", + points: 1, + }, + redeemReward: { + loyaltyProgramId: "loyalty_program_id", + rewardId: "reward_id", + orderId: "order_id", + }, + deleteReward: { + loyaltyProgramId: "loyalty_program_id", + rewardId: "reward_id", + points: 1, + }, + adjustPoints: { + loyaltyProgramId: "loyalty_program_id", + points: 1, + reason: "reason", + }, + loyaltyAccountId: "loyalty_account_id", + locationId: "location_id", + source: "SQUARE", + expirePoints: { + loyaltyProgramId: "loyalty_program_id", + points: 1, + }, + otherEvent: { + loyaltyProgramId: "loyalty_program_id", + points: 1, + }, + accumulatePromotionPoints: { + loyaltyProgramId: "loyalty_program_id", + loyaltyPromotionId: "loyalty_promotion_id", + points: 1, + orderId: "order_id", + }, + }, + events: [ + { + id: "ee46aafd-1af6-3695-a385-276e2ef0be26", + type: "ACCUMULATE_POINTS", + createdAt: "2020-05-08T21:41:12Z", + accumulatePoints: { + loyaltyProgramId: "d619f755-2d17-41f3-990d-c04ecedd64dd", + points: 6, + orderId: "RFZfrdtm3mhO1oGzf5Cx7fEMsmGZY", + }, + adjustPoints: { + points: 1, + }, + loyaltyAccountId: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + locationId: "P034NEENMD09F", + source: "LOYALTY_API", + expirePoints: { + points: 1, + }, + otherEvent: { + points: 1, + }, + }, + ], + }); + }); + + test("adjust", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "bc29a517-3dc9-450e-aa76-fae39ee849d1", + adjust_points: { points: 10, reason: "Complimentary points" }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + event: { + id: "613a6fca-8d67-39d0-bad2-3b4bc45c8637", + type: "ADJUST_POINTS", + created_at: "2020-05-08T21:42:32Z", + accumulate_points: { loyalty_program_id: "loyalty_program_id", points: 1, order_id: "order_id" }, + create_reward: { loyalty_program_id: "loyalty_program_id", reward_id: "reward_id", points: 1 }, + redeem_reward: { + loyalty_program_id: "loyalty_program_id", + reward_id: "reward_id", + order_id: "order_id", + }, + delete_reward: { loyalty_program_id: "loyalty_program_id", reward_id: "reward_id", points: 1 }, + adjust_points: { + loyalty_program_id: "d619f755-2d17-41f3-990d-c04ecedd64dd", + points: 10, + reason: "Complimentary points", + }, + loyalty_account_id: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + location_id: "location_id", + source: "LOYALTY_API", + expire_points: { loyalty_program_id: "loyalty_program_id", points: 1 }, + other_event: { loyalty_program_id: "loyalty_program_id", points: 1 }, + accumulate_promotion_points: { + loyalty_program_id: "loyalty_program_id", + loyalty_promotion_id: "loyalty_promotion_id", + points: 1, + order_id: "order_id", + }, + }, + }; + server + .mockEndpoint() + .post("/v2/loyalty/accounts/account_id/adjust") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.loyalty.accounts.adjust({ + accountId: "account_id", + idempotencyKey: "bc29a517-3dc9-450e-aa76-fae39ee849d1", + adjustPoints: { + points: 10, + reason: "Complimentary points", + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + event: { + id: "613a6fca-8d67-39d0-bad2-3b4bc45c8637", + type: "ADJUST_POINTS", + createdAt: "2020-05-08T21:42:32Z", + accumulatePoints: { + loyaltyProgramId: "loyalty_program_id", + points: 1, + orderId: "order_id", + }, + createReward: { + loyaltyProgramId: "loyalty_program_id", + rewardId: "reward_id", + points: 1, + }, + redeemReward: { + loyaltyProgramId: "loyalty_program_id", + rewardId: "reward_id", + orderId: "order_id", + }, + deleteReward: { + loyaltyProgramId: "loyalty_program_id", + rewardId: "reward_id", + points: 1, + }, + adjustPoints: { + loyaltyProgramId: "d619f755-2d17-41f3-990d-c04ecedd64dd", + points: 10, + reason: "Complimentary points", + }, + loyaltyAccountId: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + locationId: "location_id", + source: "LOYALTY_API", + expirePoints: { + loyaltyProgramId: "loyalty_program_id", + points: 1, + }, + otherEvent: { + loyaltyProgramId: "loyalty_program_id", + points: 1, + }, + accumulatePromotionPoints: { + loyaltyProgramId: "loyalty_program_id", + loyaltyPromotionId: "loyalty_promotion_id", + points: 1, + orderId: "order_id", + }, + }, + }); + }); +}); diff --git a/tests/wire/loyalty/programs.test.ts b/tests/wire/loyalty/programs.test.ts new file mode 100644 index 000000000..dbe16eb4d --- /dev/null +++ b/tests/wire/loyalty/programs.test.ts @@ -0,0 +1,258 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("Programs", () => { + test("list", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + programs: [ + { + id: "d619f755-2d17-41f3-990d-c04ecedd64dd", + status: "ACTIVE", + reward_tiers: [ + { + id: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", + points: 10, + name: "10% off entire sale", + created_at: "2020-04-20T16:55:11Z", + pricing_rule_reference: { + object_id: "74C4JSHESNLTB2A7ITO5HO6F", + catalog_version: BigInt(1000000), + }, + }, + ], + expiration_policy: { expiration_duration: "expiration_duration" }, + terminology: { one: "Point", other: "Points" }, + location_ids: ["P034NEENMD09F"], + created_at: "2020-04-20T16:55:11Z", + updated_at: "2020-05-01T02:00:02Z", + accrual_rules: [ + { + accrual_type: "SPEND", + points: 1, + spend_data: { + amount_money: { amount: BigInt(100), currency: "USD" }, + excluded_category_ids: ["7ZERJKO5PVYXCVUHV2JCZ2UG", "FQKAOJE5C4FIMF5A2URMLW6V"], + excluded_item_variation_ids: ["CBZXBUVVTYUBZGQO44RHMR6B", "EDILT24Z2NISEXDKGY6HP7XV"], + tax_mode: "BEFORE_TAX", + }, + }, + ], + }, + ], + }; + server + .mockEndpoint() + .get("/v2/loyalty/programs") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.loyalty.programs.list(); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + programs: [ + { + id: "d619f755-2d17-41f3-990d-c04ecedd64dd", + status: "ACTIVE", + rewardTiers: [ + { + id: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", + points: 10, + name: "10% off entire sale", + createdAt: "2020-04-20T16:55:11Z", + pricingRuleReference: { + objectId: "74C4JSHESNLTB2A7ITO5HO6F", + catalogVersion: BigInt("1000000"), + }, + }, + ], + expirationPolicy: { + expirationDuration: "expiration_duration", + }, + terminology: { + one: "Point", + other: "Points", + }, + locationIds: ["P034NEENMD09F"], + createdAt: "2020-04-20T16:55:11Z", + updatedAt: "2020-05-01T02:00:02Z", + accrualRules: [ + { + accrualType: "SPEND", + points: 1, + spendData: { + amountMoney: { + amount: BigInt("100"), + currency: "USD", + }, + excludedCategoryIds: ["7ZERJKO5PVYXCVUHV2JCZ2UG", "FQKAOJE5C4FIMF5A2URMLW6V"], + excludedItemVariationIds: ["CBZXBUVVTYUBZGQO44RHMR6B", "EDILT24Z2NISEXDKGY6HP7XV"], + taxMode: "BEFORE_TAX", + }, + }, + ], + }, + ], + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + program: { + id: "d619f755-2d17-41f3-990d-c04ecedd64dd", + status: "ACTIVE", + reward_tiers: [ + { + id: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", + points: 10, + name: "10% off entire sale", + created_at: "2020-04-20T16:55:11Z", + pricing_rule_reference: { + object_id: "74C4JSHESNLTB2A7ITO5HO6F", + catalog_version: BigInt(1000000), + }, + }, + ], + expiration_policy: { expiration_duration: "expiration_duration" }, + terminology: { one: "Point", other: "Points" }, + location_ids: ["P034NEENMD09F"], + created_at: "2020-04-20T16:55:11Z", + updated_at: "2020-05-01T02:00:02Z", + accrual_rules: [ + { + accrual_type: "SPEND", + points: 1, + spend_data: { + amount_money: { amount: BigInt(100), currency: "USD" }, + excluded_category_ids: ["7ZERJKO5PVYXCVUHV2JCZ2UG", "FQKAOJE5C4FIMF5A2URMLW6V"], + excluded_item_variation_ids: ["CBZXBUVVTYUBZGQO44RHMR6B", "EDILT24Z2NISEXDKGY6HP7XV"], + tax_mode: "BEFORE_TAX", + }, + }, + ], + }, + }; + server + .mockEndpoint() + .get("/v2/loyalty/programs/program_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.loyalty.programs.get({ + programId: "program_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + program: { + id: "d619f755-2d17-41f3-990d-c04ecedd64dd", + status: "ACTIVE", + rewardTiers: [ + { + id: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", + points: 10, + name: "10% off entire sale", + createdAt: "2020-04-20T16:55:11Z", + pricingRuleReference: { + objectId: "74C4JSHESNLTB2A7ITO5HO6F", + catalogVersion: BigInt("1000000"), + }, + }, + ], + expirationPolicy: { + expirationDuration: "expiration_duration", + }, + terminology: { + one: "Point", + other: "Points", + }, + locationIds: ["P034NEENMD09F"], + createdAt: "2020-04-20T16:55:11Z", + updatedAt: "2020-05-01T02:00:02Z", + accrualRules: [ + { + accrualType: "SPEND", + points: 1, + spendData: { + amountMoney: { + amount: BigInt("100"), + currency: "USD", + }, + excludedCategoryIds: ["7ZERJKO5PVYXCVUHV2JCZ2UG", "FQKAOJE5C4FIMF5A2URMLW6V"], + excludedItemVariationIds: ["CBZXBUVVTYUBZGQO44RHMR6B", "EDILT24Z2NISEXDKGY6HP7XV"], + taxMode: "BEFORE_TAX", + }, + }, + ], + }, + }); + }); + + test("calculate", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + order_id: "RFZfrdtm3mhO1oGzf5Cx7fEMsmGZY", + loyalty_account_id: "79b807d2-d786-46a9-933b-918028d7a8c5", + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + points: 6, + promotion_points: 12, + }; + server + .mockEndpoint() + .post("/v2/loyalty/programs/program_id/calculate") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.loyalty.programs.calculate({ + programId: "program_id", + orderId: "RFZfrdtm3mhO1oGzf5Cx7fEMsmGZY", + loyaltyAccountId: "79b807d2-d786-46a9-933b-918028d7a8c5", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + points: 6, + promotionPoints: 12, + }); + }); +}); diff --git a/tests/wire/loyalty/programs/promotions.test.ts b/tests/wire/loyalty/programs/promotions.test.ts new file mode 100644 index 000000000..7739e6ed6 --- /dev/null +++ b/tests/wire/loyalty/programs/promotions.test.ts @@ -0,0 +1,322 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../../mock-server/MockServerPool"; +import { SquareClient } from "../../../../src/Client"; + +describe("Promotions", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + loyalty_promotion: { + name: "Tuesday Happy Hour Promo", + incentive: { type: "POINTS_MULTIPLIER", points_multiplier_data: { multiplier: "3.0" } }, + available_time: { + time_periods: [ + "BEGIN:VEVENT\nDTSTART:20220816T160000\nDURATION:PT2H\nRRULE:FREQ=WEEKLY;BYDAY=TU\nEND:VEVENT", + ], + }, + trigger_limit: { times: 1, interval: "DAY" }, + minimum_spend_amount_money: { amount: BigInt(2000), currency: "USD" }, + qualifying_category_ids: ["XTQPYLR3IIU9C44VRCB3XD12"], + }, + idempotency_key: "ec78c477-b1c3-4899-a209-a4e71337c996", + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + loyalty_promotion: { + id: "loypromo_f0f9b849-725e-378d-b810-511237e07b67", + name: "Tuesday Happy Hour Promo", + incentive: { + type: "POINTS_MULTIPLIER", + points_multiplier_data: { points_multiplier: 3, multiplier: "3.000" }, + points_addition_data: { points_addition: 1 }, + }, + available_time: { + start_date: "2022-08-16", + end_date: "end_date", + time_periods: [ + "BEGIN:VEVENT\nDTSTART:20220816T160000\nDURATION:PT2H\nRRULE:FREQ=WEEKLY;BYDAY=TU\nEND:VEVENT", + ], + }, + trigger_limit: { times: 1, interval: "DAY" }, + status: "ACTIVE", + created_at: "2022-08-16T08:38:54Z", + canceled_at: "canceled_at", + updated_at: "2022-08-16T08:38:54Z", + loyalty_program_id: "d619f755-2d17-41f3-990d-c04ecedd64dd", + minimum_spend_amount_money: { amount: BigInt(2000), currency: "USD" }, + qualifying_item_variation_ids: ["qualifying_item_variation_ids"], + qualifying_category_ids: ["XTQPYLR3IIU9C44VRCB3XD12"], + }, + }; + server + .mockEndpoint() + .post("/v2/loyalty/programs/program_id/promotions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.loyalty.programs.promotions.create({ + programId: "program_id", + loyaltyPromotion: { + name: "Tuesday Happy Hour Promo", + incentive: { + type: "POINTS_MULTIPLIER", + pointsMultiplierData: { + multiplier: "3.0", + }, + }, + availableTime: { + timePeriods: [ + "BEGIN:VEVENT\nDTSTART:20220816T160000\nDURATION:PT2H\nRRULE:FREQ=WEEKLY;BYDAY=TU\nEND:VEVENT", + ], + }, + triggerLimit: { + times: 1, + interval: "DAY", + }, + minimumSpendAmountMoney: { + amount: BigInt("2000"), + currency: "USD", + }, + qualifyingCategoryIds: ["XTQPYLR3IIU9C44VRCB3XD12"], + }, + idempotencyKey: "ec78c477-b1c3-4899-a209-a4e71337c996", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + loyaltyPromotion: { + id: "loypromo_f0f9b849-725e-378d-b810-511237e07b67", + name: "Tuesday Happy Hour Promo", + incentive: { + type: "POINTS_MULTIPLIER", + pointsMultiplierData: { + pointsMultiplier: 3, + multiplier: "3.000", + }, + pointsAdditionData: { + pointsAddition: 1, + }, + }, + availableTime: { + startDate: "2022-08-16", + endDate: "end_date", + timePeriods: [ + "BEGIN:VEVENT\nDTSTART:20220816T160000\nDURATION:PT2H\nRRULE:FREQ=WEEKLY;BYDAY=TU\nEND:VEVENT", + ], + }, + triggerLimit: { + times: 1, + interval: "DAY", + }, + status: "ACTIVE", + createdAt: "2022-08-16T08:38:54Z", + canceledAt: "canceled_at", + updatedAt: "2022-08-16T08:38:54Z", + loyaltyProgramId: "d619f755-2d17-41f3-990d-c04ecedd64dd", + minimumSpendAmountMoney: { + amount: BigInt("2000"), + currency: "USD", + }, + qualifyingItemVariationIds: ["qualifying_item_variation_ids"], + qualifyingCategoryIds: ["XTQPYLR3IIU9C44VRCB3XD12"], + }, + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + loyalty_promotion: { + id: "loypromo_f0f9b849-725e-378d-b810-511237e07b67", + name: "Tuesday Happy Hour Promo", + incentive: { + type: "POINTS_MULTIPLIER", + points_multiplier_data: { points_multiplier: 3, multiplier: "3.000" }, + points_addition_data: { points_addition: 1 }, + }, + available_time: { + start_date: "2022-08-16", + end_date: "end_date", + time_periods: [ + "BEGIN:VEVENT\nDTSTART:20220816T160000\nDURATION:PT2H\nRRULE:FREQ=WEEKLY;BYDAY=TU\nEND:VEVENT", + ], + }, + trigger_limit: { times: 1, interval: "DAY" }, + status: "ACTIVE", + created_at: "2022-08-16T08:38:54Z", + canceled_at: "canceled_at", + updated_at: "2022-08-16T08:38:54Z", + loyalty_program_id: "d619f755-2d17-41f3-990d-c04ecedd64dd", + minimum_spend_amount_money: { amount: BigInt(2000), currency: "USD" }, + qualifying_item_variation_ids: ["CJ3RYL56ITAKMD4VRCM7XERS", "AT3RYLR3TUA9C34VRCB7X5RR"], + qualifying_category_ids: ["qualifying_category_ids"], + }, + }; + server + .mockEndpoint() + .get("/v2/loyalty/programs/program_id/promotions/promotion_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.loyalty.programs.promotions.get({ + promotionId: "promotion_id", + programId: "program_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + loyaltyPromotion: { + id: "loypromo_f0f9b849-725e-378d-b810-511237e07b67", + name: "Tuesday Happy Hour Promo", + incentive: { + type: "POINTS_MULTIPLIER", + pointsMultiplierData: { + pointsMultiplier: 3, + multiplier: "3.000", + }, + pointsAdditionData: { + pointsAddition: 1, + }, + }, + availableTime: { + startDate: "2022-08-16", + endDate: "end_date", + timePeriods: [ + "BEGIN:VEVENT\nDTSTART:20220816T160000\nDURATION:PT2H\nRRULE:FREQ=WEEKLY;BYDAY=TU\nEND:VEVENT", + ], + }, + triggerLimit: { + times: 1, + interval: "DAY", + }, + status: "ACTIVE", + createdAt: "2022-08-16T08:38:54Z", + canceledAt: "canceled_at", + updatedAt: "2022-08-16T08:38:54Z", + loyaltyProgramId: "d619f755-2d17-41f3-990d-c04ecedd64dd", + minimumSpendAmountMoney: { + amount: BigInt("2000"), + currency: "USD", + }, + qualifyingItemVariationIds: ["CJ3RYL56ITAKMD4VRCM7XERS", "AT3RYLR3TUA9C34VRCB7X5RR"], + qualifyingCategoryIds: ["qualifying_category_ids"], + }, + }); + }); + + test("cancel", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + loyalty_promotion: { + id: "loypromo_f0f9b849-725e-378d-b810-511237e07b67", + name: "Tuesday Happy Hour Promo", + incentive: { + type: "POINTS_MULTIPLIER", + points_multiplier_data: { points_multiplier: 3, multiplier: "3.000" }, + points_addition_data: { points_addition: 1 }, + }, + available_time: { + start_date: "2022-08-16", + end_date: "end_date", + time_periods: [ + "BEGIN:VEVENT\nDTSTART:20220816T160000\nDURATION:PT2H\nRRULE:FREQ=WEEKLY;BYDAY=TU\nEND:VEVENT", + ], + }, + trigger_limit: { times: 1, interval: "DAY" }, + status: "CANCELED", + created_at: "2022-08-16T08:38:54Z", + canceled_at: "2022-08-17T12:42:49Z", + updated_at: "2022-08-17T12:42:49Z", + loyalty_program_id: "d619f755-2d17-41f3-990d-c04ecedd64dd", + minimum_spend_amount_money: { amount: BigInt(2000), currency: "USD" }, + qualifying_item_variation_ids: ["qualifying_item_variation_ids"], + qualifying_category_ids: ["XTQPYLR3IIU9C44VRCB3XD12"], + }, + }; + server + .mockEndpoint() + .post("/v2/loyalty/programs/program_id/promotions/promotion_id/cancel") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.loyalty.programs.promotions.cancel({ + promotionId: "promotion_id", + programId: "program_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + loyaltyPromotion: { + id: "loypromo_f0f9b849-725e-378d-b810-511237e07b67", + name: "Tuesday Happy Hour Promo", + incentive: { + type: "POINTS_MULTIPLIER", + pointsMultiplierData: { + pointsMultiplier: 3, + multiplier: "3.000", + }, + pointsAdditionData: { + pointsAddition: 1, + }, + }, + availableTime: { + startDate: "2022-08-16", + endDate: "end_date", + timePeriods: [ + "BEGIN:VEVENT\nDTSTART:20220816T160000\nDURATION:PT2H\nRRULE:FREQ=WEEKLY;BYDAY=TU\nEND:VEVENT", + ], + }, + triggerLimit: { + times: 1, + interval: "DAY", + }, + status: "CANCELED", + createdAt: "2022-08-16T08:38:54Z", + canceledAt: "2022-08-17T12:42:49Z", + updatedAt: "2022-08-17T12:42:49Z", + loyaltyProgramId: "d619f755-2d17-41f3-990d-c04ecedd64dd", + minimumSpendAmountMoney: { + amount: BigInt("2000"), + currency: "USD", + }, + qualifyingItemVariationIds: ["qualifying_item_variation_ids"], + qualifyingCategoryIds: ["XTQPYLR3IIU9C44VRCB3XD12"], + }, + }); + }); +}); diff --git a/tests/wire/loyalty/rewards.test.ts b/tests/wire/loyalty/rewards.test.ts new file mode 100644 index 000000000..b67d8c73b --- /dev/null +++ b/tests/wire/loyalty/rewards.test.ts @@ -0,0 +1,391 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("Rewards", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + reward: { + loyalty_account_id: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + reward_tier_id: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", + order_id: "RFZfrdtm3mhO1oGzf5Cx7fEMsmGZY", + }, + idempotency_key: "18c2e5ea-a620-4b1f-ad60-7b167285e451", + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + reward: { + id: "a8f43ebe-2ad6-3001-bdd5-7d7c2da08943", + status: "ISSUED", + loyalty_account_id: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + reward_tier_id: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", + points: 10, + order_id: "RFZfrdtm3mhO1oGzf5Cx7fEMsmGZY", + created_at: "2020-05-01T21:49:54Z", + updated_at: "2020-05-01T21:49:54Z", + redeemed_at: "redeemed_at", + }, + }; + server + .mockEndpoint() + .post("/v2/loyalty/rewards") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.loyalty.rewards.create({ + reward: { + loyaltyAccountId: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + rewardTierId: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", + orderId: "RFZfrdtm3mhO1oGzf5Cx7fEMsmGZY", + }, + idempotencyKey: "18c2e5ea-a620-4b1f-ad60-7b167285e451", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + reward: { + id: "a8f43ebe-2ad6-3001-bdd5-7d7c2da08943", + status: "ISSUED", + loyaltyAccountId: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + rewardTierId: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", + points: 10, + orderId: "RFZfrdtm3mhO1oGzf5Cx7fEMsmGZY", + createdAt: "2020-05-01T21:49:54Z", + updatedAt: "2020-05-01T21:49:54Z", + redeemedAt: "redeemed_at", + }, + }); + }); + + test("search", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { query: { loyalty_account_id: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd" }, limit: 10 }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + rewards: [ + { + id: "d03f79f4-815f-3500-b851-cc1e68a457f9", + status: "REDEEMED", + loyalty_account_id: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + reward_tier_id: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", + points: 10, + order_id: "PyATxhYLfsMqpVkcKJITPydgEYfZY", + created_at: "2020-05-08T22:00:44Z", + updated_at: "2020-05-08T22:01:17Z", + redeemed_at: "2020-05-08T22:01:17Z", + }, + { + id: "9f18ac21-233a-31c3-be77-b45840f5a810", + status: "REDEEMED", + loyalty_account_id: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + reward_tier_id: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", + points: 10, + order_id: "order_id", + created_at: "2020-05-08T21:55:42Z", + updated_at: "2020-05-08T21:56:00Z", + redeemed_at: "2020-05-08T21:56:00Z", + }, + { + id: "a8f43ebe-2ad6-3001-bdd5-7d7c2da08943", + status: "DELETED", + loyalty_account_id: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + reward_tier_id: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", + points: 10, + order_id: "5NB69ZNh3FbsOs1ox43bh1xrli6YY", + created_at: "2020-05-01T21:49:54Z", + updated_at: "2020-05-08T21:55:10Z", + redeemed_at: "redeemed_at", + }, + { + id: "a051254c-f840-3b45-8cf1-50bcd38ff92a", + status: "ISSUED", + loyalty_account_id: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + reward_tier_id: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", + points: 10, + order_id: "LQQ16znvi2VIUKPVhUfJefzr1eEZY", + created_at: "2020-05-01T20:20:37Z", + updated_at: "2020-05-01T20:20:40Z", + redeemed_at: "redeemed_at", + }, + ], + cursor: "cursor", + }; + server + .mockEndpoint() + .post("/v2/loyalty/rewards/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.loyalty.rewards.search({ + query: { + loyaltyAccountId: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + }, + limit: 10, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + rewards: [ + { + id: "d03f79f4-815f-3500-b851-cc1e68a457f9", + status: "REDEEMED", + loyaltyAccountId: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + rewardTierId: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", + points: 10, + orderId: "PyATxhYLfsMqpVkcKJITPydgEYfZY", + createdAt: "2020-05-08T22:00:44Z", + updatedAt: "2020-05-08T22:01:17Z", + redeemedAt: "2020-05-08T22:01:17Z", + }, + { + id: "9f18ac21-233a-31c3-be77-b45840f5a810", + status: "REDEEMED", + loyaltyAccountId: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + rewardTierId: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", + points: 10, + orderId: "order_id", + createdAt: "2020-05-08T21:55:42Z", + updatedAt: "2020-05-08T21:56:00Z", + redeemedAt: "2020-05-08T21:56:00Z", + }, + { + id: "a8f43ebe-2ad6-3001-bdd5-7d7c2da08943", + status: "DELETED", + loyaltyAccountId: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + rewardTierId: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", + points: 10, + orderId: "5NB69ZNh3FbsOs1ox43bh1xrli6YY", + createdAt: "2020-05-01T21:49:54Z", + updatedAt: "2020-05-08T21:55:10Z", + redeemedAt: "redeemed_at", + }, + { + id: "a051254c-f840-3b45-8cf1-50bcd38ff92a", + status: "ISSUED", + loyaltyAccountId: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + rewardTierId: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", + points: 10, + orderId: "LQQ16znvi2VIUKPVhUfJefzr1eEZY", + createdAt: "2020-05-01T20:20:37Z", + updatedAt: "2020-05-01T20:20:40Z", + redeemedAt: "redeemed_at", + }, + ], + cursor: "cursor", + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + reward: { + id: "9f18ac21-233a-31c3-be77-b45840f5a810", + status: "REDEEMED", + loyalty_account_id: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + reward_tier_id: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", + points: 10, + order_id: "order_id", + created_at: "2020-05-08T21:55:42Z", + updated_at: "2020-05-08T21:56:00Z", + redeemed_at: "2020-05-08T21:56:00Z", + }, + }; + server + .mockEndpoint() + .get("/v2/loyalty/rewards/reward_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.loyalty.rewards.get({ + rewardId: "reward_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + reward: { + id: "9f18ac21-233a-31c3-be77-b45840f5a810", + status: "REDEEMED", + loyaltyAccountId: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + rewardTierId: "e1b39225-9da5-43d1-a5db-782cdd8ad94f", + points: 10, + orderId: "order_id", + createdAt: "2020-05-08T21:55:42Z", + updatedAt: "2020-05-08T21:56:00Z", + redeemedAt: "2020-05-08T21:56:00Z", + }, + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/loyalty/rewards/reward_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.loyalty.rewards.delete({ + rewardId: "reward_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("redeem", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "98adc7f7-6963-473b-b29c-f3c9cdd7d994", + location_id: "P034NEENMD09F", + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + event: { + id: "67377a6e-dbdc-369d-aa16-2e7ed422e71f", + type: "REDEEM_REWARD", + created_at: "2020-05-08T21:56:00Z", + accumulate_points: { loyalty_program_id: "loyalty_program_id", points: 1, order_id: "order_id" }, + create_reward: { loyalty_program_id: "loyalty_program_id", reward_id: "reward_id", points: 1 }, + redeem_reward: { + loyalty_program_id: "d619f755-2d17-41f3-990d-c04ecedd64dd", + reward_id: "9f18ac21-233a-31c3-be77-b45840f5a810", + order_id: "order_id", + }, + delete_reward: { loyalty_program_id: "loyalty_program_id", reward_id: "reward_id", points: 1 }, + adjust_points: { loyalty_program_id: "loyalty_program_id", points: 1, reason: "reason" }, + loyalty_account_id: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + location_id: "P034NEENMD09F", + source: "LOYALTY_API", + expire_points: { loyalty_program_id: "loyalty_program_id", points: 1 }, + other_event: { loyalty_program_id: "loyalty_program_id", points: 1 }, + accumulate_promotion_points: { + loyalty_program_id: "loyalty_program_id", + loyalty_promotion_id: "loyalty_promotion_id", + points: 1, + order_id: "order_id", + }, + }, + }; + server + .mockEndpoint() + .post("/v2/loyalty/rewards/reward_id/redeem") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.loyalty.rewards.redeem({ + rewardId: "reward_id", + idempotencyKey: "98adc7f7-6963-473b-b29c-f3c9cdd7d994", + locationId: "P034NEENMD09F", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + event: { + id: "67377a6e-dbdc-369d-aa16-2e7ed422e71f", + type: "REDEEM_REWARD", + createdAt: "2020-05-08T21:56:00Z", + accumulatePoints: { + loyaltyProgramId: "loyalty_program_id", + points: 1, + orderId: "order_id", + }, + createReward: { + loyaltyProgramId: "loyalty_program_id", + rewardId: "reward_id", + points: 1, + }, + redeemReward: { + loyaltyProgramId: "d619f755-2d17-41f3-990d-c04ecedd64dd", + rewardId: "9f18ac21-233a-31c3-be77-b45840f5a810", + orderId: "order_id", + }, + deleteReward: { + loyaltyProgramId: "loyalty_program_id", + rewardId: "reward_id", + points: 1, + }, + adjustPoints: { + loyaltyProgramId: "loyalty_program_id", + points: 1, + reason: "reason", + }, + loyaltyAccountId: "5adcb100-07f1-4ee7-b8c6-6bb9ebc474bd", + locationId: "P034NEENMD09F", + source: "LOYALTY_API", + expirePoints: { + loyaltyProgramId: "loyalty_program_id", + points: 1, + }, + otherEvent: { + loyaltyProgramId: "loyalty_program_id", + points: 1, + }, + accumulatePromotionPoints: { + loyaltyProgramId: "loyalty_program_id", + loyaltyPromotionId: "loyalty_promotion_id", + points: 1, + orderId: "order_id", + }, + }, + }); + }); +}); diff --git a/tests/wire/merchants.test.ts b/tests/wire/merchants.test.ts new file mode 100644 index 000000000..e7926916c --- /dev/null +++ b/tests/wire/merchants.test.ts @@ -0,0 +1,58 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Merchants", () => { + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + merchant: { + id: "DM7VKY8Q63GNP", + business_name: "Apple A Day", + country: "US", + language_code: "en-US", + currency: "USD", + status: "ACTIVE", + main_location_id: "9A65CGC72ZQG1", + created_at: "2021-12-10T19:25:52.484Z", + }, + }; + server + .mockEndpoint() + .get("/v2/merchants/merchant_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.merchants.get({ + merchantId: "merchant_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + merchant: { + id: "DM7VKY8Q63GNP", + businessName: "Apple A Day", + country: "US", + languageCode: "en-US", + currency: "USD", + status: "ACTIVE", + mainLocationId: "9A65CGC72ZQG1", + createdAt: "2021-12-10T19:25:52.484Z", + }, + }); + }); +}); diff --git a/tests/wire/merchants/customAttributeDefinitions.test.ts b/tests/wire/merchants/customAttributeDefinitions.test.ts new file mode 100644 index 000000000..97c98f35a --- /dev/null +++ b/tests/wire/merchants/customAttributeDefinitions.test.ts @@ -0,0 +1,229 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("CustomAttributeDefinitions", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + custom_attribute_definition: { + key: "alternative_seller_name", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Alternative Merchant Name", + description: "This is the other name this merchant goes by.", + visibility: "VISIBILITY_READ_ONLY", + }, + }; + const rawResponseBody = { + custom_attribute_definition: { + key: "alternative_seller_name", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Alternative Merchant Name", + description: "This is the other name this merchant goes by.", + visibility: "VISIBILITY_READ_ONLY", + version: 1, + updated_at: "2023-05-05T19:06:36.559Z", + created_at: "2023-05-05T19:06:36.559Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/merchants/custom-attribute-definitions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.merchants.customAttributeDefinitions.create({ + customAttributeDefinition: { + key: "alternative_seller_name", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Alternative Merchant Name", + description: "This is the other name this merchant goes by.", + visibility: "VISIBILITY_READ_ONLY", + }, + }); + expect(response).toEqual({ + customAttributeDefinition: { + key: "alternative_seller_name", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Alternative Merchant Name", + description: "This is the other name this merchant goes by.", + visibility: "VISIBILITY_READ_ONLY", + version: 1, + updatedAt: "2023-05-05T19:06:36.559Z", + createdAt: "2023-05-05T19:06:36.559Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + custom_attribute_definition: { + key: "alternative_seller_name", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Alternative Merchant Name", + description: "This is the other name this merchant goes by.", + visibility: "VISIBILITY_READ_ONLY", + version: 1, + updated_at: "2023-05-05T19:06:36.559Z", + created_at: "2023-05-05T19:06:36.559Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/merchants/custom-attribute-definitions/key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.merchants.customAttributeDefinitions.get({ + key: "key", + }); + expect(response).toEqual({ + customAttributeDefinition: { + key: "alternative_seller_name", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Alternative Merchant Name", + description: "This is the other name this merchant goes by.", + visibility: "VISIBILITY_READ_ONLY", + version: 1, + updatedAt: "2023-05-05T19:06:36.559Z", + createdAt: "2023-05-05T19:06:36.559Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + custom_attribute_definition: { + description: "Update the description as desired.", + visibility: "VISIBILITY_READ_ONLY", + }, + }; + const rawResponseBody = { + custom_attribute_definition: { + key: "alternative_seller_name", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Alternative Merchant Name", + description: "Update the description as desired.", + visibility: "VISIBILITY_READ_ONLY", + version: 2, + updated_at: "2023-05-05T19:34:10.181Z", + created_at: "2023-05-05T19:06:36.559Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .put("/v2/merchants/custom-attribute-definitions/key") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.merchants.customAttributeDefinitions.update({ + key: "key", + customAttributeDefinition: { + description: "Update the description as desired.", + visibility: "VISIBILITY_READ_ONLY", + }, + }); + expect(response).toEqual({ + customAttributeDefinition: { + key: "alternative_seller_name", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.String", + }, + name: "Alternative Merchant Name", + description: "Update the description as desired.", + visibility: "VISIBILITY_READ_ONLY", + version: 2, + updatedAt: "2023-05-05T19:34:10.181Z", + createdAt: "2023-05-05T19:06:36.559Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/merchants/custom-attribute-definitions/key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.merchants.customAttributeDefinitions.delete({ + key: "key", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/merchants/customAttributes.test.ts b/tests/wire/merchants/customAttributes.test.ts new file mode 100644 index 000000000..358de20d9 --- /dev/null +++ b/tests/wire/merchants/customAttributes.test.ts @@ -0,0 +1,359 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("CustomAttributes", () => { + test("batchDelete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + values: { id1: { key: "alternative_seller_name" }, id2: { key: "has_seen_tutorial" } }, + }; + const rawResponseBody = { + values: { + id1: { errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }] }, + id2: { errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }] }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/merchants/custom-attributes/bulk-delete") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.merchants.customAttributes.batchDelete({ + values: { + id1: { + key: "alternative_seller_name", + }, + id2: { + key: "has_seen_tutorial", + }, + }, + }); + expect(response).toEqual({ + values: { + id1: { + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + id2: { + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("batchUpsert", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + values: { + id1: { + merchant_id: "DM7VKY8Q63GNP", + custom_attribute: { key: "alternative_seller_name", value: "Ultimate Sneaker Store" }, + }, + id2: { merchant_id: "DM7VKY8Q63GNP", custom_attribute: { key: "has_seen_tutorial", value: true } }, + }, + }; + const rawResponseBody = { + values: { + id1: { + merchant_id: "DM7VKY8Q63GNP", + custom_attribute: { + key: "alternative_seller_name", + value: "Ultimate Sneaker Store", + version: 2, + visibility: "VISIBILITY_READ_ONLY", + updated_at: "2023-05-06T19:21:04.551Z", + created_at: "2023-05-06T19:02:58.647Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + id2: { + merchant_id: "DM7VKY8Q63GNP", + custom_attribute: { + key: "has_seen_tutorial", + value: true, + version: 1, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updated_at: "2023-05-06T19:21:04.551Z", + created_at: "2023-05-06T19:02:58.647Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/merchants/custom-attributes/bulk-upsert") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.merchants.customAttributes.batchUpsert({ + values: { + id1: { + merchantId: "DM7VKY8Q63GNP", + customAttribute: { + key: "alternative_seller_name", + value: "Ultimate Sneaker Store", + }, + }, + id2: { + merchantId: "DM7VKY8Q63GNP", + customAttribute: { + key: "has_seen_tutorial", + value: true, + }, + }, + }, + }); + expect(response).toEqual({ + values: { + id1: { + merchantId: "DM7VKY8Q63GNP", + customAttribute: { + key: "alternative_seller_name", + value: "Ultimate Sneaker Store", + version: 2, + visibility: "VISIBILITY_READ_ONLY", + updatedAt: "2023-05-06T19:21:04.551Z", + createdAt: "2023-05-06T19:02:58.647Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + id2: { + merchantId: "DM7VKY8Q63GNP", + customAttribute: { + key: "has_seen_tutorial", + value: true, + version: 1, + visibility: "VISIBILITY_READ_WRITE_VALUES", + updatedAt: "2023-05-06T19:21:04.551Z", + createdAt: "2023-05-06T19:02:58.647Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + custom_attribute: { + key: "alternative_seller_name", + value: "Ultimate Sneaker Store", + version: 2, + visibility: "VISIBILITY_READ_ONLY", + definition: { + key: "key", + schema: { key: "value" }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updated_at: "updated_at", + created_at: "created_at", + }, + updated_at: "2023-05-06T19:21:04.551Z", + created_at: "2023-05-06T19:02:58.647Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/merchants/merchant_id/custom-attributes/key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.merchants.customAttributes.get({ + merchantId: "merchant_id", + key: "key", + }); + expect(response).toEqual({ + customAttribute: { + key: "alternative_seller_name", + value: "Ultimate Sneaker Store", + version: 2, + visibility: "VISIBILITY_READ_ONLY", + definition: { + key: "key", + schema: { + key: "value", + }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updatedAt: "updated_at", + createdAt: "created_at", + }, + updatedAt: "2023-05-06T19:21:04.551Z", + createdAt: "2023-05-06T19:02:58.647Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("upsert", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { custom_attribute: { value: "Ultimate Sneaker Store" } }; + const rawResponseBody = { + custom_attribute: { + key: "alternative_seller_name", + value: "Ultimate Sneaker Store", + version: 2, + visibility: "VISIBILITY_READ_ONLY", + definition: { + key: "key", + schema: { key: "value" }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updated_at: "updated_at", + created_at: "created_at", + }, + updated_at: "2023-05-06T19:21:04.551Z", + created_at: "2023-05-06T19:02:58.647Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/merchants/merchant_id/custom-attributes/key") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.merchants.customAttributes.upsert({ + merchantId: "merchant_id", + key: "key", + customAttribute: { + value: "Ultimate Sneaker Store", + }, + }); + expect(response).toEqual({ + customAttribute: { + key: "alternative_seller_name", + value: "Ultimate Sneaker Store", + version: 2, + visibility: "VISIBILITY_READ_ONLY", + definition: { + key: "key", + schema: { + key: "value", + }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updatedAt: "updated_at", + createdAt: "created_at", + }, + updatedAt: "2023-05-06T19:21:04.551Z", + createdAt: "2023-05-06T19:02:58.647Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/merchants/merchant_id/custom-attributes/key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.merchants.customAttributes.delete({ + merchantId: "merchant_id", + key: "key", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/mobile.test.ts b/tests/wire/mobile.test.ts new file mode 100644 index 000000000..81f6b19d8 --- /dev/null +++ b/tests/wire/mobile.test.ts @@ -0,0 +1,43 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Mobile", () => { + test("authorizationCode", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { location_id: "YOUR_LOCATION_ID" }; + const rawResponseBody = { + authorization_code: "YOUR_MOBILE_AUTHORIZATION_CODE", + expires_at: "2019-01-10T19:42:08Z", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/mobile/authorization-code") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.mobile.authorizationCode({ + locationId: "YOUR_LOCATION_ID", + }); + expect(response).toEqual({ + authorizationCode: "YOUR_MOBILE_AUTHORIZATION_CODE", + expiresAt: "2019-01-10T19:42:08Z", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/oAuth.test.ts b/tests/wire/oAuth.test.ts new file mode 100644 index 000000000..3f2c98074 --- /dev/null +++ b/tests/wire/oAuth.test.ts @@ -0,0 +1,147 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("OAuth", () => { + test("revokeToken", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { client_id: "CLIENT_ID", access_token: "ACCESS_TOKEN" }; + const rawResponseBody = { + success: true, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/oauth2/revoke") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.oAuth.revokeToken({ + clientId: "CLIENT_ID", + accessToken: "ACCESS_TOKEN", + }); + expect(response).toEqual({ + success: true, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("obtainToken", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + client_id: "sq0idp-uaPHILoPzWZk3tlJqlML0g", + client_secret: "sq0csp-30a-4C_tVOnTh14Piza2BfTPBXyLafLPWSzY1qAjeBfM", + code: "sq0cgb-l0SBqxs4uwxErTVyYOdemg", + grant_type: "authorization_code", + }; + const rawResponseBody = { + access_token: "EAAl3ikZIe18J-2-cHlV2bL4-EaZHGoJUhtEBT7QA6-7AgwIHw8Xe1IoUvGsNxA", + token_type: "bearer", + expires_at: "2025-04-03T18:31:06Z", + merchant_id: "MLQW2MYBY81PZ", + subscription_id: "subscription_id", + plan_id: "plan_id", + id_token: "id_token", + refresh_token: "EQAAl0OcByu3IYJYScGGg-8E5YNf0r0b6jCTCMy5nOcRZ4ok0wbWAL8vY3tZWNcc", + short_lived: false, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + refresh_token_expires_at: "refresh_token_expires_at", + }; + server + .mockEndpoint() + .post("/oauth2/token") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.oAuth.obtainToken({ + clientId: "sq0idp-uaPHILoPzWZk3tlJqlML0g", + clientSecret: "sq0csp-30a-4C_tVOnTh14Piza2BfTPBXyLafLPWSzY1qAjeBfM", + code: "sq0cgb-l0SBqxs4uwxErTVyYOdemg", + grantType: "authorization_code", + }); + expect(response).toEqual({ + accessToken: "EAAl3ikZIe18J-2-cHlV2bL4-EaZHGoJUhtEBT7QA6-7AgwIHw8Xe1IoUvGsNxA", + tokenType: "bearer", + expiresAt: "2025-04-03T18:31:06Z", + merchantId: "MLQW2MYBY81PZ", + subscriptionId: "subscription_id", + planId: "plan_id", + idToken: "id_token", + refreshToken: "EQAAl0OcByu3IYJYScGGg-8E5YNf0r0b6jCTCMy5nOcRZ4ok0wbWAL8vY3tZWNcc", + shortLived: false, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + refreshTokenExpiresAt: "refresh_token_expires_at", + }); + }); + + test("RetrieveTokenStatus", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + scopes: ["PAYMENTS_READ", "PAYMENTS_WRITE"], + expires_at: "2022-10-14T14:44:00Z", + client_id: "CLIENT_ID", + merchant_id: "MERCHANT_ID", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/oauth2/token/status") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.oAuth.retrieveTokenStatus(); + expect(response).toEqual({ + scopes: ["PAYMENTS_READ", "PAYMENTS_WRITE"], + expiresAt: "2022-10-14T14:44:00Z", + clientId: "CLIENT_ID", + merchantId: "MERCHANT_ID", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("authorize", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + server.mockEndpoint().get("/oauth2/authorize").respondWith().statusCode(200).build(); + + const response = await client.oAuth.authorize(); + expect(response).toEqual(undefined); + }); +}); diff --git a/tests/wire/orders.test.ts b/tests/wire/orders.test.ts new file mode 100644 index 000000000..b1e897e29 --- /dev/null +++ b/tests/wire/orders.test.ts @@ -0,0 +1,2662 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Orders", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + order: { + location_id: "057P5VYJ4A5X1", + reference_id: "my-order-001", + line_items: [ + { + name: "New York Strip Steak", + quantity: "1", + base_price_money: { amount: BigInt(1599), currency: "USD" }, + }, + { + quantity: "2", + catalog_object_id: "BEMYCSMIJL46OCDV4KYIKXIB", + modifiers: [{ catalog_object_id: "CHQX7Y4KY6N5KINJKZCFURPZ" }], + applied_discounts: [{ discount_uid: "one-dollar-off" }], + }, + ], + taxes: [{ uid: "state-sales-tax", name: "State Sales Tax", percentage: "9", scope: "ORDER" }], + discounts: [ + { uid: "labor-day-sale", name: "Labor Day Sale", percentage: "5", scope: "ORDER" }, + { uid: "membership-discount", catalog_object_id: "DB7L55ZH2BGWI4H23ULIWOQ7", scope: "ORDER" }, + { + uid: "one-dollar-off", + name: "Sale - $1.00 off", + amount_money: { amount: BigInt(100), currency: "USD" }, + scope: "LINE_ITEM", + }, + ], + }, + idempotency_key: "8193148c-9586-11e6-99f9-28cfe92138cf", + }; + const rawResponseBody = { + order: { + id: "CAISENgvlJ6jLWAzERDzjyHVybY", + location_id: "057P5VYJ4A5X1", + reference_id: "my-order-001", + source: { name: "My App" }, + customer_id: "customer_id", + line_items: [ + { + uid: "8uSwfzvUImn3IRrvciqlXC", + name: "New York Strip Steak", + quantity: "1", + applied_taxes: [ + { + uid: "aKG87ArnDpvMLSZJHxWUl", + tax_uid: "state-sales-tax", + applied_money: { amount: BigInt(136), currency: "USD" }, + }, + ], + applied_discounts: [ + { + uid: "jWdgP1TpHPFBuVrz81mXVC", + discount_uid: "membership-discount", + applied_money: { amount: BigInt(8), currency: "USD" }, + }, + { + uid: "jnZOjjVY57eRcQAVgEwFuC", + discount_uid: "labor-day-sale", + applied_money: { amount: BigInt(79), currency: "USD" }, + }, + ], + base_price_money: { amount: BigInt(1599), currency: "USD" }, + variation_total_price_money: { amount: BigInt(1599), currency: "USD" }, + gross_sales_money: { amount: BigInt(1599), currency: "USD" }, + total_tax_money: { amount: BigInt(136), currency: "USD" }, + total_discount_money: { amount: BigInt(87), currency: "USD" }, + total_money: { amount: BigInt(1648), currency: "USD" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + { + uid: "v8ZuEXpOJpb0bazLuvrLDB", + name: "New York Steak", + quantity: "2", + catalog_object_id: "BEMYCSMIJL46OCDV4KYIKXIB", + variation_name: "Larger", + modifiers: [ + { + uid: "Lo3qMMckDluu9Qsb58d4CC", + catalog_object_id: "CHQX7Y4KY6N5KINJKZCFURPZ", + name: "Well", + base_price_money: { amount: BigInt(50), currency: "USD" }, + total_price_money: { amount: BigInt(100), currency: "USD" }, + }, + ], + applied_taxes: [ + { + uid: "v1dAgrfUVUPTnVTf9sRPz", + tax_uid: "state-sales-tax", + applied_money: { amount: BigInt(374), currency: "USD" }, + }, + ], + applied_discounts: [ + { + uid: "nUXvdsIItfKko0dbYtY58C", + discount_uid: "membership-discount", + applied_money: { amount: BigInt(22), currency: "USD" }, + }, + { + uid: "qSdkOOOernlVQqsJ94SPjB", + discount_uid: "labor-day-sale", + applied_money: { amount: BigInt(224), currency: "USD" }, + }, + { + uid: "y7bVl4njrWAnfDwmz19izB", + discount_uid: "one-dollar-off", + applied_money: { amount: BigInt(100), currency: "USD" }, + }, + ], + base_price_money: { amount: BigInt(2200), currency: "USD" }, + variation_total_price_money: { amount: BigInt(4400), currency: "USD" }, + gross_sales_money: { amount: BigInt(4500), currency: "USD" }, + total_tax_money: { amount: BigInt(374), currency: "USD" }, + total_discount_money: { amount: BigInt(346), currency: "USD" }, + total_money: { amount: BigInt(4528), currency: "USD" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + ], + taxes: [ + { + uid: "state-sales-tax", + name: "State Sales Tax", + type: "ADDITIVE", + percentage: "9", + applied_money: { amount: BigInt(510), currency: "USD" }, + scope: "ORDER", + }, + ], + discounts: [ + { + uid: "membership-discount", + catalog_object_id: "DB7L55ZH2BGWI4H23ULIWOQ7", + name: "Membership Discount", + type: "FIXED_PERCENTAGE", + percentage: "0.5", + applied_money: { amount: BigInt(30), currency: "USD" }, + scope: "ORDER", + }, + { + uid: "labor-day-sale", + name: "Labor Day Sale", + type: "FIXED_PERCENTAGE", + percentage: "5", + applied_money: { amount: BigInt(303), currency: "USD" }, + scope: "ORDER", + }, + { + uid: "one-dollar-off", + name: "Sale - $1.00 off", + type: "FIXED_AMOUNT", + amount_money: { amount: BigInt(100), currency: "USD" }, + applied_money: { amount: BigInt(100), currency: "USD" }, + scope: "LINE_ITEM", + }, + ], + service_charges: [{}], + fulfillments: [{}], + returns: [{}], + net_amounts: { + total_money: { amount: BigInt(6176), currency: "USD" }, + tax_money: { amount: BigInt(510), currency: "USD" }, + discount_money: { amount: BigInt(433), currency: "USD" }, + tip_money: { amount: BigInt(0), currency: "USD" }, + service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + rounding_adjustment: { uid: "uid", name: "name" }, + tenders: [{ type: "CARD" }], + refunds: [ + { id: "id", location_id: "location_id", reason: "reason", amount_money: {}, status: "PENDING" }, + ], + metadata: { key: "value" }, + created_at: "2020-01-17T20:47:53.293Z", + updated_at: "2020-01-17T20:47:53.293Z", + closed_at: "closed_at", + state: "OPEN", + version: 1, + total_money: { amount: BigInt(6176), currency: "USD" }, + total_tax_money: { amount: BigInt(510), currency: "USD" }, + total_discount_money: { amount: BigInt(433), currency: "USD" }, + total_tip_money: { amount: BigInt(0), currency: "USD" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + ticket_name: "ticket_name", + pricing_options: { auto_apply_discounts: true, auto_apply_taxes: true }, + rewards: [{ id: "id", reward_tier_id: "reward_tier_id" }], + net_amount_due_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/orders") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.orders.create({ + order: { + locationId: "057P5VYJ4A5X1", + referenceId: "my-order-001", + lineItems: [ + { + name: "New York Strip Steak", + quantity: "1", + basePriceMoney: { + amount: BigInt("1599"), + currency: "USD", + }, + }, + { + quantity: "2", + catalogObjectId: "BEMYCSMIJL46OCDV4KYIKXIB", + modifiers: [ + { + catalogObjectId: "CHQX7Y4KY6N5KINJKZCFURPZ", + }, + ], + appliedDiscounts: [ + { + discountUid: "one-dollar-off", + }, + ], + }, + ], + taxes: [ + { + uid: "state-sales-tax", + name: "State Sales Tax", + percentage: "9", + scope: "ORDER", + }, + ], + discounts: [ + { + uid: "labor-day-sale", + name: "Labor Day Sale", + percentage: "5", + scope: "ORDER", + }, + { + uid: "membership-discount", + catalogObjectId: "DB7L55ZH2BGWI4H23ULIWOQ7", + scope: "ORDER", + }, + { + uid: "one-dollar-off", + name: "Sale - $1.00 off", + amountMoney: { + amount: BigInt("100"), + currency: "USD", + }, + scope: "LINE_ITEM", + }, + ], + }, + idempotencyKey: "8193148c-9586-11e6-99f9-28cfe92138cf", + }); + expect(response).toEqual({ + order: { + id: "CAISENgvlJ6jLWAzERDzjyHVybY", + locationId: "057P5VYJ4A5X1", + referenceId: "my-order-001", + source: { + name: "My App", + }, + customerId: "customer_id", + lineItems: [ + { + uid: "8uSwfzvUImn3IRrvciqlXC", + name: "New York Strip Steak", + quantity: "1", + appliedTaxes: [ + { + uid: "aKG87ArnDpvMLSZJHxWUl", + taxUid: "state-sales-tax", + appliedMoney: { + amount: BigInt("136"), + currency: "USD", + }, + }, + ], + appliedDiscounts: [ + { + uid: "jWdgP1TpHPFBuVrz81mXVC", + discountUid: "membership-discount", + appliedMoney: { + amount: BigInt("8"), + currency: "USD", + }, + }, + { + uid: "jnZOjjVY57eRcQAVgEwFuC", + discountUid: "labor-day-sale", + appliedMoney: { + amount: BigInt("79"), + currency: "USD", + }, + }, + ], + basePriceMoney: { + amount: BigInt("1599"), + currency: "USD", + }, + variationTotalPriceMoney: { + amount: BigInt("1599"), + currency: "USD", + }, + grossSalesMoney: { + amount: BigInt("1599"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("136"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("87"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("1648"), + currency: "USD", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + { + uid: "v8ZuEXpOJpb0bazLuvrLDB", + name: "New York Steak", + quantity: "2", + catalogObjectId: "BEMYCSMIJL46OCDV4KYIKXIB", + variationName: "Larger", + modifiers: [ + { + uid: "Lo3qMMckDluu9Qsb58d4CC", + catalogObjectId: "CHQX7Y4KY6N5KINJKZCFURPZ", + name: "Well", + basePriceMoney: { + amount: BigInt("50"), + currency: "USD", + }, + totalPriceMoney: { + amount: BigInt("100"), + currency: "USD", + }, + }, + ], + appliedTaxes: [ + { + uid: "v1dAgrfUVUPTnVTf9sRPz", + taxUid: "state-sales-tax", + appliedMoney: { + amount: BigInt("374"), + currency: "USD", + }, + }, + ], + appliedDiscounts: [ + { + uid: "nUXvdsIItfKko0dbYtY58C", + discountUid: "membership-discount", + appliedMoney: { + amount: BigInt("22"), + currency: "USD", + }, + }, + { + uid: "qSdkOOOernlVQqsJ94SPjB", + discountUid: "labor-day-sale", + appliedMoney: { + amount: BigInt("224"), + currency: "USD", + }, + }, + { + uid: "y7bVl4njrWAnfDwmz19izB", + discountUid: "one-dollar-off", + appliedMoney: { + amount: BigInt("100"), + currency: "USD", + }, + }, + ], + basePriceMoney: { + amount: BigInt("2200"), + currency: "USD", + }, + variationTotalPriceMoney: { + amount: BigInt("4400"), + currency: "USD", + }, + grossSalesMoney: { + amount: BigInt("4500"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("374"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("346"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("4528"), + currency: "USD", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + ], + taxes: [ + { + uid: "state-sales-tax", + name: "State Sales Tax", + type: "ADDITIVE", + percentage: "9", + appliedMoney: { + amount: BigInt("510"), + currency: "USD", + }, + scope: "ORDER", + }, + ], + discounts: [ + { + uid: "membership-discount", + catalogObjectId: "DB7L55ZH2BGWI4H23ULIWOQ7", + name: "Membership Discount", + type: "FIXED_PERCENTAGE", + percentage: "0.5", + appliedMoney: { + amount: BigInt("30"), + currency: "USD", + }, + scope: "ORDER", + }, + { + uid: "labor-day-sale", + name: "Labor Day Sale", + type: "FIXED_PERCENTAGE", + percentage: "5", + appliedMoney: { + amount: BigInt("303"), + currency: "USD", + }, + scope: "ORDER", + }, + { + uid: "one-dollar-off", + name: "Sale - $1.00 off", + type: "FIXED_AMOUNT", + amountMoney: { + amount: BigInt("100"), + currency: "USD", + }, + appliedMoney: { + amount: BigInt("100"), + currency: "USD", + }, + scope: "LINE_ITEM", + }, + ], + serviceCharges: [{}], + fulfillments: [{}], + returns: [{}], + netAmounts: { + totalMoney: { + amount: BigInt("6176"), + currency: "USD", + }, + taxMoney: { + amount: BigInt("510"), + currency: "USD", + }, + discountMoney: { + amount: BigInt("433"), + currency: "USD", + }, + tipMoney: { + amount: BigInt("0"), + currency: "USD", + }, + serviceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + roundingAdjustment: { + uid: "uid", + name: "name", + }, + tenders: [ + { + type: "CARD", + }, + ], + refunds: [ + { + id: "id", + locationId: "location_id", + reason: "reason", + amountMoney: {}, + status: "PENDING", + }, + ], + metadata: { + key: "value", + }, + createdAt: "2020-01-17T20:47:53.293Z", + updatedAt: "2020-01-17T20:47:53.293Z", + closedAt: "closed_at", + state: "OPEN", + version: 1, + totalMoney: { + amount: BigInt("6176"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("510"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("433"), + currency: "USD", + }, + totalTipMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + ticketName: "ticket_name", + pricingOptions: { + autoApplyDiscounts: true, + autoApplyTaxes: true, + }, + rewards: [ + { + id: "id", + rewardTierId: "reward_tier_id", + }, + ], + netAmountDueMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("batchGet", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + location_id: "057P5VYJ4A5X1", + order_ids: ["CAISEM82RcpmcFBM0TfOyiHV3es", "CAISENgvlJ6jLWAzERDzjyHVybY"], + }; + const rawResponseBody = { + orders: [ + { + id: "CAISEM82RcpmcFBM0TfOyiHV3es", + location_id: "057P5VYJ4A5X1", + reference_id: "my-order-001", + customer_id: "customer_id", + line_items: [ + { + uid: "945986d1-9586-11e6-ad5a-28cfe92138cf", + name: "Awesome product", + quantity: "1", + base_price_money: { amount: BigInt(1599), currency: "USD" }, + total_money: { amount: BigInt(1599), currency: "USD" }, + }, + { + uid: "a8f4168c-9586-11e6-bdf0-28cfe92138cf", + name: "Another awesome product", + quantity: "3", + base_price_money: { amount: BigInt(2000), currency: "USD" }, + total_money: { amount: BigInt(6000), currency: "USD" }, + }, + ], + taxes: [{}], + discounts: [{}], + service_charges: [{}], + fulfillments: [{}], + returns: [{}], + tenders: [{ type: "CARD" }], + refunds: [ + { id: "id", location_id: "location_id", reason: "reason", amount_money: {}, status: "PENDING" }, + ], + created_at: "created_at", + updated_at: "updated_at", + closed_at: "closed_at", + state: "OPEN", + version: 1, + total_money: { amount: BigInt(7599), currency: "USD" }, + ticket_name: "ticket_name", + rewards: [{ id: "id", reward_tier_id: "reward_tier_id" }], + }, + ], + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/orders/batch-retrieve") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.orders.batchGet({ + locationId: "057P5VYJ4A5X1", + orderIds: ["CAISEM82RcpmcFBM0TfOyiHV3es", "CAISENgvlJ6jLWAzERDzjyHVybY"], + }); + expect(response).toEqual({ + orders: [ + { + id: "CAISEM82RcpmcFBM0TfOyiHV3es", + locationId: "057P5VYJ4A5X1", + referenceId: "my-order-001", + customerId: "customer_id", + lineItems: [ + { + uid: "945986d1-9586-11e6-ad5a-28cfe92138cf", + name: "Awesome product", + quantity: "1", + basePriceMoney: { + amount: BigInt("1599"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("1599"), + currency: "USD", + }, + }, + { + uid: "a8f4168c-9586-11e6-bdf0-28cfe92138cf", + name: "Another awesome product", + quantity: "3", + basePriceMoney: { + amount: BigInt("2000"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("6000"), + currency: "USD", + }, + }, + ], + taxes: [{}], + discounts: [{}], + serviceCharges: [{}], + fulfillments: [{}], + returns: [{}], + tenders: [ + { + type: "CARD", + }, + ], + refunds: [ + { + id: "id", + locationId: "location_id", + reason: "reason", + amountMoney: {}, + status: "PENDING", + }, + ], + createdAt: "created_at", + updatedAt: "updated_at", + closedAt: "closed_at", + state: "OPEN", + version: 1, + totalMoney: { + amount: BigInt("7599"), + currency: "USD", + }, + ticketName: "ticket_name", + rewards: [ + { + id: "id", + rewardTierId: "reward_tier_id", + }, + ], + }, + ], + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("calculate", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + order: { + location_id: "D7AVYMEAPJ3A3", + line_items: [ + { name: "Item 1", quantity: "1", base_price_money: { amount: BigInt(500), currency: "USD" } }, + { name: "Item 2", quantity: "2", base_price_money: { amount: BigInt(300), currency: "USD" } }, + ], + discounts: [{ name: "50% Off", percentage: "50", scope: "ORDER" }], + }, + }; + const rawResponseBody = { + order: { + id: "id", + location_id: "D7AVYMEAPJ3A3", + reference_id: "reference_id", + source: { name: "name" }, + customer_id: "customer_id", + line_items: [ + { + uid: "ULkg0tQTRK2bkU9fNv3IJD", + name: "Item 1", + quantity: "1", + applied_discounts: [ + { + uid: "9zr9S4dxvPAixvn0lpa1VC", + discount_uid: "zGsRZP69aqSSR9lq9euSPB", + applied_money: { amount: BigInt(250), currency: "USD" }, + }, + ], + base_price_money: { amount: BigInt(500), currency: "USD" }, + variation_total_price_money: { amount: BigInt(500), currency: "USD" }, + gross_sales_money: { amount: BigInt(500), currency: "USD" }, + total_tax_money: { amount: BigInt(0), currency: "USD" }, + total_discount_money: { amount: BigInt(250), currency: "USD" }, + total_money: { amount: BigInt(250), currency: "USD" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + { + uid: "mumY8Nun4BC5aKe2yyx5a", + name: "Item 2", + quantity: "2", + applied_discounts: [ + { + uid: "qa8LwwZK82FgSEkQc2HYVC", + discount_uid: "zGsRZP69aqSSR9lq9euSPB", + applied_money: { amount: BigInt(300), currency: "USD" }, + }, + ], + base_price_money: { amount: BigInt(300), currency: "USD" }, + variation_total_price_money: { amount: BigInt(600), currency: "USD" }, + gross_sales_money: { amount: BigInt(600), currency: "USD" }, + total_tax_money: { amount: BigInt(0), currency: "USD" }, + total_discount_money: { amount: BigInt(300), currency: "USD" }, + total_money: { amount: BigInt(300), currency: "USD" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + ], + taxes: [{}], + discounts: [ + { + uid: "zGsRZP69aqSSR9lq9euSPB", + name: "50% Off", + type: "FIXED_PERCENTAGE", + percentage: "50", + applied_money: { amount: BigInt(550), currency: "USD" }, + scope: "ORDER", + }, + ], + service_charges: [{}], + fulfillments: [{}], + returns: [{}], + net_amounts: { + total_money: { amount: BigInt(550), currency: "USD" }, + tax_money: { amount: BigInt(0), currency: "USD" }, + discount_money: { amount: BigInt(550), currency: "USD" }, + tip_money: { amount: BigInt(0), currency: "USD" }, + service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + rounding_adjustment: { uid: "uid", name: "name" }, + tenders: [{ type: "CARD" }], + refunds: [ + { id: "id", location_id: "location_id", reason: "reason", amount_money: {}, status: "PENDING" }, + ], + metadata: { key: "value" }, + created_at: "2020-05-18T16:30:49.614Z", + updated_at: "2020-05-18T16:30:49.614Z", + closed_at: "closed_at", + state: "OPEN", + version: 1, + total_money: { amount: BigInt(550), currency: "USD" }, + total_tax_money: { amount: BigInt(0), currency: "USD" }, + total_discount_money: { amount: BigInt(550), currency: "USD" }, + total_tip_money: { amount: BigInt(0), currency: "USD" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + ticket_name: "ticket_name", + pricing_options: { auto_apply_discounts: true, auto_apply_taxes: true }, + rewards: [{ id: "id", reward_tier_id: "reward_tier_id" }], + net_amount_due_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/orders/calculate") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.orders.calculate({ + order: { + locationId: "D7AVYMEAPJ3A3", + lineItems: [ + { + name: "Item 1", + quantity: "1", + basePriceMoney: { + amount: BigInt("500"), + currency: "USD", + }, + }, + { + name: "Item 2", + quantity: "2", + basePriceMoney: { + amount: BigInt("300"), + currency: "USD", + }, + }, + ], + discounts: [ + { + name: "50% Off", + percentage: "50", + scope: "ORDER", + }, + ], + }, + }); + expect(response).toEqual({ + order: { + id: "id", + locationId: "D7AVYMEAPJ3A3", + referenceId: "reference_id", + source: { + name: "name", + }, + customerId: "customer_id", + lineItems: [ + { + uid: "ULkg0tQTRK2bkU9fNv3IJD", + name: "Item 1", + quantity: "1", + appliedDiscounts: [ + { + uid: "9zr9S4dxvPAixvn0lpa1VC", + discountUid: "zGsRZP69aqSSR9lq9euSPB", + appliedMoney: { + amount: BigInt("250"), + currency: "USD", + }, + }, + ], + basePriceMoney: { + amount: BigInt("500"), + currency: "USD", + }, + variationTotalPriceMoney: { + amount: BigInt("500"), + currency: "USD", + }, + grossSalesMoney: { + amount: BigInt("500"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("250"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("250"), + currency: "USD", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + { + uid: "mumY8Nun4BC5aKe2yyx5a", + name: "Item 2", + quantity: "2", + appliedDiscounts: [ + { + uid: "qa8LwwZK82FgSEkQc2HYVC", + discountUid: "zGsRZP69aqSSR9lq9euSPB", + appliedMoney: { + amount: BigInt("300"), + currency: "USD", + }, + }, + ], + basePriceMoney: { + amount: BigInt("300"), + currency: "USD", + }, + variationTotalPriceMoney: { + amount: BigInt("600"), + currency: "USD", + }, + grossSalesMoney: { + amount: BigInt("600"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("300"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("300"), + currency: "USD", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + ], + taxes: [{}], + discounts: [ + { + uid: "zGsRZP69aqSSR9lq9euSPB", + name: "50% Off", + type: "FIXED_PERCENTAGE", + percentage: "50", + appliedMoney: { + amount: BigInt("550"), + currency: "USD", + }, + scope: "ORDER", + }, + ], + serviceCharges: [{}], + fulfillments: [{}], + returns: [{}], + netAmounts: { + totalMoney: { + amount: BigInt("550"), + currency: "USD", + }, + taxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + discountMoney: { + amount: BigInt("550"), + currency: "USD", + }, + tipMoney: { + amount: BigInt("0"), + currency: "USD", + }, + serviceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + roundingAdjustment: { + uid: "uid", + name: "name", + }, + tenders: [ + { + type: "CARD", + }, + ], + refunds: [ + { + id: "id", + locationId: "location_id", + reason: "reason", + amountMoney: {}, + status: "PENDING", + }, + ], + metadata: { + key: "value", + }, + createdAt: "2020-05-18T16:30:49.614Z", + updatedAt: "2020-05-18T16:30:49.614Z", + closedAt: "closed_at", + state: "OPEN", + version: 1, + totalMoney: { + amount: BigInt("550"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("550"), + currency: "USD", + }, + totalTipMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + ticketName: "ticket_name", + pricingOptions: { + autoApplyDiscounts: true, + autoApplyTaxes: true, + }, + rewards: [ + { + id: "id", + rewardTierId: "reward_tier_id", + }, + ], + netAmountDueMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("clone", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + order_id: "ZAISEM52YcpmcWAzERDOyiWS123", + version: 3, + idempotency_key: "UNIQUE_STRING", + }; + const rawResponseBody = { + order: { + id: "CAISENgvlJ6jLWAzERDzjyHVybY", + location_id: "057P5VYJ4A5X1", + reference_id: "my-order-001", + source: { name: "My App" }, + customer_id: "customer_id", + line_items: [ + { + uid: "8uSwfzvUImn3IRrvciqlXC", + name: "New York Strip Steak", + quantity: "1", + applied_taxes: [ + { + uid: "aKG87ArnDpvMLSZJHxWUl", + tax_uid: "state-sales-tax", + applied_money: { amount: BigInt(136), currency: "USD" }, + }, + ], + applied_discounts: [ + { + uid: "jWdgP1TpHPFBuVrz81mXVC", + discount_uid: "membership-discount", + applied_money: { amount: BigInt(8), currency: "USD" }, + }, + { + uid: "jnZOjjVY57eRcQAVgEwFuC", + discount_uid: "labor-day-sale", + applied_money: { amount: BigInt(79), currency: "USD" }, + }, + ], + base_price_money: { amount: BigInt(1599), currency: "USD" }, + variation_total_price_money: { amount: BigInt(1599), currency: "USD" }, + gross_sales_money: { amount: BigInt(1599), currency: "USD" }, + total_tax_money: { amount: BigInt(136), currency: "USD" }, + total_discount_money: { amount: BigInt(87), currency: "USD" }, + total_money: { amount: BigInt(1648), currency: "USD" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + { + uid: "v8ZuEXpOJpb0bazLuvrLDB", + name: "New York Steak", + quantity: "2", + catalog_object_id: "BEMYCSMIJL46OCDV4KYIKXIB", + variation_name: "Larger", + modifiers: [ + { + uid: "Lo3qMMckDluu9Qsb58d4CC", + catalog_object_id: "CHQX7Y4KY6N5KINJKZCFURPZ", + name: "Well", + base_price_money: { amount: BigInt(50), currency: "USD" }, + total_price_money: { amount: BigInt(100), currency: "USD" }, + }, + ], + applied_taxes: [ + { + uid: "v1dAgrfUVUPTnVTf9sRPz", + tax_uid: "state-sales-tax", + applied_money: { amount: BigInt(374), currency: "USD" }, + }, + ], + applied_discounts: [ + { + uid: "nUXvdsIItfKko0dbYtY58C", + discount_uid: "membership-discount", + applied_money: { amount: BigInt(22), currency: "USD" }, + }, + { + uid: "qSdkOOOernlVQqsJ94SPjB", + discount_uid: "labor-day-sale", + applied_money: { amount: BigInt(224), currency: "USD" }, + }, + { + uid: "y7bVl4njrWAnfDwmz19izB", + discount_uid: "one-dollar-off", + applied_money: { amount: BigInt(100), currency: "USD" }, + }, + ], + base_price_money: { amount: BigInt(2200), currency: "USD" }, + variation_total_price_money: { amount: BigInt(4400), currency: "USD" }, + gross_sales_money: { amount: BigInt(4500), currency: "USD" }, + total_tax_money: { amount: BigInt(374), currency: "USD" }, + total_discount_money: { amount: BigInt(346), currency: "USD" }, + total_money: { amount: BigInt(4528), currency: "USD" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + ], + taxes: [ + { + uid: "state-sales-tax", + name: "State Sales Tax", + type: "ADDITIVE", + percentage: "9", + applied_money: { amount: BigInt(510), currency: "USD" }, + scope: "ORDER", + }, + ], + discounts: [ + { + uid: "membership-discount", + catalog_object_id: "DB7L55ZH2BGWI4H23ULIWOQ7", + name: "Membership Discount", + type: "FIXED_PERCENTAGE", + percentage: "0.5", + applied_money: { amount: BigInt(30), currency: "USD" }, + scope: "ORDER", + }, + { + uid: "labor-day-sale", + name: "Labor Day Sale", + type: "FIXED_PERCENTAGE", + percentage: "5", + applied_money: { amount: BigInt(303), currency: "USD" }, + scope: "ORDER", + }, + { + uid: "one-dollar-off", + name: "Sale - $1.00 off", + type: "FIXED_AMOUNT", + amount_money: { amount: BigInt(100), currency: "USD" }, + applied_money: { amount: BigInt(100), currency: "USD" }, + scope: "LINE_ITEM", + }, + ], + service_charges: [{}], + fulfillments: [{}], + returns: [{}], + net_amounts: { + total_money: { amount: BigInt(6176), currency: "USD" }, + tax_money: { amount: BigInt(510), currency: "USD" }, + discount_money: { amount: BigInt(433), currency: "USD" }, + tip_money: { amount: BigInt(0), currency: "USD" }, + service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + rounding_adjustment: { uid: "uid", name: "name" }, + tenders: [{ type: "CARD" }], + refunds: [ + { id: "id", location_id: "location_id", reason: "reason", amount_money: {}, status: "PENDING" }, + ], + metadata: { key: "value" }, + created_at: "2020-01-17T20:47:53.293Z", + updated_at: "2020-01-17T20:47:53.293Z", + closed_at: "closed_at", + state: "DRAFT", + version: 1, + total_money: { amount: BigInt(6176), currency: "USD" }, + total_tax_money: { amount: BigInt(510), currency: "USD" }, + total_discount_money: { amount: BigInt(433), currency: "USD" }, + total_tip_money: { amount: BigInt(0), currency: "USD" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + ticket_name: "ticket_name", + pricing_options: { auto_apply_discounts: true, auto_apply_taxes: true }, + rewards: [{ id: "id", reward_tier_id: "reward_tier_id" }], + net_amount_due_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/orders/clone") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.orders.clone({ + orderId: "ZAISEM52YcpmcWAzERDOyiWS123", + version: 3, + idempotencyKey: "UNIQUE_STRING", + }); + expect(response).toEqual({ + order: { + id: "CAISENgvlJ6jLWAzERDzjyHVybY", + locationId: "057P5VYJ4A5X1", + referenceId: "my-order-001", + source: { + name: "My App", + }, + customerId: "customer_id", + lineItems: [ + { + uid: "8uSwfzvUImn3IRrvciqlXC", + name: "New York Strip Steak", + quantity: "1", + appliedTaxes: [ + { + uid: "aKG87ArnDpvMLSZJHxWUl", + taxUid: "state-sales-tax", + appliedMoney: { + amount: BigInt("136"), + currency: "USD", + }, + }, + ], + appliedDiscounts: [ + { + uid: "jWdgP1TpHPFBuVrz81mXVC", + discountUid: "membership-discount", + appliedMoney: { + amount: BigInt("8"), + currency: "USD", + }, + }, + { + uid: "jnZOjjVY57eRcQAVgEwFuC", + discountUid: "labor-day-sale", + appliedMoney: { + amount: BigInt("79"), + currency: "USD", + }, + }, + ], + basePriceMoney: { + amount: BigInt("1599"), + currency: "USD", + }, + variationTotalPriceMoney: { + amount: BigInt("1599"), + currency: "USD", + }, + grossSalesMoney: { + amount: BigInt("1599"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("136"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("87"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("1648"), + currency: "USD", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + { + uid: "v8ZuEXpOJpb0bazLuvrLDB", + name: "New York Steak", + quantity: "2", + catalogObjectId: "BEMYCSMIJL46OCDV4KYIKXIB", + variationName: "Larger", + modifiers: [ + { + uid: "Lo3qMMckDluu9Qsb58d4CC", + catalogObjectId: "CHQX7Y4KY6N5KINJKZCFURPZ", + name: "Well", + basePriceMoney: { + amount: BigInt("50"), + currency: "USD", + }, + totalPriceMoney: { + amount: BigInt("100"), + currency: "USD", + }, + }, + ], + appliedTaxes: [ + { + uid: "v1dAgrfUVUPTnVTf9sRPz", + taxUid: "state-sales-tax", + appliedMoney: { + amount: BigInt("374"), + currency: "USD", + }, + }, + ], + appliedDiscounts: [ + { + uid: "nUXvdsIItfKko0dbYtY58C", + discountUid: "membership-discount", + appliedMoney: { + amount: BigInt("22"), + currency: "USD", + }, + }, + { + uid: "qSdkOOOernlVQqsJ94SPjB", + discountUid: "labor-day-sale", + appliedMoney: { + amount: BigInt("224"), + currency: "USD", + }, + }, + { + uid: "y7bVl4njrWAnfDwmz19izB", + discountUid: "one-dollar-off", + appliedMoney: { + amount: BigInt("100"), + currency: "USD", + }, + }, + ], + basePriceMoney: { + amount: BigInt("2200"), + currency: "USD", + }, + variationTotalPriceMoney: { + amount: BigInt("4400"), + currency: "USD", + }, + grossSalesMoney: { + amount: BigInt("4500"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("374"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("346"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("4528"), + currency: "USD", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + ], + taxes: [ + { + uid: "state-sales-tax", + name: "State Sales Tax", + type: "ADDITIVE", + percentage: "9", + appliedMoney: { + amount: BigInt("510"), + currency: "USD", + }, + scope: "ORDER", + }, + ], + discounts: [ + { + uid: "membership-discount", + catalogObjectId: "DB7L55ZH2BGWI4H23ULIWOQ7", + name: "Membership Discount", + type: "FIXED_PERCENTAGE", + percentage: "0.5", + appliedMoney: { + amount: BigInt("30"), + currency: "USD", + }, + scope: "ORDER", + }, + { + uid: "labor-day-sale", + name: "Labor Day Sale", + type: "FIXED_PERCENTAGE", + percentage: "5", + appliedMoney: { + amount: BigInt("303"), + currency: "USD", + }, + scope: "ORDER", + }, + { + uid: "one-dollar-off", + name: "Sale - $1.00 off", + type: "FIXED_AMOUNT", + amountMoney: { + amount: BigInt("100"), + currency: "USD", + }, + appliedMoney: { + amount: BigInt("100"), + currency: "USD", + }, + scope: "LINE_ITEM", + }, + ], + serviceCharges: [{}], + fulfillments: [{}], + returns: [{}], + netAmounts: { + totalMoney: { + amount: BigInt("6176"), + currency: "USD", + }, + taxMoney: { + amount: BigInt("510"), + currency: "USD", + }, + discountMoney: { + amount: BigInt("433"), + currency: "USD", + }, + tipMoney: { + amount: BigInt("0"), + currency: "USD", + }, + serviceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + roundingAdjustment: { + uid: "uid", + name: "name", + }, + tenders: [ + { + type: "CARD", + }, + ], + refunds: [ + { + id: "id", + locationId: "location_id", + reason: "reason", + amountMoney: {}, + status: "PENDING", + }, + ], + metadata: { + key: "value", + }, + createdAt: "2020-01-17T20:47:53.293Z", + updatedAt: "2020-01-17T20:47:53.293Z", + closedAt: "closed_at", + state: "DRAFT", + version: 1, + totalMoney: { + amount: BigInt("6176"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("510"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("433"), + currency: "USD", + }, + totalTipMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + ticketName: "ticket_name", + pricingOptions: { + autoApplyDiscounts: true, + autoApplyTaxes: true, + }, + rewards: [ + { + id: "id", + rewardTierId: "reward_tier_id", + }, + ], + netAmountDueMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("search", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + location_ids: ["057P5VYJ4A5X1", "18YC4JDH91E1H"], + query: { + filter: { + state_filter: { states: ["COMPLETED"] }, + date_time_filter: { + closed_at: { start_at: "2018-03-03T20:00:00+00:00", end_at: "2019-03-04T21:54:45+00:00" }, + }, + }, + sort: { sort_field: "CLOSED_AT", sort_order: "DESC" }, + }, + limit: 3, + return_entries: true, + }; + const rawResponseBody = { + order_entries: [ + { order_id: "CAISEM82RcpmcFBM0TfOyiHV3es", version: 1, location_id: "057P5VYJ4A5X1" }, + { order_id: "CAISENgvlJ6jLWAzERDzjyHVybY", version: 1, location_id: "18YC4JDH91E1H" }, + { order_id: "CAISEM52YcpmcWAzERDOyiWS3ty", version: 1, location_id: "057P5VYJ4A5X1" }, + ], + orders: [ + { + id: "id", + location_id: "location_id", + reference_id: "reference_id", + customer_id: "customer_id", + line_items: [{ quantity: "quantity" }], + taxes: [{}], + discounts: [{}], + service_charges: [{}], + fulfillments: [{}], + returns: [{}], + tenders: [{ type: "CARD" }], + refunds: [ + { id: "id", location_id: "location_id", reason: "reason", amount_money: {}, status: "PENDING" }, + ], + created_at: "created_at", + updated_at: "updated_at", + closed_at: "closed_at", + state: "OPEN", + version: 1, + ticket_name: "ticket_name", + rewards: [{ id: "id", reward_tier_id: "reward_tier_id" }], + }, + ], + cursor: "123", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/orders/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.orders.search({ + locationIds: ["057P5VYJ4A5X1", "18YC4JDH91E1H"], + query: { + filter: { + stateFilter: { + states: ["COMPLETED"], + }, + dateTimeFilter: { + closedAt: { + startAt: "2018-03-03T20:00:00+00:00", + endAt: "2019-03-04T21:54:45+00:00", + }, + }, + }, + sort: { + sortField: "CLOSED_AT", + sortOrder: "DESC", + }, + }, + limit: 3, + returnEntries: true, + }); + expect(response).toEqual({ + orderEntries: [ + { + orderId: "CAISEM82RcpmcFBM0TfOyiHV3es", + version: 1, + locationId: "057P5VYJ4A5X1", + }, + { + orderId: "CAISENgvlJ6jLWAzERDzjyHVybY", + version: 1, + locationId: "18YC4JDH91E1H", + }, + { + orderId: "CAISEM52YcpmcWAzERDOyiWS3ty", + version: 1, + locationId: "057P5VYJ4A5X1", + }, + ], + orders: [ + { + id: "id", + locationId: "location_id", + referenceId: "reference_id", + customerId: "customer_id", + lineItems: [ + { + quantity: "quantity", + }, + ], + taxes: [{}], + discounts: [{}], + serviceCharges: [{}], + fulfillments: [{}], + returns: [{}], + tenders: [ + { + type: "CARD", + }, + ], + refunds: [ + { + id: "id", + locationId: "location_id", + reason: "reason", + amountMoney: {}, + status: "PENDING", + }, + ], + createdAt: "created_at", + updatedAt: "updated_at", + closedAt: "closed_at", + state: "OPEN", + version: 1, + ticketName: "ticket_name", + rewards: [ + { + id: "id", + rewardTierId: "reward_tier_id", + }, + ], + }, + ], + cursor: "123", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + order: { + id: "CAISENgvlJ6jLWAzERDzjyHVybY", + location_id: "D7AVYMEAPJ3A3", + reference_id: "reference_id", + source: { name: "name" }, + customer_id: "customer_id", + line_items: [ + { + uid: "ULkg0tQTRK2bkU9fNv3IJD", + name: "Item 1", + quantity: "1", + applied_discounts: [ + { + uid: "9zr9S4dxvPAixvn0lpa1VC", + discount_uid: "zGsRZP69aqSSR9lq9euSPB", + applied_money: { amount: BigInt(250), currency: "USD" }, + }, + ], + base_price_money: { amount: BigInt(500), currency: "USD" }, + variation_total_price_money: { amount: BigInt(500), currency: "USD" }, + gross_sales_money: { amount: BigInt(500), currency: "USD" }, + total_tax_money: { amount: BigInt(0), currency: "USD" }, + total_discount_money: { amount: BigInt(250), currency: "USD" }, + total_money: { amount: BigInt(250), currency: "USD" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + { + uid: "mumY8Nun4BC5aKe2yyx5a", + name: "Item 2", + quantity: "2", + applied_discounts: [ + { + uid: "qa8LwwZK82FgSEkQc2HYVC", + discount_uid: "zGsRZP69aqSSR9lq9euSPB", + applied_money: { amount: BigInt(300), currency: "USD" }, + }, + ], + base_price_money: { amount: BigInt(300), currency: "USD" }, + variation_total_price_money: { amount: BigInt(600), currency: "USD" }, + gross_sales_money: { amount: BigInt(600), currency: "USD" }, + total_tax_money: { amount: BigInt(0), currency: "USD" }, + total_discount_money: { amount: BigInt(300), currency: "USD" }, + total_money: { amount: BigInt(300), currency: "USD" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + ], + taxes: [{}], + discounts: [ + { + uid: "zGsRZP69aqSSR9lq9euSPB", + name: "50% Off", + type: "FIXED_PERCENTAGE", + percentage: "50", + applied_money: { amount: BigInt(550), currency: "USD" }, + scope: "ORDER", + }, + ], + service_charges: [{}], + fulfillments: [{}], + returns: [{}], + net_amounts: { + total_money: { amount: BigInt(550), currency: "USD" }, + tax_money: { amount: BigInt(0), currency: "USD" }, + discount_money: { amount: BigInt(550), currency: "USD" }, + tip_money: { amount: BigInt(0), currency: "USD" }, + service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + rounding_adjustment: { uid: "uid", name: "name" }, + tenders: [{ type: "CARD" }], + refunds: [ + { id: "id", location_id: "location_id", reason: "reason", amount_money: {}, status: "PENDING" }, + ], + metadata: { key: "value" }, + created_at: "2020-05-18T16:30:49.614Z", + updated_at: "2020-05-18T16:30:49.614Z", + closed_at: "closed_at", + state: "OPEN", + version: 1, + total_money: { amount: BigInt(550), currency: "USD" }, + total_tax_money: { amount: BigInt(0), currency: "USD" }, + total_discount_money: { amount: BigInt(550), currency: "USD" }, + total_tip_money: { amount: BigInt(0), currency: "USD" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + ticket_name: "ticket_name", + pricing_options: { auto_apply_discounts: true, auto_apply_taxes: true }, + rewards: [{ id: "id", reward_tier_id: "reward_tier_id" }], + net_amount_due_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/orders/order_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.orders.get({ + orderId: "order_id", + }); + expect(response).toEqual({ + order: { + id: "CAISENgvlJ6jLWAzERDzjyHVybY", + locationId: "D7AVYMEAPJ3A3", + referenceId: "reference_id", + source: { + name: "name", + }, + customerId: "customer_id", + lineItems: [ + { + uid: "ULkg0tQTRK2bkU9fNv3IJD", + name: "Item 1", + quantity: "1", + appliedDiscounts: [ + { + uid: "9zr9S4dxvPAixvn0lpa1VC", + discountUid: "zGsRZP69aqSSR9lq9euSPB", + appliedMoney: { + amount: BigInt("250"), + currency: "USD", + }, + }, + ], + basePriceMoney: { + amount: BigInt("500"), + currency: "USD", + }, + variationTotalPriceMoney: { + amount: BigInt("500"), + currency: "USD", + }, + grossSalesMoney: { + amount: BigInt("500"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("250"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("250"), + currency: "USD", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + { + uid: "mumY8Nun4BC5aKe2yyx5a", + name: "Item 2", + quantity: "2", + appliedDiscounts: [ + { + uid: "qa8LwwZK82FgSEkQc2HYVC", + discountUid: "zGsRZP69aqSSR9lq9euSPB", + appliedMoney: { + amount: BigInt("300"), + currency: "USD", + }, + }, + ], + basePriceMoney: { + amount: BigInt("300"), + currency: "USD", + }, + variationTotalPriceMoney: { + amount: BigInt("600"), + currency: "USD", + }, + grossSalesMoney: { + amount: BigInt("600"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("300"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("300"), + currency: "USD", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + ], + taxes: [{}], + discounts: [ + { + uid: "zGsRZP69aqSSR9lq9euSPB", + name: "50% Off", + type: "FIXED_PERCENTAGE", + percentage: "50", + appliedMoney: { + amount: BigInt("550"), + currency: "USD", + }, + scope: "ORDER", + }, + ], + serviceCharges: [{}], + fulfillments: [{}], + returns: [{}], + netAmounts: { + totalMoney: { + amount: BigInt("550"), + currency: "USD", + }, + taxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + discountMoney: { + amount: BigInt("550"), + currency: "USD", + }, + tipMoney: { + amount: BigInt("0"), + currency: "USD", + }, + serviceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + roundingAdjustment: { + uid: "uid", + name: "name", + }, + tenders: [ + { + type: "CARD", + }, + ], + refunds: [ + { + id: "id", + locationId: "location_id", + reason: "reason", + amountMoney: {}, + status: "PENDING", + }, + ], + metadata: { + key: "value", + }, + createdAt: "2020-05-18T16:30:49.614Z", + updatedAt: "2020-05-18T16:30:49.614Z", + closedAt: "closed_at", + state: "OPEN", + version: 1, + totalMoney: { + amount: BigInt("550"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("550"), + currency: "USD", + }, + totalTipMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + ticketName: "ticket_name", + pricingOptions: { + autoApplyDiscounts: true, + autoApplyTaxes: true, + }, + rewards: [ + { + id: "id", + rewardTierId: "reward_tier_id", + }, + ], + netAmountDueMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + order: { + location_id: "location_id", + line_items: [ + { + uid: "cookie_uid", + name: "COOKIE", + quantity: "2", + base_price_money: { amount: BigInt(200), currency: "USD" }, + }, + ], + version: 1, + }, + fields_to_clear: ["discounts"], + idempotency_key: "UNIQUE_STRING", + }; + const rawResponseBody = { + order: { + id: "DREk7wJcyXNHqULq8JJ2iPAsluJZY", + location_id: "MXVQSVNDGN3C8", + reference_id: "reference_id", + source: { name: "Cookies" }, + customer_id: "customer_id", + line_items: [ + { + uid: "EuYkakhmu3ksHIds5Hiot", + name: "Small Coffee", + quantity: "1", + base_price_money: { amount: BigInt(500), currency: "USD" }, + variation_total_price_money: { amount: BigInt(500), currency: "USD" }, + gross_sales_money: { amount: BigInt(500), currency: "USD" }, + total_tax_money: { amount: BigInt(0), currency: "USD" }, + total_discount_money: { amount: BigInt(0), currency: "USD" }, + total_money: { amount: BigInt(500), currency: "USD" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + { + uid: "cookie_uid", + name: "COOKIE", + quantity: "2", + base_price_money: { amount: BigInt(200), currency: "USD" }, + variation_total_price_money: { amount: BigInt(400), currency: "USD" }, + gross_sales_money: { amount: BigInt(400), currency: "USD" }, + total_tax_money: { amount: BigInt(0), currency: "USD" }, + total_discount_money: { amount: BigInt(0), currency: "USD" }, + total_money: { amount: BigInt(400), currency: "USD" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + ], + taxes: [{}], + discounts: [{}], + service_charges: [{}], + fulfillments: [{}], + returns: [{}], + net_amounts: { + total_money: { amount: BigInt(900), currency: "USD" }, + tax_money: { amount: BigInt(0), currency: "USD" }, + discount_money: { amount: BigInt(0), currency: "USD" }, + service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + rounding_adjustment: { uid: "uid", name: "name" }, + tenders: [{ type: "CARD" }], + refunds: [ + { id: "id", location_id: "location_id", reason: "reason", amount_money: {}, status: "PENDING" }, + ], + metadata: { key: "value" }, + created_at: "2019-08-23T18:26:18.243Z", + updated_at: "2019-08-23T18:33:47.523Z", + closed_at: "closed_at", + state: "OPEN", + version: 2, + total_money: { amount: BigInt(900), currency: "USD" }, + total_tax_money: { amount: BigInt(0), currency: "USD" }, + total_discount_money: { amount: BigInt(0), currency: "USD" }, + total_tip_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + ticket_name: "ticket_name", + pricing_options: { auto_apply_discounts: true, auto_apply_taxes: true }, + rewards: [{ id: "id", reward_tier_id: "reward_tier_id" }], + net_amount_due_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .put("/v2/orders/order_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.orders.update({ + orderId: "order_id", + order: { + locationId: "location_id", + lineItems: [ + { + uid: "cookie_uid", + name: "COOKIE", + quantity: "2", + basePriceMoney: { + amount: BigInt("200"), + currency: "USD", + }, + }, + ], + version: 1, + }, + fieldsToClear: ["discounts"], + idempotencyKey: "UNIQUE_STRING", + }); + expect(response).toEqual({ + order: { + id: "DREk7wJcyXNHqULq8JJ2iPAsluJZY", + locationId: "MXVQSVNDGN3C8", + referenceId: "reference_id", + source: { + name: "Cookies", + }, + customerId: "customer_id", + lineItems: [ + { + uid: "EuYkakhmu3ksHIds5Hiot", + name: "Small Coffee", + quantity: "1", + basePriceMoney: { + amount: BigInt("500"), + currency: "USD", + }, + variationTotalPriceMoney: { + amount: BigInt("500"), + currency: "USD", + }, + grossSalesMoney: { + amount: BigInt("500"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("500"), + currency: "USD", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + { + uid: "cookie_uid", + name: "COOKIE", + quantity: "2", + basePriceMoney: { + amount: BigInt("200"), + currency: "USD", + }, + variationTotalPriceMoney: { + amount: BigInt("400"), + currency: "USD", + }, + grossSalesMoney: { + amount: BigInt("400"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("400"), + currency: "USD", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + ], + taxes: [{}], + discounts: [{}], + serviceCharges: [{}], + fulfillments: [{}], + returns: [{}], + netAmounts: { + totalMoney: { + amount: BigInt("900"), + currency: "USD", + }, + taxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + discountMoney: { + amount: BigInt("0"), + currency: "USD", + }, + serviceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + roundingAdjustment: { + uid: "uid", + name: "name", + }, + tenders: [ + { + type: "CARD", + }, + ], + refunds: [ + { + id: "id", + locationId: "location_id", + reason: "reason", + amountMoney: {}, + status: "PENDING", + }, + ], + metadata: { + key: "value", + }, + createdAt: "2019-08-23T18:26:18.243Z", + updatedAt: "2019-08-23T18:33:47.523Z", + closedAt: "closed_at", + state: "OPEN", + version: 2, + totalMoney: { + amount: BigInt("900"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalTipMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + ticketName: "ticket_name", + pricingOptions: { + autoApplyDiscounts: true, + autoApplyTaxes: true, + }, + rewards: [ + { + id: "id", + rewardTierId: "reward_tier_id", + }, + ], + netAmountDueMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("pay", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "c043a359-7ad9-4136-82a9-c3f1d66dcbff", + payment_ids: ["EnZdNAlWCmfh6Mt5FMNST1o7taB", "0LRiVlbXVwe8ozu4KbZxd12mvaB"], + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + order: { + id: "lgwOlEityYPJtcuvKTVKT1pA986YY", + location_id: "P3CCK6HSNDAS7", + reference_id: "reference_id", + source: { name: "Source Name" }, + customer_id: "customer_id", + line_items: [ + { + uid: "QW6kofLHJK7JEKMjlSVP5C", + name: "Item 1", + quantity: "1", + base_price_money: { amount: BigInt(500), currency: "USD" }, + gross_sales_money: { amount: BigInt(500), currency: "USD" }, + total_tax_money: { amount: BigInt(0), currency: "USD" }, + total_discount_money: { amount: BigInt(0), currency: "USD" }, + total_money: { amount: BigInt(500), currency: "USD" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + { + uid: "zhw8MNfRGdFQMI2WE1UBJD", + name: "Item 2", + quantity: "2", + base_price_money: { amount: BigInt(750), currency: "USD" }, + gross_sales_money: { amount: BigInt(1500), currency: "USD" }, + total_tax_money: { amount: BigInt(0), currency: "USD" }, + total_discount_money: { amount: BigInt(0), currency: "USD" }, + total_money: { amount: BigInt(1500), currency: "USD" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + ], + taxes: [{}], + discounts: [{}], + service_charges: [{}], + fulfillments: [{}], + returns: [{}], + net_amounts: { + total_money: { amount: BigInt(2000), currency: "USD" }, + tax_money: { amount: BigInt(0), currency: "USD" }, + discount_money: { amount: BigInt(0), currency: "USD" }, + tip_money: { amount: BigInt(0), currency: "USD" }, + service_charge_money: { amount: BigInt(0), currency: "USD" }, + }, + rounding_adjustment: { uid: "uid", name: "name" }, + tenders: [ + { + id: "EnZdNAlWCmfh6Mt5FMNST1o7taB", + location_id: "P3CCK6HSNDAS7", + transaction_id: "lgwOlEityYPJtcuvKTVKT1pA986YY", + created_at: "2019-08-06T02:47:36.293Z", + amount_money: { amount: BigInt(1000), currency: "USD" }, + type: "CARD", + card_details: { + status: "CAPTURED", + card: { + card_brand: "VISA", + last_4: "1111", + exp_month: BigInt(2), + exp_year: BigInt(2022), + fingerprint: "sq-1-n_BL15KP87ClDa4-h2nXOI0fp5VnxNH6hfhzqhptTfAgxgLuGFcg6jIPngDz4IkkTQ", + }, + entry_method: "KEYED", + }, + payment_id: "EnZdNAlWCmfh6Mt5FMNST1o7taB", + }, + { + id: "0LRiVlbXVwe8ozu4KbZxd12mvaB", + location_id: "P3CCK6HSNDAS7", + transaction_id: "lgwOlEityYPJtcuvKTVKT1pA986YY", + created_at: "2019-08-06T02:47:36.809Z", + amount_money: { amount: BigInt(1000), currency: "USD" }, + type: "CARD", + card_details: { + status: "CAPTURED", + card: { + card_brand: "VISA", + last_4: "1111", + exp_month: BigInt(2), + exp_year: BigInt(2022), + fingerprint: "sq-1-n_BL15KP87ClDa4-h2nXOI0fp5VnxNH6hfhzqhptTfAgxgLuGFcg6jIPngDz4IkkTQ", + }, + entry_method: "KEYED", + }, + payment_id: "0LRiVlbXVwe8ozu4KbZxd12mvaB", + }, + ], + refunds: [ + { id: "id", location_id: "location_id", reason: "reason", amount_money: {}, status: "PENDING" }, + ], + metadata: { key: "value" }, + created_at: "2019-08-06T02:47:35.693Z", + updated_at: "2019-08-06T02:47:37.140Z", + closed_at: "2019-08-06T02:47:37.140Z", + state: "COMPLETED", + version: 4, + total_money: { amount: BigInt(2000), currency: "USD" }, + total_tax_money: { amount: BigInt(0), currency: "USD" }, + total_discount_money: { amount: BigInt(0), currency: "USD" }, + total_tip_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + total_service_charge_money: { amount: BigInt(0), currency: "USD" }, + ticket_name: "ticket_name", + pricing_options: { auto_apply_discounts: true, auto_apply_taxes: true }, + rewards: [{ id: "id", reward_tier_id: "reward_tier_id" }], + net_amount_due_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + }, + }; + server + .mockEndpoint() + .post("/v2/orders/order_id/pay") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.orders.pay({ + orderId: "order_id", + idempotencyKey: "c043a359-7ad9-4136-82a9-c3f1d66dcbff", + paymentIds: ["EnZdNAlWCmfh6Mt5FMNST1o7taB", "0LRiVlbXVwe8ozu4KbZxd12mvaB"], + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + order: { + id: "lgwOlEityYPJtcuvKTVKT1pA986YY", + locationId: "P3CCK6HSNDAS7", + referenceId: "reference_id", + source: { + name: "Source Name", + }, + customerId: "customer_id", + lineItems: [ + { + uid: "QW6kofLHJK7JEKMjlSVP5C", + name: "Item 1", + quantity: "1", + basePriceMoney: { + amount: BigInt("500"), + currency: "USD", + }, + grossSalesMoney: { + amount: BigInt("500"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("500"), + currency: "USD", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + { + uid: "zhw8MNfRGdFQMI2WE1UBJD", + name: "Item 2", + quantity: "2", + basePriceMoney: { + amount: BigInt("750"), + currency: "USD", + }, + grossSalesMoney: { + amount: BigInt("1500"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("1500"), + currency: "USD", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + ], + taxes: [{}], + discounts: [{}], + serviceCharges: [{}], + fulfillments: [{}], + returns: [{}], + netAmounts: { + totalMoney: { + amount: BigInt("2000"), + currency: "USD", + }, + taxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + discountMoney: { + amount: BigInt("0"), + currency: "USD", + }, + tipMoney: { + amount: BigInt("0"), + currency: "USD", + }, + serviceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + }, + roundingAdjustment: { + uid: "uid", + name: "name", + }, + tenders: [ + { + id: "EnZdNAlWCmfh6Mt5FMNST1o7taB", + locationId: "P3CCK6HSNDAS7", + transactionId: "lgwOlEityYPJtcuvKTVKT1pA986YY", + createdAt: "2019-08-06T02:47:36.293Z", + amountMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + type: "CARD", + cardDetails: { + status: "CAPTURED", + card: { + cardBrand: "VISA", + last4: "1111", + expMonth: BigInt("2"), + expYear: BigInt("2022"), + fingerprint: "sq-1-n_BL15KP87ClDa4-h2nXOI0fp5VnxNH6hfhzqhptTfAgxgLuGFcg6jIPngDz4IkkTQ", + }, + entryMethod: "KEYED", + }, + paymentId: "EnZdNAlWCmfh6Mt5FMNST1o7taB", + }, + { + id: "0LRiVlbXVwe8ozu4KbZxd12mvaB", + locationId: "P3CCK6HSNDAS7", + transactionId: "lgwOlEityYPJtcuvKTVKT1pA986YY", + createdAt: "2019-08-06T02:47:36.809Z", + amountMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + type: "CARD", + cardDetails: { + status: "CAPTURED", + card: { + cardBrand: "VISA", + last4: "1111", + expMonth: BigInt("2"), + expYear: BigInt("2022"), + fingerprint: "sq-1-n_BL15KP87ClDa4-h2nXOI0fp5VnxNH6hfhzqhptTfAgxgLuGFcg6jIPngDz4IkkTQ", + }, + entryMethod: "KEYED", + }, + paymentId: "0LRiVlbXVwe8ozu4KbZxd12mvaB", + }, + ], + refunds: [ + { + id: "id", + locationId: "location_id", + reason: "reason", + amountMoney: {}, + status: "PENDING", + }, + ], + metadata: { + key: "value", + }, + createdAt: "2019-08-06T02:47:35.693Z", + updatedAt: "2019-08-06T02:47:37.140Z", + closedAt: "2019-08-06T02:47:37.140Z", + state: "COMPLETED", + version: 4, + totalMoney: { + amount: BigInt("2000"), + currency: "USD", + }, + totalTaxMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalDiscountMoney: { + amount: BigInt("0"), + currency: "USD", + }, + totalTipMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + totalServiceChargeMoney: { + amount: BigInt("0"), + currency: "USD", + }, + ticketName: "ticket_name", + pricingOptions: { + autoApplyDiscounts: true, + autoApplyTaxes: true, + }, + rewards: [ + { + id: "id", + rewardTierId: "reward_tier_id", + }, + ], + netAmountDueMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + }, + }); + }); +}); diff --git a/tests/wire/orders/customAttributeDefinitions.test.ts b/tests/wire/orders/customAttributeDefinitions.test.ts new file mode 100644 index 000000000..06546ebac --- /dev/null +++ b/tests/wire/orders/customAttributeDefinitions.test.ts @@ -0,0 +1,231 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("CustomAttributeDefinitions", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + custom_attribute_definition: { + key: "cover-count", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.Number", + }, + name: "Cover count", + description: "The number of people seated at a table", + visibility: "VISIBILITY_READ_WRITE_VALUES", + }, + idempotency_key: "IDEMPOTENCY_KEY", + }; + const rawResponseBody = { + custom_attribute_definition: { + key: "cover-count", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.Number", + }, + name: "Cover count", + description: "The number of people seated at a table", + visibility: "VISIBILITY_READ_WRITE_VALUES", + version: 1, + updated_at: "2022-10-06T16:53:23.141Z", + created_at: "2022-10-06T16:53:23.141Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/orders/custom-attribute-definitions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.orders.customAttributeDefinitions.create({ + customAttributeDefinition: { + key: "cover-count", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.Number", + }, + name: "Cover count", + description: "The number of people seated at a table", + visibility: "VISIBILITY_READ_WRITE_VALUES", + }, + idempotencyKey: "IDEMPOTENCY_KEY", + }); + expect(response).toEqual({ + customAttributeDefinition: { + key: "cover-count", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.Number", + }, + name: "Cover count", + description: "The number of people seated at a table", + visibility: "VISIBILITY_READ_WRITE_VALUES", + version: 1, + updatedAt: "2022-10-06T16:53:23.141Z", + createdAt: "2022-10-06T16:53:23.141Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + custom_attribute_definition: { + key: "cover-count", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.Number", + }, + name: "Cover count", + description: "The number of people seated at a table", + visibility: "VISIBILITY_READ_WRITE_VALUES", + version: 1, + updated_at: "2022-10-06T16:53:23.141Z", + created_at: "2022-10-06T16:53:23.141Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/orders/custom-attribute-definitions/key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.orders.customAttributeDefinitions.get({ + key: "key", + }); + expect(response).toEqual({ + customAttributeDefinition: { + key: "cover-count", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.Number", + }, + name: "Cover count", + description: "The number of people seated at a table", + visibility: "VISIBILITY_READ_WRITE_VALUES", + version: 1, + updatedAt: "2022-10-06T16:53:23.141Z", + createdAt: "2022-10-06T16:53:23.141Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + custom_attribute_definition: { key: "cover-count", visibility: "VISIBILITY_READ_ONLY", version: 1 }, + idempotency_key: "IDEMPOTENCY_KEY", + }; + const rawResponseBody = { + custom_attribute_definition: { + key: "cover-count", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.Number", + }, + name: "Cover count", + description: "The number of people seated at a table", + visibility: "VISIBILITY_READ_ONLY", + version: 2, + updated_at: "2022-11-16T17:44:11.436Z", + created_at: "2022-11-16T16:53:23.141Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .put("/v2/orders/custom-attribute-definitions/key") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.orders.customAttributeDefinitions.update({ + key: "key", + customAttributeDefinition: { + key: "cover-count", + visibility: "VISIBILITY_READ_ONLY", + version: 1, + }, + idempotencyKey: "IDEMPOTENCY_KEY", + }); + expect(response).toEqual({ + customAttributeDefinition: { + key: "cover-count", + schema: { + ref: "https://developer-production-s.squarecdn.com/schemas/v1/common.json#squareup.common.Number", + }, + name: "Cover count", + description: "The number of people seated at a table", + visibility: "VISIBILITY_READ_ONLY", + version: 2, + updatedAt: "2022-11-16T17:44:11.436Z", + createdAt: "2022-11-16T16:53:23.141Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/orders/custom-attribute-definitions/key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.orders.customAttributeDefinitions.delete({ + key: "key", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/orders/customAttributes.test.ts b/tests/wire/orders/customAttributes.test.ts new file mode 100644 index 000000000..e7734114b --- /dev/null +++ b/tests/wire/orders/customAttributes.test.ts @@ -0,0 +1,363 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("CustomAttributes", () => { + test("batchDelete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + values: { + "cover-count": { key: "cover-count", order_id: "7BbXGEIWNldxAzrtGf9GPVZTwZ4F" }, + "table-number": { key: "table-number", order_id: "7BbXGEIWNldxAzrtGf9GPVZTwZ4F" }, + }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + values: { + "cover-count": { errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }] }, + "table-number": { errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }] }, + }, + }; + server + .mockEndpoint() + .post("/v2/orders/custom-attributes/bulk-delete") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.orders.customAttributes.batchDelete({ + values: { + "cover-count": { + key: "cover-count", + orderId: "7BbXGEIWNldxAzrtGf9GPVZTwZ4F", + }, + "table-number": { + key: "table-number", + orderId: "7BbXGEIWNldxAzrtGf9GPVZTwZ4F", + }, + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + values: { + "cover-count": { + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + "table-number": { + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + }, + }); + }); + + test("batchUpsert", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + values: { + "cover-count": { + custom_attribute: { key: "cover-count", value: "6", version: 2 }, + order_id: "7BbXGEIWNldxAzrtGf9GPVZTwZ4F", + }, + "table-number": { + custom_attribute: { key: "table-number", value: "11", version: 4 }, + order_id: "7BbXGEIWNldxAzrtGf9GPVZTwZ4F", + }, + }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + values: { + "cover-count": { + custom_attribute: { + key: "cover-count", + value: "6", + visibility: "VISIBILITY_READ_WRITE_VALUES", + updated_at: "2022-11-22T21:28:35.721Z", + created_at: "2022-11-22T21:27:33.429Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + "table-number": { + custom_attribute: { + key: "table-number", + value: "11", + visibility: "VISIBILITY_HIDDEN", + updated_at: "2022-11-22T21:28:35.726Z", + created_at: "2022-11-22T21:24:57.823Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + }, + }; + server + .mockEndpoint() + .post("/v2/orders/custom-attributes/bulk-upsert") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.orders.customAttributes.batchUpsert({ + values: { + "cover-count": { + customAttribute: { + key: "cover-count", + value: "6", + version: 2, + }, + orderId: "7BbXGEIWNldxAzrtGf9GPVZTwZ4F", + }, + "table-number": { + customAttribute: { + key: "table-number", + value: "11", + version: 4, + }, + orderId: "7BbXGEIWNldxAzrtGf9GPVZTwZ4F", + }, + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + values: { + "cover-count": { + customAttribute: { + key: "cover-count", + value: "6", + visibility: "VISIBILITY_READ_WRITE_VALUES", + updatedAt: "2022-11-22T21:28:35.721Z", + createdAt: "2022-11-22T21:27:33.429Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + "table-number": { + customAttribute: { + key: "table-number", + value: "11", + visibility: "VISIBILITY_HIDDEN", + updatedAt: "2022-11-22T21:28:35.726Z", + createdAt: "2022-11-22T21:24:57.823Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + }, + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + custom_attribute: { + key: "cover-count", + value: "6", + version: 1, + visibility: "VISIBILITY_READ_WRITE_VALUES", + definition: { + key: "key", + schema: { key: "value" }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updated_at: "updated_at", + created_at: "created_at", + }, + updated_at: "2022-11-22T21:28:35.721Z", + created_at: "2022-11-22T21:27:33.429Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/orders/order_id/custom-attributes/custom_attribute_key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.orders.customAttributes.get({ + orderId: "order_id", + customAttributeKey: "custom_attribute_key", + }); + expect(response).toEqual({ + customAttribute: { + key: "cover-count", + value: "6", + version: 1, + visibility: "VISIBILITY_READ_WRITE_VALUES", + definition: { + key: "key", + schema: { + key: "value", + }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updatedAt: "updated_at", + createdAt: "created_at", + }, + updatedAt: "2022-11-22T21:28:35.721Z", + createdAt: "2022-11-22T21:27:33.429Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("upsert", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { custom_attribute: { key: "table-number", value: "42", version: 1 } }; + const rawResponseBody = { + custom_attribute: { + key: "table-number", + value: "42", + version: 1, + visibility: "VISIBILITY_READ_WRITE_VALUES", + definition: { + key: "key", + schema: { key: "value" }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updated_at: "updated_at", + created_at: "created_at", + }, + updated_at: "2022-10-06T20:41:22.673Z", + created_at: "2022-10-06T20:41:22.673Z", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/orders/order_id/custom-attributes/custom_attribute_key") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.orders.customAttributes.upsert({ + orderId: "order_id", + customAttributeKey: "custom_attribute_key", + customAttribute: { + key: "table-number", + value: "42", + version: 1, + }, + }); + expect(response).toEqual({ + customAttribute: { + key: "table-number", + value: "42", + version: 1, + visibility: "VISIBILITY_READ_WRITE_VALUES", + definition: { + key: "key", + schema: { + key: "value", + }, + name: "name", + description: "description", + visibility: "VISIBILITY_HIDDEN", + version: 1, + updatedAt: "updated_at", + createdAt: "created_at", + }, + updatedAt: "2022-10-06T20:41:22.673Z", + createdAt: "2022-10-06T20:41:22.673Z", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/orders/order_id/custom-attributes/custom_attribute_key") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.orders.customAttributes.delete({ + orderId: "order_id", + customAttributeKey: "custom_attribute_key", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/payments.test.ts b/tests/wire/payments.test.ts new file mode 100644 index 000000000..093a49de0 --- /dev/null +++ b/tests/wire/payments.test.ts @@ -0,0 +1,1726 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Payments", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + source_id: "ccof:GaJGNaZa8x4OgDJn4GB", + idempotency_key: "7b0f3ec5-086a-4871-8f13-3c81b3875218", + amount_money: { amount: BigInt(1000), currency: "USD" }, + app_fee_money: { amount: BigInt(10), currency: "USD" }, + autocomplete: true, + customer_id: "W92WH6P11H4Z77CTET0RNTGFW8", + location_id: "L88917AVBK2S5", + reference_id: "123456", + note: "Brief description", + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + payment: { + id: "R2B3Z8WMVt3EAmzYWLZvz7Y69EbZY", + created_at: "2021-10-13T21:14:29.577Z", + updated_at: "2021-10-13T21:14:30.504Z", + amount_money: { amount: BigInt(1000), currency: "USD" }, + tip_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + total_money: { amount: BigInt(1000), currency: "USD" }, + app_fee_money: { amount: BigInt(10), currency: "USD" }, + approved_money: { amount: BigInt(1000), currency: "USD" }, + processing_fee: [{}], + refunded_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + status: "COMPLETED", + delay_duration: "PT168H", + delay_action: "CANCEL", + delayed_until: "2021-10-20T21:14:29.577Z", + source_type: "CARD", + card_details: { + status: "CAPTURED", + card: { + card_brand: "VISA", + last_4: "1111", + exp_month: BigInt(11), + exp_year: BigInt(2022), + fingerprint: "sq-1-Hxim77tbdcbGejOejnoAklBVJed2YFLTmirfl8Q5XZzObTc8qY_U8RkwzoNL8dCEcQ", + card_type: "DEBIT", + prepaid_type: "NOT_PREPAID", + bin: "411111", + }, + entry_method: "ON_FILE", + cvv_status: "CVV_ACCEPTED", + avs_status: "AVS_ACCEPTED", + auth_result_code: "vNEn2f", + application_identifier: "application_identifier", + application_name: "application_name", + application_cryptogram: "application_cryptogram", + verification_method: "verification_method", + verification_results: "verification_results", + statement_description: "SQ *EXAMPLE TEST GOSQ.C", + card_payment_timeline: { + authorized_at: "2021-10-13T21:14:29.732Z", + captured_at: "2021-10-13T21:14:30.504Z", + }, + refund_requires_card_presence: true, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + cash_details: { buyer_supplied_money: {} }, + bank_account_details: { + bank_name: "bank_name", + transfer_type: "transfer_type", + account_ownership_type: "account_ownership_type", + fingerprint: "fingerprint", + country: "country", + statement_description: "statement_description", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + external_details: { type: "type", source: "source", source_id: "source_id" }, + wallet_details: { status: "status", brand: "brand" }, + buy_now_pay_later_details: { brand: "brand" }, + square_account_details: { + payment_source_token: "payment_source_token", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + location_id: "L88917AVBK2S5", + order_id: "pRsjRTgFWATl7so6DxdKBJa7ssbZY", + reference_id: "123456", + customer_id: "W92WH6P11H4Z77CTET0RNTGFW8", + employee_id: "employee_id", + team_member_id: "team_member_id", + refund_ids: ["refund_ids"], + risk_evaluation: { created_at: "2021-10-13T21:14:30.423Z", risk_level: "NORMAL" }, + terminal_checkout_id: "terminal_checkout_id", + buyer_email_address: "buyer_email_address", + billing_address: { + address_line_1: "address_line_1", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "administrative_district_level_1", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "postal_code", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + shipping_address: { + address_line_1: "address_line_1", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "administrative_district_level_1", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "postal_code", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + note: "Brief Description", + statement_description_identifier: "statement_description_identifier", + capabilities: ["capabilities"], + receipt_number: "R2B3", + receipt_url: "https://squareup.com/receipt/preview/EXAMPLE_RECEIPT_ID", + device_details: { + device_id: "device_id", + device_installation_id: "device_installation_id", + device_name: "device_name", + }, + application_details: { + square_product: "ECOMMERCE_API", + application_id: "sq0ids-TcgftTEtKxJTRF1lCFJ9TA", + }, + is_offline_payment: true, + offline_payment_details: { client_created_at: "client_created_at" }, + version_token: "TPtNEOBOa6Qq6E3C3IjckSVOM6b3hMbfhjvTxHBQUsB6o", + }, + }; + server + .mockEndpoint() + .post("/v2/payments") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.payments.create({ + sourceId: "ccof:GaJGNaZa8x4OgDJn4GB", + idempotencyKey: "7b0f3ec5-086a-4871-8f13-3c81b3875218", + amountMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + appFeeMoney: { + amount: BigInt("10"), + currency: "USD", + }, + autocomplete: true, + customerId: "W92WH6P11H4Z77CTET0RNTGFW8", + locationId: "L88917AVBK2S5", + referenceId: "123456", + note: "Brief description", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + payment: { + id: "R2B3Z8WMVt3EAmzYWLZvz7Y69EbZY", + createdAt: "2021-10-13T21:14:29.577Z", + updatedAt: "2021-10-13T21:14:30.504Z", + amountMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + tipMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + totalMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + appFeeMoney: { + amount: BigInt("10"), + currency: "USD", + }, + approvedMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + processingFee: [{}], + refundedMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + status: "COMPLETED", + delayDuration: "PT168H", + delayAction: "CANCEL", + delayedUntil: "2021-10-20T21:14:29.577Z", + sourceType: "CARD", + cardDetails: { + status: "CAPTURED", + card: { + cardBrand: "VISA", + last4: "1111", + expMonth: BigInt("11"), + expYear: BigInt("2022"), + fingerprint: "sq-1-Hxim77tbdcbGejOejnoAklBVJed2YFLTmirfl8Q5XZzObTc8qY_U8RkwzoNL8dCEcQ", + cardType: "DEBIT", + prepaidType: "NOT_PREPAID", + bin: "411111", + }, + entryMethod: "ON_FILE", + cvvStatus: "CVV_ACCEPTED", + avsStatus: "AVS_ACCEPTED", + authResultCode: "vNEn2f", + applicationIdentifier: "application_identifier", + applicationName: "application_name", + applicationCryptogram: "application_cryptogram", + verificationMethod: "verification_method", + verificationResults: "verification_results", + statementDescription: "SQ *EXAMPLE TEST GOSQ.C", + cardPaymentTimeline: { + authorizedAt: "2021-10-13T21:14:29.732Z", + capturedAt: "2021-10-13T21:14:30.504Z", + }, + refundRequiresCardPresence: true, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + cashDetails: { + buyerSuppliedMoney: {}, + }, + bankAccountDetails: { + bankName: "bank_name", + transferType: "transfer_type", + accountOwnershipType: "account_ownership_type", + fingerprint: "fingerprint", + country: "country", + statementDescription: "statement_description", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + externalDetails: { + type: "type", + source: "source", + sourceId: "source_id", + }, + walletDetails: { + status: "status", + brand: "brand", + }, + buyNowPayLaterDetails: { + brand: "brand", + }, + squareAccountDetails: { + paymentSourceToken: "payment_source_token", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + locationId: "L88917AVBK2S5", + orderId: "pRsjRTgFWATl7so6DxdKBJa7ssbZY", + referenceId: "123456", + customerId: "W92WH6P11H4Z77CTET0RNTGFW8", + employeeId: "employee_id", + teamMemberId: "team_member_id", + refundIds: ["refund_ids"], + riskEvaluation: { + createdAt: "2021-10-13T21:14:30.423Z", + riskLevel: "NORMAL", + }, + terminalCheckoutId: "terminal_checkout_id", + buyerEmailAddress: "buyer_email_address", + billingAddress: { + addressLine1: "address_line_1", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "administrative_district_level_1", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "postal_code", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + shippingAddress: { + addressLine1: "address_line_1", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "administrative_district_level_1", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "postal_code", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + note: "Brief Description", + statementDescriptionIdentifier: "statement_description_identifier", + capabilities: ["capabilities"], + receiptNumber: "R2B3", + receiptUrl: "https://squareup.com/receipt/preview/EXAMPLE_RECEIPT_ID", + deviceDetails: { + deviceId: "device_id", + deviceInstallationId: "device_installation_id", + deviceName: "device_name", + }, + applicationDetails: { + squareProduct: "ECOMMERCE_API", + applicationId: "sq0ids-TcgftTEtKxJTRF1lCFJ9TA", + }, + isOfflinePayment: true, + offlinePaymentDetails: { + clientCreatedAt: "client_created_at", + }, + versionToken: "TPtNEOBOa6Qq6E3C3IjckSVOM6b3hMbfhjvTxHBQUsB6o", + }, + }); + }); + + test("cancelByIdempotencyKey", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { idempotency_key: "a7e36d40-d24b-11e8-b568-0800200c9a66" }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/payments/cancel") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.payments.cancelByIdempotencyKey({ + idempotencyKey: "a7e36d40-d24b-11e8-b568-0800200c9a66", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + payment: { + id: "bP9mAsEMYPUGjjGNaNO5ZDVyLhSZY", + created_at: "2021-10-13T19:34:33.524Z", + updated_at: "2021-10-13T19:34:34.339Z", + amount_money: { amount: BigInt(555), currency: "USD" }, + tip_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + total_money: { amount: BigInt(555), currency: "USD" }, + app_fee_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + approved_money: { amount: BigInt(555), currency: "USD" }, + processing_fee: [ + { + effective_at: "2021-10-13T21:34:35.000Z", + type: "INITIAL", + amount_money: { amount: BigInt(34), currency: "USD" }, + }, + ], + refunded_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + status: "COMPLETED", + delay_duration: "PT168H", + delay_action: "CANCEL", + delayed_until: "2021-10-20T19:34:33.524Z", + source_type: "CARD", + card_details: { + status: "CAPTURED", + card: { + card_brand: "VISA", + last_4: "1111", + exp_month: BigInt(11), + exp_year: BigInt(2022), + fingerprint: "sq-1-Hxim77tbdcbGejOejnoAklBVJed2YFLTmirfl8Q5XZzObTc8qY_U8RkwzoNL8dCEcQ", + card_type: "DEBIT", + prepaid_type: "NOT_PREPAID", + bin: "411111", + }, + entry_method: "KEYED", + cvv_status: "CVV_ACCEPTED", + avs_status: "AVS_ACCEPTED", + auth_result_code: "2Nkw7q", + application_identifier: "application_identifier", + application_name: "application_name", + application_cryptogram: "application_cryptogram", + verification_method: "verification_method", + verification_results: "verification_results", + statement_description: "SQ *EXAMPLE TEST GOSQ.C", + card_payment_timeline: { + authorized_at: "2021-10-13T19:34:33.680Z", + captured_at: "2021-10-13T19:34:34.340Z", + }, + refund_requires_card_presence: true, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + cash_details: { buyer_supplied_money: {} }, + bank_account_details: { + bank_name: "bank_name", + transfer_type: "transfer_type", + account_ownership_type: "account_ownership_type", + fingerprint: "fingerprint", + country: "country", + statement_description: "statement_description", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + external_details: { type: "type", source: "source", source_id: "source_id" }, + wallet_details: { status: "status", brand: "brand" }, + buy_now_pay_later_details: { brand: "brand" }, + square_account_details: { + payment_source_token: "payment_source_token", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + location_id: "L88917AVBK2S5", + order_id: "d7eKah653Z579f3gVtjlxpSlmUcZY", + reference_id: "reference_id", + customer_id: "customer_id", + employee_id: "TMoK_ogh6rH1o4dV", + team_member_id: "TMoK_ogh6rH1o4dV", + refund_ids: ["refund_ids"], + risk_evaluation: { created_at: "created_at", risk_level: "PENDING" }, + terminal_checkout_id: "terminal_checkout_id", + buyer_email_address: "buyer_email_address", + billing_address: { + address_line_1: "address_line_1", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "administrative_district_level_1", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "postal_code", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + shipping_address: { + address_line_1: "address_line_1", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "administrative_district_level_1", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "postal_code", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + note: "Test Note", + statement_description_identifier: "statement_description_identifier", + capabilities: ["capabilities"], + receipt_number: "bP9m", + receipt_url: "https://squareup.com/receipt/preview/bP9mAsEMYPUGjjGNaNO5ZDVyLhSZY", + device_details: { + device_id: "device_id", + device_installation_id: "device_installation_id", + device_name: "device_name", + }, + application_details: { + square_product: "VIRTUAL_TERMINAL", + application_id: "sq0ids-Pw67AZAlLVB7hsRmwlJPuA", + }, + is_offline_payment: true, + offline_payment_details: { client_created_at: "client_created_at" }, + version_token: "56pRkL3slrzet2iQrTp9n0bdJVYTB9YEWdTNjQfZOPV6o", + }, + }; + server + .mockEndpoint() + .get("/v2/payments/payment_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.payments.get({ + paymentId: "payment_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + payment: { + id: "bP9mAsEMYPUGjjGNaNO5ZDVyLhSZY", + createdAt: "2021-10-13T19:34:33.524Z", + updatedAt: "2021-10-13T19:34:34.339Z", + amountMoney: { + amount: BigInt("555"), + currency: "USD", + }, + tipMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + totalMoney: { + amount: BigInt("555"), + currency: "USD", + }, + appFeeMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + approvedMoney: { + amount: BigInt("555"), + currency: "USD", + }, + processingFee: [ + { + effectiveAt: "2021-10-13T21:34:35.000Z", + type: "INITIAL", + amountMoney: { + amount: BigInt("34"), + currency: "USD", + }, + }, + ], + refundedMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + status: "COMPLETED", + delayDuration: "PT168H", + delayAction: "CANCEL", + delayedUntil: "2021-10-20T19:34:33.524Z", + sourceType: "CARD", + cardDetails: { + status: "CAPTURED", + card: { + cardBrand: "VISA", + last4: "1111", + expMonth: BigInt("11"), + expYear: BigInt("2022"), + fingerprint: "sq-1-Hxim77tbdcbGejOejnoAklBVJed2YFLTmirfl8Q5XZzObTc8qY_U8RkwzoNL8dCEcQ", + cardType: "DEBIT", + prepaidType: "NOT_PREPAID", + bin: "411111", + }, + entryMethod: "KEYED", + cvvStatus: "CVV_ACCEPTED", + avsStatus: "AVS_ACCEPTED", + authResultCode: "2Nkw7q", + applicationIdentifier: "application_identifier", + applicationName: "application_name", + applicationCryptogram: "application_cryptogram", + verificationMethod: "verification_method", + verificationResults: "verification_results", + statementDescription: "SQ *EXAMPLE TEST GOSQ.C", + cardPaymentTimeline: { + authorizedAt: "2021-10-13T19:34:33.680Z", + capturedAt: "2021-10-13T19:34:34.340Z", + }, + refundRequiresCardPresence: true, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + cashDetails: { + buyerSuppliedMoney: {}, + }, + bankAccountDetails: { + bankName: "bank_name", + transferType: "transfer_type", + accountOwnershipType: "account_ownership_type", + fingerprint: "fingerprint", + country: "country", + statementDescription: "statement_description", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + externalDetails: { + type: "type", + source: "source", + sourceId: "source_id", + }, + walletDetails: { + status: "status", + brand: "brand", + }, + buyNowPayLaterDetails: { + brand: "brand", + }, + squareAccountDetails: { + paymentSourceToken: "payment_source_token", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + locationId: "L88917AVBK2S5", + orderId: "d7eKah653Z579f3gVtjlxpSlmUcZY", + referenceId: "reference_id", + customerId: "customer_id", + employeeId: "TMoK_ogh6rH1o4dV", + teamMemberId: "TMoK_ogh6rH1o4dV", + refundIds: ["refund_ids"], + riskEvaluation: { + createdAt: "created_at", + riskLevel: "PENDING", + }, + terminalCheckoutId: "terminal_checkout_id", + buyerEmailAddress: "buyer_email_address", + billingAddress: { + addressLine1: "address_line_1", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "administrative_district_level_1", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "postal_code", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + shippingAddress: { + addressLine1: "address_line_1", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "administrative_district_level_1", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "postal_code", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + note: "Test Note", + statementDescriptionIdentifier: "statement_description_identifier", + capabilities: ["capabilities"], + receiptNumber: "bP9m", + receiptUrl: "https://squareup.com/receipt/preview/bP9mAsEMYPUGjjGNaNO5ZDVyLhSZY", + deviceDetails: { + deviceId: "device_id", + deviceInstallationId: "device_installation_id", + deviceName: "device_name", + }, + applicationDetails: { + squareProduct: "VIRTUAL_TERMINAL", + applicationId: "sq0ids-Pw67AZAlLVB7hsRmwlJPuA", + }, + isOfflinePayment: true, + offlinePaymentDetails: { + clientCreatedAt: "client_created_at", + }, + versionToken: "56pRkL3slrzet2iQrTp9n0bdJVYTB9YEWdTNjQfZOPV6o", + }, + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + payment: { + amount_money: { amount: BigInt(1000), currency: "USD" }, + tip_money: { amount: BigInt(100), currency: "USD" }, + version_token: "ODhwVQ35xwlzRuoZEwKXucfu7583sPTzK48c5zoGd0g6o", + }, + idempotency_key: "956f8b13-e4ec-45d6-85e8-d1d95ef0c5de", + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + payment: { + id: "1QjqpBVyrI9S4H9sTGDWU9JeiWdZY", + created_at: "2021-10-13T20:26:44.191Z", + updated_at: "2021-10-13T20:26:44.364Z", + amount_money: { amount: BigInt(1000), currency: "USD" }, + tip_money: { amount: BigInt(100), currency: "USD" }, + total_money: { amount: BigInt(1100), currency: "USD" }, + app_fee_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + approved_money: { amount: BigInt(1000), currency: "USD" }, + processing_fee: [{}], + refunded_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + status: "APPROVED", + delay_duration: "PT168H", + delay_action: "CANCEL", + delayed_until: "2021-10-20T20:26:44.191Z", + source_type: "CARD", + card_details: { + status: "AUTHORIZED", + card: { + card_brand: "VISA", + last_4: "1111", + exp_month: BigInt(11), + exp_year: BigInt(2022), + fingerprint: "sq-1-Hxim77tbdcbGejOejnoAklBVJed2YFLTmirfl8Q5XZzObTc8qY_U8RkwzoNL8dCEcQ", + card_type: "DEBIT", + prepaid_type: "NOT_PREPAID", + bin: "411111", + }, + entry_method: "ON_FILE", + cvv_status: "CVV_ACCEPTED", + avs_status: "AVS_ACCEPTED", + auth_result_code: "68aLBM", + application_identifier: "application_identifier", + application_name: "application_name", + application_cryptogram: "application_cryptogram", + verification_method: "verification_method", + verification_results: "verification_results", + statement_description: "SQ *EXAMPLE TEST GOSQ.C", + card_payment_timeline: { authorized_at: "2021-10-13T20:26:44.364Z" }, + refund_requires_card_presence: true, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + cash_details: { buyer_supplied_money: {} }, + bank_account_details: { + bank_name: "bank_name", + transfer_type: "transfer_type", + account_ownership_type: "account_ownership_type", + fingerprint: "fingerprint", + country: "country", + statement_description: "statement_description", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + external_details: { type: "type", source: "source", source_id: "source_id" }, + wallet_details: { status: "status", brand: "brand" }, + buy_now_pay_later_details: { brand: "brand" }, + square_account_details: { + payment_source_token: "payment_source_token", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + location_id: "L88917AVBK2S5", + order_id: "nUSN9TdxpiK3SrQg3wzmf6r8LP9YY", + reference_id: "reference_id", + customer_id: "W92WH6P11H4Z77CTET0RNTGFW8", + employee_id: "employee_id", + team_member_id: "team_member_id", + refund_ids: ["refund_ids"], + risk_evaluation: { created_at: "2021-10-13T20:26:45.271Z", risk_level: "NORMAL" }, + terminal_checkout_id: "terminal_checkout_id", + buyer_email_address: "buyer_email_address", + billing_address: { + address_line_1: "address_line_1", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "administrative_district_level_1", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "postal_code", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + shipping_address: { + address_line_1: "address_line_1", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "administrative_district_level_1", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "postal_code", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + note: "Example Note", + statement_description_identifier: "statement_description_identifier", + capabilities: ["EDIT_AMOUNT_UP", "EDIT_AMOUNT_DOWN", "EDIT_TIP_AMOUNT_UP", "EDIT_TIP_AMOUNT_DOWN"], + receipt_number: "1Qjq", + receipt_url: "receipt_url", + device_details: { + device_id: "device_id", + device_installation_id: "device_installation_id", + device_name: "device_name", + }, + application_details: { + square_product: "ECOMMERCE_API", + application_id: "sq0ids-TcgftTEtKxJTRF1lCFJ9TA", + }, + is_offline_payment: true, + offline_payment_details: { client_created_at: "client_created_at" }, + version_token: "rDrXnqiS7fJgexccgdpzmwqTiXui1aIKCp9EchZ7trE6o", + }, + }; + server + .mockEndpoint() + .put("/v2/payments/payment_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.payments.update({ + paymentId: "payment_id", + payment: { + amountMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + tipMoney: { + amount: BigInt("100"), + currency: "USD", + }, + versionToken: "ODhwVQ35xwlzRuoZEwKXucfu7583sPTzK48c5zoGd0g6o", + }, + idempotencyKey: "956f8b13-e4ec-45d6-85e8-d1d95ef0c5de", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + payment: { + id: "1QjqpBVyrI9S4H9sTGDWU9JeiWdZY", + createdAt: "2021-10-13T20:26:44.191Z", + updatedAt: "2021-10-13T20:26:44.364Z", + amountMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + tipMoney: { + amount: BigInt("100"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("1100"), + currency: "USD", + }, + appFeeMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + approvedMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + processingFee: [{}], + refundedMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + status: "APPROVED", + delayDuration: "PT168H", + delayAction: "CANCEL", + delayedUntil: "2021-10-20T20:26:44.191Z", + sourceType: "CARD", + cardDetails: { + status: "AUTHORIZED", + card: { + cardBrand: "VISA", + last4: "1111", + expMonth: BigInt("11"), + expYear: BigInt("2022"), + fingerprint: "sq-1-Hxim77tbdcbGejOejnoAklBVJed2YFLTmirfl8Q5XZzObTc8qY_U8RkwzoNL8dCEcQ", + cardType: "DEBIT", + prepaidType: "NOT_PREPAID", + bin: "411111", + }, + entryMethod: "ON_FILE", + cvvStatus: "CVV_ACCEPTED", + avsStatus: "AVS_ACCEPTED", + authResultCode: "68aLBM", + applicationIdentifier: "application_identifier", + applicationName: "application_name", + applicationCryptogram: "application_cryptogram", + verificationMethod: "verification_method", + verificationResults: "verification_results", + statementDescription: "SQ *EXAMPLE TEST GOSQ.C", + cardPaymentTimeline: { + authorizedAt: "2021-10-13T20:26:44.364Z", + }, + refundRequiresCardPresence: true, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + cashDetails: { + buyerSuppliedMoney: {}, + }, + bankAccountDetails: { + bankName: "bank_name", + transferType: "transfer_type", + accountOwnershipType: "account_ownership_type", + fingerprint: "fingerprint", + country: "country", + statementDescription: "statement_description", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + externalDetails: { + type: "type", + source: "source", + sourceId: "source_id", + }, + walletDetails: { + status: "status", + brand: "brand", + }, + buyNowPayLaterDetails: { + brand: "brand", + }, + squareAccountDetails: { + paymentSourceToken: "payment_source_token", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + locationId: "L88917AVBK2S5", + orderId: "nUSN9TdxpiK3SrQg3wzmf6r8LP9YY", + referenceId: "reference_id", + customerId: "W92WH6P11H4Z77CTET0RNTGFW8", + employeeId: "employee_id", + teamMemberId: "team_member_id", + refundIds: ["refund_ids"], + riskEvaluation: { + createdAt: "2021-10-13T20:26:45.271Z", + riskLevel: "NORMAL", + }, + terminalCheckoutId: "terminal_checkout_id", + buyerEmailAddress: "buyer_email_address", + billingAddress: { + addressLine1: "address_line_1", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "administrative_district_level_1", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "postal_code", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + shippingAddress: { + addressLine1: "address_line_1", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "administrative_district_level_1", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "postal_code", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + note: "Example Note", + statementDescriptionIdentifier: "statement_description_identifier", + capabilities: ["EDIT_AMOUNT_UP", "EDIT_AMOUNT_DOWN", "EDIT_TIP_AMOUNT_UP", "EDIT_TIP_AMOUNT_DOWN"], + receiptNumber: "1Qjq", + receiptUrl: "receipt_url", + deviceDetails: { + deviceId: "device_id", + deviceInstallationId: "device_installation_id", + deviceName: "device_name", + }, + applicationDetails: { + squareProduct: "ECOMMERCE_API", + applicationId: "sq0ids-TcgftTEtKxJTRF1lCFJ9TA", + }, + isOfflinePayment: true, + offlinePaymentDetails: { + clientCreatedAt: "client_created_at", + }, + versionToken: "rDrXnqiS7fJgexccgdpzmwqTiXui1aIKCp9EchZ7trE6o", + }, + }); + }); + + test("cancel", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + payment: { + id: "1QjqpBVyrI9S4H9sTGDWU9JeiWdZY", + created_at: "2021-10-13T20:26:44.191Z", + updated_at: "2021-10-13T20:31:21.597Z", + amount_money: { amount: BigInt(1000), currency: "USD" }, + tip_money: { amount: BigInt(100), currency: "USD" }, + total_money: { amount: BigInt(1100), currency: "USD" }, + app_fee_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + approved_money: { amount: BigInt(1000), currency: "USD" }, + processing_fee: [{}], + refunded_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + status: "CANCELED", + delay_duration: "PT168H", + delay_action: "CANCEL", + delayed_until: "2021-10-20T20:26:44.191Z", + source_type: "CARD", + card_details: { + status: "VOIDED", + card: { + card_brand: "VISA", + last_4: "1111", + exp_month: BigInt(11), + exp_year: BigInt(2022), + fingerprint: "sq-1-Hxim77tbdcbGejOejnoAklBVJed2YFLTmirfl8Q5XZzObTc8qY_U8RkwzoNL8dCEcQ", + card_type: "DEBIT", + prepaid_type: "NOT_PREPAID", + bin: "411111", + }, + entry_method: "ON_FILE", + cvv_status: "CVV_ACCEPTED", + avs_status: "AVS_ACCEPTED", + auth_result_code: "68aLBM", + application_identifier: "application_identifier", + application_name: "application_name", + application_cryptogram: "application_cryptogram", + verification_method: "verification_method", + verification_results: "verification_results", + statement_description: "SQ *EXAMPLE TEST GOSQ.C", + card_payment_timeline: { + authorized_at: "2021-10-13T20:26:44.364Z", + voided_at: "2021-10-13T20:31:21.597Z", + }, + refund_requires_card_presence: true, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + cash_details: { buyer_supplied_money: {} }, + bank_account_details: { + bank_name: "bank_name", + transfer_type: "transfer_type", + account_ownership_type: "account_ownership_type", + fingerprint: "fingerprint", + country: "country", + statement_description: "statement_description", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + external_details: { type: "type", source: "source", source_id: "source_id" }, + wallet_details: { status: "status", brand: "brand" }, + buy_now_pay_later_details: { brand: "brand" }, + square_account_details: { + payment_source_token: "payment_source_token", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + location_id: "L88917AVBK2S5", + order_id: "nUSN9TdxpiK3SrQg3wzmf6r8LP9YY", + reference_id: "reference_id", + customer_id: "W92WH6P11H4Z77CTET0RNTGFW8", + employee_id: "employee_id", + team_member_id: "team_member_id", + refund_ids: ["refund_ids"], + risk_evaluation: { created_at: "2021-10-13T20:26:45.271Z", risk_level: "NORMAL" }, + terminal_checkout_id: "terminal_checkout_id", + buyer_email_address: "buyer_email_address", + billing_address: { + address_line_1: "address_line_1", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "administrative_district_level_1", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "postal_code", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + shipping_address: { + address_line_1: "address_line_1", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "administrative_district_level_1", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "postal_code", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + note: "Example Note", + statement_description_identifier: "statement_description_identifier", + capabilities: ["capabilities"], + receipt_number: "receipt_number", + receipt_url: "receipt_url", + device_details: { + device_id: "device_id", + device_installation_id: "device_installation_id", + device_name: "device_name", + }, + application_details: { + square_product: "ECOMMERCE_API", + application_id: "sq0ids-TcgftTEtKxJTRF1lCFJ9TA", + }, + is_offline_payment: true, + offline_payment_details: { client_created_at: "client_created_at" }, + version_token: "N8AGYgEjCiY9Q57Jw7aVHEpBq8bzGCDCQMRX8Vs56N06o", + }, + }; + server + .mockEndpoint() + .post("/v2/payments/payment_id/cancel") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.payments.cancel({ + paymentId: "payment_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + payment: { + id: "1QjqpBVyrI9S4H9sTGDWU9JeiWdZY", + createdAt: "2021-10-13T20:26:44.191Z", + updatedAt: "2021-10-13T20:31:21.597Z", + amountMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + tipMoney: { + amount: BigInt("100"), + currency: "USD", + }, + totalMoney: { + amount: BigInt("1100"), + currency: "USD", + }, + appFeeMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + approvedMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + processingFee: [{}], + refundedMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + status: "CANCELED", + delayDuration: "PT168H", + delayAction: "CANCEL", + delayedUntil: "2021-10-20T20:26:44.191Z", + sourceType: "CARD", + cardDetails: { + status: "VOIDED", + card: { + cardBrand: "VISA", + last4: "1111", + expMonth: BigInt("11"), + expYear: BigInt("2022"), + fingerprint: "sq-1-Hxim77tbdcbGejOejnoAklBVJed2YFLTmirfl8Q5XZzObTc8qY_U8RkwzoNL8dCEcQ", + cardType: "DEBIT", + prepaidType: "NOT_PREPAID", + bin: "411111", + }, + entryMethod: "ON_FILE", + cvvStatus: "CVV_ACCEPTED", + avsStatus: "AVS_ACCEPTED", + authResultCode: "68aLBM", + applicationIdentifier: "application_identifier", + applicationName: "application_name", + applicationCryptogram: "application_cryptogram", + verificationMethod: "verification_method", + verificationResults: "verification_results", + statementDescription: "SQ *EXAMPLE TEST GOSQ.C", + cardPaymentTimeline: { + authorizedAt: "2021-10-13T20:26:44.364Z", + voidedAt: "2021-10-13T20:31:21.597Z", + }, + refundRequiresCardPresence: true, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + cashDetails: { + buyerSuppliedMoney: {}, + }, + bankAccountDetails: { + bankName: "bank_name", + transferType: "transfer_type", + accountOwnershipType: "account_ownership_type", + fingerprint: "fingerprint", + country: "country", + statementDescription: "statement_description", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + externalDetails: { + type: "type", + source: "source", + sourceId: "source_id", + }, + walletDetails: { + status: "status", + brand: "brand", + }, + buyNowPayLaterDetails: { + brand: "brand", + }, + squareAccountDetails: { + paymentSourceToken: "payment_source_token", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + locationId: "L88917AVBK2S5", + orderId: "nUSN9TdxpiK3SrQg3wzmf6r8LP9YY", + referenceId: "reference_id", + customerId: "W92WH6P11H4Z77CTET0RNTGFW8", + employeeId: "employee_id", + teamMemberId: "team_member_id", + refundIds: ["refund_ids"], + riskEvaluation: { + createdAt: "2021-10-13T20:26:45.271Z", + riskLevel: "NORMAL", + }, + terminalCheckoutId: "terminal_checkout_id", + buyerEmailAddress: "buyer_email_address", + billingAddress: { + addressLine1: "address_line_1", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "administrative_district_level_1", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "postal_code", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + shippingAddress: { + addressLine1: "address_line_1", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "administrative_district_level_1", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "postal_code", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + note: "Example Note", + statementDescriptionIdentifier: "statement_description_identifier", + capabilities: ["capabilities"], + receiptNumber: "receipt_number", + receiptUrl: "receipt_url", + deviceDetails: { + deviceId: "device_id", + deviceInstallationId: "device_installation_id", + deviceName: "device_name", + }, + applicationDetails: { + squareProduct: "ECOMMERCE_API", + applicationId: "sq0ids-TcgftTEtKxJTRF1lCFJ9TA", + }, + isOfflinePayment: true, + offlinePaymentDetails: { + clientCreatedAt: "client_created_at", + }, + versionToken: "N8AGYgEjCiY9Q57Jw7aVHEpBq8bzGCDCQMRX8Vs56N06o", + }, + }); + }); + + test("complete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = {}; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + payment: { + id: "bP9mAsEMYPUGjjGNaNO5ZDVyLhSZY", + created_at: "2021-10-13T19:34:33.524Z", + updated_at: "2021-10-13T19:34:34.339Z", + amount_money: { amount: BigInt(555), currency: "USD" }, + tip_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + total_money: { amount: BigInt(555), currency: "USD" }, + app_fee_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + approved_money: { amount: BigInt(555), currency: "USD" }, + processing_fee: [ + { + effective_at: "2021-10-13T21:34:35.000Z", + type: "INITIAL", + amount_money: { amount: BigInt(34), currency: "USD" }, + }, + ], + refunded_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + status: "COMPLETED", + delay_duration: "PT168H", + delay_action: "CANCEL", + delayed_until: "2021-10-20T19:34:33.524Z", + source_type: "CARD", + card_details: { + status: "CAPTURED", + card: { + card_brand: "VISA", + last_4: "1111", + exp_month: BigInt(11), + exp_year: BigInt(2022), + fingerprint: "sq-1-Hxim77tbdcbGejOejnoAklBVJed2YFLTmirfl8Q5XZzObTc8qY_U8RkwzoNL8dCEcQ", + card_type: "DEBIT", + prepaid_type: "NOT_PREPAID", + bin: "411111", + }, + entry_method: "KEYED", + cvv_status: "CVV_ACCEPTED", + avs_status: "AVS_ACCEPTED", + auth_result_code: "2Nkw7q", + application_identifier: "application_identifier", + application_name: "application_name", + application_cryptogram: "application_cryptogram", + verification_method: "verification_method", + verification_results: "verification_results", + statement_description: "SQ *EXAMPLE TEST GOSQ.C", + card_payment_timeline: { + authorized_at: "2021-10-13T19:34:33.680Z", + captured_at: "2021-10-13T19:34:34.340Z", + }, + refund_requires_card_presence: true, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + cash_details: { buyer_supplied_money: {} }, + bank_account_details: { + bank_name: "bank_name", + transfer_type: "transfer_type", + account_ownership_type: "account_ownership_type", + fingerprint: "fingerprint", + country: "country", + statement_description: "statement_description", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + external_details: { type: "type", source: "source", source_id: "source_id" }, + wallet_details: { status: "status", brand: "brand" }, + buy_now_pay_later_details: { brand: "brand" }, + square_account_details: { + payment_source_token: "payment_source_token", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + location_id: "L88917AVBK2S5", + order_id: "d7eKah653Z579f3gVtjlxpSlmUcZY", + reference_id: "reference_id", + customer_id: "customer_id", + employee_id: "TMoK_ogh6rH1o4dV", + team_member_id: "TMoK_ogh6rH1o4dV", + refund_ids: ["refund_ids"], + risk_evaluation: { created_at: "created_at", risk_level: "PENDING" }, + terminal_checkout_id: "terminal_checkout_id", + buyer_email_address: "buyer_email_address", + billing_address: { + address_line_1: "address_line_1", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "administrative_district_level_1", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "postal_code", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + shipping_address: { + address_line_1: "address_line_1", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "administrative_district_level_1", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "postal_code", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + note: "Test Note", + statement_description_identifier: "statement_description_identifier", + capabilities: ["capabilities"], + receipt_number: "bP9m", + receipt_url: "https://squareup.com/receipt/preview/bP9mAsEMYPUGjjGNaNO5ZDVyLhSZY", + device_details: { + device_id: "device_id", + device_installation_id: "device_installation_id", + device_name: "device_name", + }, + application_details: { + square_product: "VIRTUAL_TERMINAL", + application_id: "sq0ids-Pw67AZAlLVB7hsRmwlJPuA", + }, + is_offline_payment: true, + offline_payment_details: { client_created_at: "client_created_at" }, + version_token: "56pRkL3slrzet2iQrTp9n0bdJVYTB9YEWdTNjQfZOPV6o", + }, + }; + server + .mockEndpoint() + .post("/v2/payments/payment_id/complete") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.payments.complete({ + paymentId: "payment_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + payment: { + id: "bP9mAsEMYPUGjjGNaNO5ZDVyLhSZY", + createdAt: "2021-10-13T19:34:33.524Z", + updatedAt: "2021-10-13T19:34:34.339Z", + amountMoney: { + amount: BigInt("555"), + currency: "USD", + }, + tipMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + totalMoney: { + amount: BigInt("555"), + currency: "USD", + }, + appFeeMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + approvedMoney: { + amount: BigInt("555"), + currency: "USD", + }, + processingFee: [ + { + effectiveAt: "2021-10-13T21:34:35.000Z", + type: "INITIAL", + amountMoney: { + amount: BigInt("34"), + currency: "USD", + }, + }, + ], + refundedMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + status: "COMPLETED", + delayDuration: "PT168H", + delayAction: "CANCEL", + delayedUntil: "2021-10-20T19:34:33.524Z", + sourceType: "CARD", + cardDetails: { + status: "CAPTURED", + card: { + cardBrand: "VISA", + last4: "1111", + expMonth: BigInt("11"), + expYear: BigInt("2022"), + fingerprint: "sq-1-Hxim77tbdcbGejOejnoAklBVJed2YFLTmirfl8Q5XZzObTc8qY_U8RkwzoNL8dCEcQ", + cardType: "DEBIT", + prepaidType: "NOT_PREPAID", + bin: "411111", + }, + entryMethod: "KEYED", + cvvStatus: "CVV_ACCEPTED", + avsStatus: "AVS_ACCEPTED", + authResultCode: "2Nkw7q", + applicationIdentifier: "application_identifier", + applicationName: "application_name", + applicationCryptogram: "application_cryptogram", + verificationMethod: "verification_method", + verificationResults: "verification_results", + statementDescription: "SQ *EXAMPLE TEST GOSQ.C", + cardPaymentTimeline: { + authorizedAt: "2021-10-13T19:34:33.680Z", + capturedAt: "2021-10-13T19:34:34.340Z", + }, + refundRequiresCardPresence: true, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + cashDetails: { + buyerSuppliedMoney: {}, + }, + bankAccountDetails: { + bankName: "bank_name", + transferType: "transfer_type", + accountOwnershipType: "account_ownership_type", + fingerprint: "fingerprint", + country: "country", + statementDescription: "statement_description", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + externalDetails: { + type: "type", + source: "source", + sourceId: "source_id", + }, + walletDetails: { + status: "status", + brand: "brand", + }, + buyNowPayLaterDetails: { + brand: "brand", + }, + squareAccountDetails: { + paymentSourceToken: "payment_source_token", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + locationId: "L88917AVBK2S5", + orderId: "d7eKah653Z579f3gVtjlxpSlmUcZY", + referenceId: "reference_id", + customerId: "customer_id", + employeeId: "TMoK_ogh6rH1o4dV", + teamMemberId: "TMoK_ogh6rH1o4dV", + refundIds: ["refund_ids"], + riskEvaluation: { + createdAt: "created_at", + riskLevel: "PENDING", + }, + terminalCheckoutId: "terminal_checkout_id", + buyerEmailAddress: "buyer_email_address", + billingAddress: { + addressLine1: "address_line_1", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "administrative_district_level_1", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "postal_code", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + shippingAddress: { + addressLine1: "address_line_1", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "administrative_district_level_1", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "postal_code", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + note: "Test Note", + statementDescriptionIdentifier: "statement_description_identifier", + capabilities: ["capabilities"], + receiptNumber: "bP9m", + receiptUrl: "https://squareup.com/receipt/preview/bP9mAsEMYPUGjjGNaNO5ZDVyLhSZY", + deviceDetails: { + deviceId: "device_id", + deviceInstallationId: "device_installation_id", + deviceName: "device_name", + }, + applicationDetails: { + squareProduct: "VIRTUAL_TERMINAL", + applicationId: "sq0ids-Pw67AZAlLVB7hsRmwlJPuA", + }, + isOfflinePayment: true, + offlinePaymentDetails: { + clientCreatedAt: "client_created_at", + }, + versionToken: "56pRkL3slrzet2iQrTp9n0bdJVYTB9YEWdTNjQfZOPV6o", + }, + }); + }); +}); diff --git a/tests/wire/payouts.test.ts b/tests/wire/payouts.test.ts new file mode 100644 index 000000000..56332359f --- /dev/null +++ b/tests/wire/payouts.test.ts @@ -0,0 +1,72 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Payouts", () => { + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + payout: { + id: "po_f3c0fb38-a5ce-427d-b858-52b925b72e45", + status: "PAID", + location_id: "L88917AVBK2S5", + created_at: "2022-03-24T03:07:09Z", + updated_at: "2022-03-24T03:07:09Z", + amount_money: { amount: BigInt(-103), currency: "UNKNOWN_CURRENCY" }, + destination: { type: "BANK_ACCOUNT", id: "bact:ZPp3oedR3AeEUNd3z7" }, + version: 1, + type: "BATCH", + payout_fee: [{}], + arrival_date: "2022-03-24", + end_to_end_id: "end_to_end_id", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/payouts/payout_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.payouts.get({ + payoutId: "payout_id", + }); + expect(response).toEqual({ + payout: { + id: "po_f3c0fb38-a5ce-427d-b858-52b925b72e45", + status: "PAID", + locationId: "L88917AVBK2S5", + createdAt: "2022-03-24T03:07:09Z", + updatedAt: "2022-03-24T03:07:09Z", + amountMoney: { + amount: BigInt("-103"), + currency: "UNKNOWN_CURRENCY", + }, + destination: { + type: "BANK_ACCOUNT", + id: "bact:ZPp3oedR3AeEUNd3z7", + }, + version: 1, + type: "BATCH", + payoutFee: [{}], + arrivalDate: "2022-03-24", + endToEndId: "end_to_end_id", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/refunds.test.ts b/tests/wire/refunds.test.ts new file mode 100644 index 000000000..74800ac51 --- /dev/null +++ b/tests/wire/refunds.test.ts @@ -0,0 +1,206 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Refunds", () => { + test("RefundPayment", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "9b7f2dcf-49da-4411-b23e-a2d6af21333a", + amount_money: { amount: BigInt(1000), currency: "USD" }, + app_fee_money: { amount: BigInt(10), currency: "USD" }, + payment_id: "R2B3Z8WMVt3EAmzYWLZvz7Y69EbZY", + reason: "Example", + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + refund: { + id: "R2B3Z8WMVt3EAmzYWLZvz7Y69EbZY_KlWP8IC1557ddwc9QWTKrCVU6m0JXDz15R2Qym5eQfR", + status: "PENDING", + location_id: "L88917AVBK2S5", + unlinked: true, + destination_type: "destination_type", + destination_details: { + cash_details: { seller_supplied_money: {} }, + external_details: { type: "type", source: "source" }, + }, + amount_money: { amount: BigInt(1000), currency: "USD" }, + app_fee_money: { amount: BigInt(10), currency: "USD" }, + processing_fee: [{}], + payment_id: "R2B3Z8WMVt3EAmzYWLZvz7Y69EbZY", + order_id: "1JLEUZeEooAIX8HMqm9kvWd69aQZY", + reason: "Example", + created_at: "2021-10-13T21:23:19.116Z", + updated_at: "2021-10-13T21:23:19.508Z", + team_member_id: "team_member_id", + terminal_refund_id: "terminal_refund_id", + }, + }; + server + .mockEndpoint() + .post("/v2/refunds") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.refunds.refundPayment({ + idempotencyKey: "9b7f2dcf-49da-4411-b23e-a2d6af21333a", + amountMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + appFeeMoney: { + amount: BigInt("10"), + currency: "USD", + }, + paymentId: "R2B3Z8WMVt3EAmzYWLZvz7Y69EbZY", + reason: "Example", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + refund: { + id: "R2B3Z8WMVt3EAmzYWLZvz7Y69EbZY_KlWP8IC1557ddwc9QWTKrCVU6m0JXDz15R2Qym5eQfR", + status: "PENDING", + locationId: "L88917AVBK2S5", + unlinked: true, + destinationType: "destination_type", + destinationDetails: { + cashDetails: { + sellerSuppliedMoney: {}, + }, + externalDetails: { + type: "type", + source: "source", + }, + }, + amountMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + appFeeMoney: { + amount: BigInt("10"), + currency: "USD", + }, + processingFee: [{}], + paymentId: "R2B3Z8WMVt3EAmzYWLZvz7Y69EbZY", + orderId: "1JLEUZeEooAIX8HMqm9kvWd69aQZY", + reason: "Example", + createdAt: "2021-10-13T21:23:19.116Z", + updatedAt: "2021-10-13T21:23:19.508Z", + teamMemberId: "team_member_id", + terminalRefundId: "terminal_refund_id", + }, + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + refund: { + id: "bP9mAsEMYPUGjjGNaNO5ZDVyLhSZY_69MmgHubkLqx9wGhnmenRUHOaKitE6llfZuxcWYjGxd", + status: "COMPLETED", + location_id: "L88917AVBK2S5", + unlinked: true, + destination_type: "destination_type", + destination_details: { + cash_details: { seller_supplied_money: {} }, + external_details: { type: "type", source: "source" }, + }, + amount_money: { amount: BigInt(555), currency: "USD" }, + app_fee_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + processing_fee: [ + { + effective_at: "2021-10-13T21:34:35.000Z", + type: "INITIAL", + amount_money: { amount: BigInt(-34), currency: "USD" }, + }, + ], + payment_id: "bP9mAsEMYPUGjjGNaNO5ZDVyLhSZY", + order_id: "9ltv0bx5PuvGXUYHYHxYSKEqC3IZY", + reason: "Example Refund", + created_at: "2021-10-13T19:59:05.073Z", + updated_at: "2021-10-13T20:00:02.442Z", + team_member_id: "team_member_id", + terminal_refund_id: "terminal_refund_id", + }, + }; + server + .mockEndpoint() + .get("/v2/refunds/refund_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.refunds.get({ + refundId: "refund_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + refund: { + id: "bP9mAsEMYPUGjjGNaNO5ZDVyLhSZY_69MmgHubkLqx9wGhnmenRUHOaKitE6llfZuxcWYjGxd", + status: "COMPLETED", + locationId: "L88917AVBK2S5", + unlinked: true, + destinationType: "destination_type", + destinationDetails: { + cashDetails: { + sellerSuppliedMoney: {}, + }, + externalDetails: { + type: "type", + source: "source", + }, + }, + amountMoney: { + amount: BigInt("555"), + currency: "USD", + }, + appFeeMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + processingFee: [ + { + effectiveAt: "2021-10-13T21:34:35.000Z", + type: "INITIAL", + amountMoney: { + amount: BigInt("-34"), + currency: "USD", + }, + }, + ], + paymentId: "bP9mAsEMYPUGjjGNaNO5ZDVyLhSZY", + orderId: "9ltv0bx5PuvGXUYHYHxYSKEqC3IZY", + reason: "Example Refund", + createdAt: "2021-10-13T19:59:05.073Z", + updatedAt: "2021-10-13T20:00:02.442Z", + teamMemberId: "team_member_id", + terminalRefundId: "terminal_refund_id", + }, + }); + }); +}); diff --git a/tests/wire/sites.test.ts b/tests/wire/sites.test.ts new file mode 100644 index 000000000..0a668f8a9 --- /dev/null +++ b/tests/wire/sites.test.ts @@ -0,0 +1,66 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Sites", () => { + test("list", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + sites: [ + { + id: "site_278075276488921835", + site_title: "My Second Site", + domain: "mysite2.square.site", + is_published: false, + created_at: "2020-10-28T13:22:51.000000Z", + updated_at: "2020-10-28T13:22:51.000000Z", + }, + { + id: "site_102725345836253849", + site_title: "My First Site", + domain: "mysite1.square.site", + is_published: true, + created_at: "2020-06-18T17:45:13.000000Z", + updated_at: "2020-11-23T02:19:10.000000Z", + }, + ], + }; + server.mockEndpoint().get("/v2/sites").respondWith().statusCode(200).jsonBody(rawResponseBody).build(); + + const response = await client.sites.list(); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + sites: [ + { + id: "site_278075276488921835", + siteTitle: "My Second Site", + domain: "mysite2.square.site", + isPublished: false, + createdAt: "2020-10-28T13:22:51.000000Z", + updatedAt: "2020-10-28T13:22:51.000000Z", + }, + { + id: "site_102725345836253849", + siteTitle: "My First Site", + domain: "mysite1.square.site", + isPublished: true, + createdAt: "2020-06-18T17:45:13.000000Z", + updatedAt: "2020-11-23T02:19:10.000000Z", + }, + ], + }); + }); +}); diff --git a/tests/wire/snippets.test.ts b/tests/wire/snippets.test.ts new file mode 100644 index 000000000..d901571c6 --- /dev/null +++ b/tests/wire/snippets.test.ts @@ -0,0 +1,130 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Snippets", () => { + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + snippet: { + id: "snippet_5d178150-a6c0-11eb-a9f1-437e6a2881e7", + site_id: "site_278075276488921835", + content: "", + created_at: "2021-03-11T25:40:09.000000Z", + updated_at: "2021-03-11T25:40:09.000000Z", + }, + }; + server + .mockEndpoint() + .get("/v2/sites/site_id/snippet") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.snippets.get({ + siteId: "site_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + snippet: { + id: "snippet_5d178150-a6c0-11eb-a9f1-437e6a2881e7", + siteId: "site_278075276488921835", + content: "", + createdAt: "2021-03-11T25:40:09.000000Z", + updatedAt: "2021-03-11T25:40:09.000000Z", + }, + }); + }); + + test("upsert", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { snippet: { content: "" } }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + snippet: { + id: "snippet_5d178150-a6c0-11eb-a9f1-437e6a2881e7", + site_id: "site_278075276488921835", + content: "", + created_at: "2021-03-11T25:40:09.000000Z", + updated_at: "2021-03-11T25:40:09.000000Z", + }, + }; + server + .mockEndpoint() + .post("/v2/sites/site_id/snippet") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.snippets.upsert({ + siteId: "site_id", + snippet: { + content: "", + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + snippet: { + id: "snippet_5d178150-a6c0-11eb-a9f1-437e6a2881e7", + siteId: "site_278075276488921835", + content: "", + createdAt: "2021-03-11T25:40:09.000000Z", + updatedAt: "2021-03-11T25:40:09.000000Z", + }, + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/sites/site_id/snippet") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.snippets.delete({ + siteId: "site_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/subscriptions.test.ts b/tests/wire/subscriptions.test.ts new file mode 100644 index 000000000..a43db7f23 --- /dev/null +++ b/tests/wire/subscriptions.test.ts @@ -0,0 +1,1157 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Subscriptions", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "8193148c-9586-11e6-99f9-28cfe92138cf", + location_id: "S8GWD5R9QB376", + plan_variation_id: "6JHXF3B2CW3YKHDV4XEM674H", + customer_id: "CHFGVKYY8RSV93M5KCYTG4PN0G", + start_date: "2023-06-20", + card_id: "ccof:qy5x8hHGYsgLrp4Q4GB", + timezone: "America/Los_Angeles", + source: { name: "My Application" }, + phases: [{ ordinal: BigInt(0), order_template_id: "U2NaowWxzXwpsZU697x7ZHOAnCNZY" }], + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + subscription: { + id: "56214fb2-cc85-47a1-93bc-44f3766bb56f", + location_id: "S8GWD5R9QB376", + plan_variation_id: "6JHXF3B2CW3YKHDV4XEM674H", + customer_id: "CHFGVKYY8RSV93M5KCYTG4PN0G", + start_date: "2023-06-20", + canceled_date: "canceled_date", + charged_through_date: "charged_through_date", + status: "ACTIVE", + tax_percentage: "tax_percentage", + invoice_ids: ["invoice_ids"], + price_override_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + version: BigInt(1), + created_at: "2023-06-20T21:53:10Z", + card_id: "ccof:qy5x8hHGYsgLrp4Q4GB", + timezone: "America/Los_Angeles", + source: { name: "My Application" }, + actions: [{}], + monthly_billing_anchor_date: 1, + phases: [ + { + uid: "873451e0-745b-4e87-ab0b-c574933fe616", + ordinal: BigInt(0), + order_template_id: "U2NaowWxzXwpsZU697x7ZHOAnCNZY", + plan_phase_uid: "X2Q2AONPB3RB64Y27S25QCZP", + }, + ], + }, + }; + server + .mockEndpoint() + .post("/v2/subscriptions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.subscriptions.create({ + idempotencyKey: "8193148c-9586-11e6-99f9-28cfe92138cf", + locationId: "S8GWD5R9QB376", + planVariationId: "6JHXF3B2CW3YKHDV4XEM674H", + customerId: "CHFGVKYY8RSV93M5KCYTG4PN0G", + startDate: "2023-06-20", + cardId: "ccof:qy5x8hHGYsgLrp4Q4GB", + timezone: "America/Los_Angeles", + source: { + name: "My Application", + }, + phases: [ + { + ordinal: BigInt("0"), + orderTemplateId: "U2NaowWxzXwpsZU697x7ZHOAnCNZY", + }, + ], + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + subscription: { + id: "56214fb2-cc85-47a1-93bc-44f3766bb56f", + locationId: "S8GWD5R9QB376", + planVariationId: "6JHXF3B2CW3YKHDV4XEM674H", + customerId: "CHFGVKYY8RSV93M5KCYTG4PN0G", + startDate: "2023-06-20", + canceledDate: "canceled_date", + chargedThroughDate: "charged_through_date", + status: "ACTIVE", + taxPercentage: "tax_percentage", + invoiceIds: ["invoice_ids"], + priceOverrideMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + version: BigInt("1"), + createdAt: "2023-06-20T21:53:10Z", + cardId: "ccof:qy5x8hHGYsgLrp4Q4GB", + timezone: "America/Los_Angeles", + source: { + name: "My Application", + }, + actions: [{}], + monthlyBillingAnchorDate: 1, + phases: [ + { + uid: "873451e0-745b-4e87-ab0b-c574933fe616", + ordinal: BigInt("0"), + orderTemplateId: "U2NaowWxzXwpsZU697x7ZHOAnCNZY", + planPhaseUid: "X2Q2AONPB3RB64Y27S25QCZP", + }, + ], + }, + }); + }); + + test("BulkSwapPlan", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + new_plan_variation_id: "FQ7CDXXWSLUJRPM3GFJSJGZ7", + old_plan_variation_id: "6JHXF3B2CW3YKHDV4XEM674H", + location_id: "S8GWD5R9QB376", + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + affected_subscriptions: 12, + }; + server + .mockEndpoint() + .post("/v2/subscriptions/bulk-swap-plan") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.subscriptions.bulkSwapPlan({ + newPlanVariationId: "FQ7CDXXWSLUJRPM3GFJSJGZ7", + oldPlanVariationId: "6JHXF3B2CW3YKHDV4XEM674H", + locationId: "S8GWD5R9QB376", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + affectedSubscriptions: 12, + }); + }); + + test("search", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + query: { + filter: { + customer_ids: ["CHFGVKYY8RSV93M5KCYTG4PN0G"], + location_ids: ["S8GWD5R9QB376"], + source_names: ["My App"], + }, + }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + subscriptions: [ + { + id: "de86fc96-8664-474b-af1a-abbe59cacf0e", + location_id: "S8GWD5R9QB376", + plan_variation_id: "L3TJVDHVBEQEGQDEZL2JJM7R", + customer_id: "CHFGVKYY8RSV93M5KCYTG4PN0G", + start_date: "2021-10-20", + canceled_date: "2021-10-30", + charged_through_date: "2021-11-20", + status: "CANCELED", + tax_percentage: "tax_percentage", + invoice_ids: ["invoice_ids"], + version: BigInt(1000000), + created_at: "2021-10-20T21:53:10Z", + card_id: "ccof:mueUsvgajChmjEbp4GB", + timezone: "UTC", + source: { name: "My Application" }, + actions: [{}], + monthly_billing_anchor_date: 1, + phases: [{}], + }, + { + id: "56214fb2-cc85-47a1-93bc-44f3766bb56f", + location_id: "S8GWD5R9QB376", + plan_variation_id: "6JHXF3B2CW3YKHDV4XEM674H", + customer_id: "CHFGVKYY8RSV93M5KCYTG4PN0G", + start_date: "2022-01-19", + canceled_date: "canceled_date", + charged_through_date: "2022-08-19", + status: "PAUSED", + tax_percentage: "5", + invoice_ids: ["grebK0Q_l8H4fqoMMVvt-Q", "rcX_i3sNmHTGKhI4W2mceA"], + price_override_money: { amount: BigInt(1000), currency: "USD" }, + version: BigInt(2), + created_at: "2022-01-19T21:53:10Z", + card_id: "card_id", + timezone: "America/Los_Angeles", + source: { name: "My Application" }, + actions: [{}], + monthly_billing_anchor_date: 1, + phases: [{}], + }, + { + id: "56214fb2-cc85-47a1-93bc-44f3766bb56f", + location_id: "S8GWD5R9QB376", + plan_variation_id: "6JHXF3B2CW3YKHDV4XEM674H", + customer_id: "CHFGVKYY8RSV93M5KCYTG4PN0G", + start_date: "2023-06-20", + canceled_date: "canceled_date", + charged_through_date: "charged_through_date", + status: "ACTIVE", + tax_percentage: "tax_percentage", + invoice_ids: ["invoice_ids"], + version: BigInt(1), + created_at: "2023-06-20T21:53:10Z", + card_id: "ccof:qy5x8hHGYsgLrp4Q4GB", + timezone: "America/Los_Angeles", + source: { name: "My Application" }, + actions: [{}], + monthly_billing_anchor_date: 1, + phases: [ + { + uid: "873451e0-745b-4e87-ab0b-c574933fe616", + ordinal: BigInt(0), + order_template_id: "U2NaowWxzXwpsZU697x7ZHOAnCNZY", + plan_phase_uid: "X2Q2AONPB3RB64Y27S25QCZP", + }, + ], + }, + ], + cursor: "cursor", + }; + server + .mockEndpoint() + .post("/v2/subscriptions/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.subscriptions.search({ + query: { + filter: { + customerIds: ["CHFGVKYY8RSV93M5KCYTG4PN0G"], + locationIds: ["S8GWD5R9QB376"], + sourceNames: ["My App"], + }, + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + subscriptions: [ + { + id: "de86fc96-8664-474b-af1a-abbe59cacf0e", + locationId: "S8GWD5R9QB376", + planVariationId: "L3TJVDHVBEQEGQDEZL2JJM7R", + customerId: "CHFGVKYY8RSV93M5KCYTG4PN0G", + startDate: "2021-10-20", + canceledDate: "2021-10-30", + chargedThroughDate: "2021-11-20", + status: "CANCELED", + taxPercentage: "tax_percentage", + invoiceIds: ["invoice_ids"], + version: BigInt("1000000"), + createdAt: "2021-10-20T21:53:10Z", + cardId: "ccof:mueUsvgajChmjEbp4GB", + timezone: "UTC", + source: { + name: "My Application", + }, + actions: [{}], + monthlyBillingAnchorDate: 1, + phases: [{}], + }, + { + id: "56214fb2-cc85-47a1-93bc-44f3766bb56f", + locationId: "S8GWD5R9QB376", + planVariationId: "6JHXF3B2CW3YKHDV4XEM674H", + customerId: "CHFGVKYY8RSV93M5KCYTG4PN0G", + startDate: "2022-01-19", + canceledDate: "canceled_date", + chargedThroughDate: "2022-08-19", + status: "PAUSED", + taxPercentage: "5", + invoiceIds: ["grebK0Q_l8H4fqoMMVvt-Q", "rcX_i3sNmHTGKhI4W2mceA"], + priceOverrideMoney: { + amount: BigInt("1000"), + currency: "USD", + }, + version: BigInt("2"), + createdAt: "2022-01-19T21:53:10Z", + cardId: "card_id", + timezone: "America/Los_Angeles", + source: { + name: "My Application", + }, + actions: [{}], + monthlyBillingAnchorDate: 1, + phases: [{}], + }, + { + id: "56214fb2-cc85-47a1-93bc-44f3766bb56f", + locationId: "S8GWD5R9QB376", + planVariationId: "6JHXF3B2CW3YKHDV4XEM674H", + customerId: "CHFGVKYY8RSV93M5KCYTG4PN0G", + startDate: "2023-06-20", + canceledDate: "canceled_date", + chargedThroughDate: "charged_through_date", + status: "ACTIVE", + taxPercentage: "tax_percentage", + invoiceIds: ["invoice_ids"], + version: BigInt("1"), + createdAt: "2023-06-20T21:53:10Z", + cardId: "ccof:qy5x8hHGYsgLrp4Q4GB", + timezone: "America/Los_Angeles", + source: { + name: "My Application", + }, + actions: [{}], + monthlyBillingAnchorDate: 1, + phases: [ + { + uid: "873451e0-745b-4e87-ab0b-c574933fe616", + ordinal: BigInt("0"), + orderTemplateId: "U2NaowWxzXwpsZU697x7ZHOAnCNZY", + planPhaseUid: "X2Q2AONPB3RB64Y27S25QCZP", + }, + ], + }, + ], + cursor: "cursor", + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + subscription: { + id: "8151fc89-da15-4eb9-a685-1a70883cebfc", + location_id: "S8GWD5R9QB376", + plan_variation_id: "6JHXF3B2CW3YKHDV4XEM674H", + customer_id: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + start_date: "2022-07-27", + canceled_date: "canceled_date", + charged_through_date: "2023-11-20", + status: "ACTIVE", + tax_percentage: "tax_percentage", + invoice_ids: ["inv:0-ChCHu2mZEabLeeHahQnXDjZQECY", "inv:0-ChrcX_i3sNmfsHTGKhI4Wg2mceA"], + price_override_money: { amount: BigInt(25000), currency: "USD" }, + version: BigInt(1000000), + created_at: "2022-07-27T21:53:10Z", + card_id: "ccof:IkWfpLj4tNHMyFii3GB", + timezone: "America/Los_Angeles", + source: { name: "My Application" }, + actions: [{}], + monthly_billing_anchor_date: 1, + phases: [{}], + }, + }; + server + .mockEndpoint() + .get("/v2/subscriptions/subscription_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.subscriptions.get({ + subscriptionId: "subscription_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + subscription: { + id: "8151fc89-da15-4eb9-a685-1a70883cebfc", + locationId: "S8GWD5R9QB376", + planVariationId: "6JHXF3B2CW3YKHDV4XEM674H", + customerId: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + startDate: "2022-07-27", + canceledDate: "canceled_date", + chargedThroughDate: "2023-11-20", + status: "ACTIVE", + taxPercentage: "tax_percentage", + invoiceIds: ["inv:0-ChCHu2mZEabLeeHahQnXDjZQECY", "inv:0-ChrcX_i3sNmfsHTGKhI4Wg2mceA"], + priceOverrideMoney: { + amount: BigInt("25000"), + currency: "USD", + }, + version: BigInt("1000000"), + createdAt: "2022-07-27T21:53:10Z", + cardId: "ccof:IkWfpLj4tNHMyFii3GB", + timezone: "America/Los_Angeles", + source: { + name: "My Application", + }, + actions: [{}], + monthlyBillingAnchorDate: 1, + phases: [{}], + }, + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { subscription: { card_id: "{NEW CARD ID}" } }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + subscription: { + id: "7217d8ca-1fee-4446-a9e5-8540b5d8c9bb", + location_id: "LPJKHYR7WFDKN", + plan_variation_id: "XOUNEKCE6NSXQW5NTSQ73MMX", + customer_id: "AM69AB81FT4479YH9HGWS1HZY8", + start_date: "2023-01-30", + canceled_date: "canceled_date", + charged_through_date: "2023-03-13", + status: "ACTIVE", + tax_percentage: "tax_percentage", + invoice_ids: ["inv:0-ChAPSfVYvNewckgf3x4iigN_ENMM", "inv:0-ChBQaCCLfjcm9WEUBGxvuydJENMM"], + price_override_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + version: BigInt(3), + created_at: "2023-01-30T19:27:32Z", + card_id: "{NEW CARD ID}", + timezone: "UTC", + source: { name: "My Application" }, + actions: [{}], + monthly_billing_anchor_date: 1, + phases: [{}], + }, + }; + server + .mockEndpoint() + .put("/v2/subscriptions/subscription_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.subscriptions.update({ + subscriptionId: "subscription_id", + subscription: { + cardId: "{NEW CARD ID}", + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + subscription: { + id: "7217d8ca-1fee-4446-a9e5-8540b5d8c9bb", + locationId: "LPJKHYR7WFDKN", + planVariationId: "XOUNEKCE6NSXQW5NTSQ73MMX", + customerId: "AM69AB81FT4479YH9HGWS1HZY8", + startDate: "2023-01-30", + canceledDate: "canceled_date", + chargedThroughDate: "2023-03-13", + status: "ACTIVE", + taxPercentage: "tax_percentage", + invoiceIds: ["inv:0-ChAPSfVYvNewckgf3x4iigN_ENMM", "inv:0-ChBQaCCLfjcm9WEUBGxvuydJENMM"], + priceOverrideMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + version: BigInt("3"), + createdAt: "2023-01-30T19:27:32Z", + cardId: "{NEW CARD ID}", + timezone: "UTC", + source: { + name: "My Application", + }, + actions: [{}], + monthlyBillingAnchorDate: 1, + phases: [{}], + }, + }); + }); + + test("DeleteAction", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + subscription: { + id: "8151fc89-da15-4eb9-a685-1a70883cebfc", + location_id: "S8GWD5R9QB376", + plan_variation_id: "6JHXF3B2CW3YKHDV4XEM674H", + customer_id: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + start_date: "2022-07-27", + canceled_date: "canceled_date", + charged_through_date: "2023-11-20", + status: "ACTIVE", + tax_percentage: "tax_percentage", + invoice_ids: ["inv:0-ChCHu2mZEabLeeHahQnXDjZQECY", "inv:0-ChrcX_i3sNmfsHTGKhI4Wg2mceA"], + price_override_money: { amount: BigInt(25000), currency: "USD" }, + version: BigInt(1000000), + created_at: "2022-07-27T21:53:10Z", + card_id: "ccof:IkWfpLj4tNHMyFii3GB", + timezone: "America/Los_Angeles", + source: { name: "My Application" }, + actions: [{}], + monthly_billing_anchor_date: 1, + phases: [{}], + }, + }; + server + .mockEndpoint() + .delete("/v2/subscriptions/subscription_id/actions/action_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.subscriptions.deleteAction({ + subscriptionId: "subscription_id", + actionId: "action_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + subscription: { + id: "8151fc89-da15-4eb9-a685-1a70883cebfc", + locationId: "S8GWD5R9QB376", + planVariationId: "6JHXF3B2CW3YKHDV4XEM674H", + customerId: "JDKYHBWT1D4F8MFH63DBMEN8Y4", + startDate: "2022-07-27", + canceledDate: "canceled_date", + chargedThroughDate: "2023-11-20", + status: "ACTIVE", + taxPercentage: "tax_percentage", + invoiceIds: ["inv:0-ChCHu2mZEabLeeHahQnXDjZQECY", "inv:0-ChrcX_i3sNmfsHTGKhI4Wg2mceA"], + priceOverrideMoney: { + amount: BigInt("25000"), + currency: "USD", + }, + version: BigInt("1000000"), + createdAt: "2022-07-27T21:53:10Z", + cardId: "ccof:IkWfpLj4tNHMyFii3GB", + timezone: "America/Los_Angeles", + source: { + name: "My Application", + }, + actions: [{}], + monthlyBillingAnchorDate: 1, + phases: [{}], + }, + }); + }); + + test("ChangeBillingAnchorDate", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { monthly_billing_anchor_date: 1 }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + subscription: { + id: "9ba40961-995a-4a3d-8c53-048c40cafc13", + location_id: "S8GWD5R9QB376", + plan_variation_id: "FQ7CDXXWSLUJRPM3GFJSJGZ7", + customer_id: "CHFGVKYY8RSV93M5KCYTG4PN0G", + start_date: "start_date", + canceled_date: "canceled_date", + charged_through_date: "charged_through_date", + status: "ACTIVE", + tax_percentage: "tax_percentage", + invoice_ids: ["invoice_ids"], + price_override_money: { amount: BigInt(2000), currency: "USD" }, + version: BigInt(3), + created_at: "2023-06-20T21:53:10Z", + card_id: "card_id", + timezone: "America/Los_Angeles", + source: { name: "My Application" }, + actions: [{}], + monthly_billing_anchor_date: 20, + phases: [ + { + uid: "98d6f53b-40e1-4714-8827-032fd923be25", + ordinal: BigInt(0), + order_template_id: "E6oBY5WfQ2eN4pkYZwq4ka6n7KeZY", + plan_phase_uid: "C66BKH3ASTDYGJJCEZXQQSS7", + }, + ], + }, + actions: [ + { + id: "f0a1dfdc-675b-3a14-a640-99f7ac1cee83", + type: "CHANGE_BILLING_ANCHOR_DATE", + effective_date: "2023-11-01", + monthly_billing_anchor_date: 1, + phases: [{}], + new_plan_variation_id: "new_plan_variation_id", + }, + ], + }; + server + .mockEndpoint() + .post("/v2/subscriptions/subscription_id/billing-anchor") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.subscriptions.changeBillingAnchorDate({ + subscriptionId: "subscription_id", + monthlyBillingAnchorDate: 1, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + subscription: { + id: "9ba40961-995a-4a3d-8c53-048c40cafc13", + locationId: "S8GWD5R9QB376", + planVariationId: "FQ7CDXXWSLUJRPM3GFJSJGZ7", + customerId: "CHFGVKYY8RSV93M5KCYTG4PN0G", + startDate: "start_date", + canceledDate: "canceled_date", + chargedThroughDate: "charged_through_date", + status: "ACTIVE", + taxPercentage: "tax_percentage", + invoiceIds: ["invoice_ids"], + priceOverrideMoney: { + amount: BigInt("2000"), + currency: "USD", + }, + version: BigInt("3"), + createdAt: "2023-06-20T21:53:10Z", + cardId: "card_id", + timezone: "America/Los_Angeles", + source: { + name: "My Application", + }, + actions: [{}], + monthlyBillingAnchorDate: 20, + phases: [ + { + uid: "98d6f53b-40e1-4714-8827-032fd923be25", + ordinal: BigInt("0"), + orderTemplateId: "E6oBY5WfQ2eN4pkYZwq4ka6n7KeZY", + planPhaseUid: "C66BKH3ASTDYGJJCEZXQQSS7", + }, + ], + }, + actions: [ + { + id: "f0a1dfdc-675b-3a14-a640-99f7ac1cee83", + type: "CHANGE_BILLING_ANCHOR_DATE", + effectiveDate: "2023-11-01", + monthlyBillingAnchorDate: 1, + phases: [{}], + newPlanVariationId: "new_plan_variation_id", + }, + ], + }); + }); + + test("cancel", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + subscription: { + id: "910afd30-464a-4e00-a8d8-2296e", + location_id: "S8GWD5R9QB376", + plan_variation_id: "6JHXF3B2CW3YKHDV4XEM674H", + customer_id: "CHFGVKYY8RSV93M5KCYTG4PN0G", + start_date: "2022-01-19", + canceled_date: "2023-06-05", + charged_through_date: "charged_through_date", + status: "ACTIVE", + tax_percentage: "tax_percentage", + invoice_ids: ["inv:0-ChCHu2mZEabLeeHahQnXDjZQECY", "inv:0-ChrcX_i3sNmfsHTGKhI4Wg2mceA"], + price_override_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + version: BigInt(3), + created_at: "2022-01-19T21:53:10Z", + card_id: "ccof:qy5x8hHGYsgLrp4Q4GB", + timezone: "America/Los_Angeles", + source: { name: "My Application" }, + actions: [{}], + monthly_billing_anchor_date: 1, + phases: [{}], + }, + actions: [ + { + id: "id", + type: "CANCEL", + effective_date: "effective_date", + monthly_billing_anchor_date: 1, + phases: [{}], + new_plan_variation_id: "new_plan_variation_id", + }, + ], + }; + server + .mockEndpoint() + .post("/v2/subscriptions/subscription_id/cancel") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.subscriptions.cancel({ + subscriptionId: "subscription_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + subscription: { + id: "910afd30-464a-4e00-a8d8-2296e", + locationId: "S8GWD5R9QB376", + planVariationId: "6JHXF3B2CW3YKHDV4XEM674H", + customerId: "CHFGVKYY8RSV93M5KCYTG4PN0G", + startDate: "2022-01-19", + canceledDate: "2023-06-05", + chargedThroughDate: "charged_through_date", + status: "ACTIVE", + taxPercentage: "tax_percentage", + invoiceIds: ["inv:0-ChCHu2mZEabLeeHahQnXDjZQECY", "inv:0-ChrcX_i3sNmfsHTGKhI4Wg2mceA"], + priceOverrideMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + version: BigInt("3"), + createdAt: "2022-01-19T21:53:10Z", + cardId: "ccof:qy5x8hHGYsgLrp4Q4GB", + timezone: "America/Los_Angeles", + source: { + name: "My Application", + }, + actions: [{}], + monthlyBillingAnchorDate: 1, + phases: [{}], + }, + actions: [ + { + id: "id", + type: "CANCEL", + effectiveDate: "effective_date", + monthlyBillingAnchorDate: 1, + phases: [{}], + newPlanVariationId: "new_plan_variation_id", + }, + ], + }); + }); + + test("pause", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = {}; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + subscription: { + id: "56214fb2-cc85-47a1-93bc-44f3766bb56f", + location_id: "S8GWD5R9QB376", + plan_variation_id: "6JHXF3B2CW3YKHDV4XEM674H", + customer_id: "CHFGVKYY8RSV93M5KCYTG4PN0G", + start_date: "2023-06-20", + canceled_date: "canceled_date", + charged_through_date: "charged_through_date", + status: "ACTIVE", + tax_percentage: "tax_percentage", + invoice_ids: ["invoice_ids"], + price_override_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + version: BigInt(1), + created_at: "2023-06-20T21:53:10Z", + card_id: "ccof:qy5x8hHGYsgLrp4Q4GB", + timezone: "America/Los_Angeles", + source: { name: "My Application" }, + actions: [{}], + monthly_billing_anchor_date: 1, + phases: [ + { + uid: "873451e0-745b-4e87-ab0b-c574933fe616", + ordinal: BigInt(0), + order_template_id: "U2NaowWxzXwpsZU697x7ZHOAnCNZY", + plan_phase_uid: "X2Q2AONPB3RB64Y27S25QCZP", + }, + ], + }, + actions: [ + { + id: "99b2439e-63f7-3ad5-95f7-ab2447a80673", + type: "PAUSE", + effective_date: "2023-11-17", + monthly_billing_anchor_date: 1, + phases: [{}], + new_plan_variation_id: "new_plan_variation_id", + }, + ], + }; + server + .mockEndpoint() + .post("/v2/subscriptions/subscription_id/pause") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.subscriptions.pause({ + subscriptionId: "subscription_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + subscription: { + id: "56214fb2-cc85-47a1-93bc-44f3766bb56f", + locationId: "S8GWD5R9QB376", + planVariationId: "6JHXF3B2CW3YKHDV4XEM674H", + customerId: "CHFGVKYY8RSV93M5KCYTG4PN0G", + startDate: "2023-06-20", + canceledDate: "canceled_date", + chargedThroughDate: "charged_through_date", + status: "ACTIVE", + taxPercentage: "tax_percentage", + invoiceIds: ["invoice_ids"], + priceOverrideMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + version: BigInt("1"), + createdAt: "2023-06-20T21:53:10Z", + cardId: "ccof:qy5x8hHGYsgLrp4Q4GB", + timezone: "America/Los_Angeles", + source: { + name: "My Application", + }, + actions: [{}], + monthlyBillingAnchorDate: 1, + phases: [ + { + uid: "873451e0-745b-4e87-ab0b-c574933fe616", + ordinal: BigInt("0"), + orderTemplateId: "U2NaowWxzXwpsZU697x7ZHOAnCNZY", + planPhaseUid: "X2Q2AONPB3RB64Y27S25QCZP", + }, + ], + }, + actions: [ + { + id: "99b2439e-63f7-3ad5-95f7-ab2447a80673", + type: "PAUSE", + effectiveDate: "2023-11-17", + monthlyBillingAnchorDate: 1, + phases: [{}], + newPlanVariationId: "new_plan_variation_id", + }, + ], + }); + }); + + test("resume", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = {}; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + subscription: { + id: "56214fb2-cc85-47a1-93bc-44f3766bb56f", + location_id: "S8GWD5R9QB376", + plan_variation_id: "6JHXF3B2CW3YKHDV4XEM674H", + customer_id: "CHFGVKYY8RSV93M5KCYTG4PN0G", + start_date: "2023-06-20", + canceled_date: "canceled_date", + charged_through_date: "charged_through_date", + status: "ACTIVE", + tax_percentage: "tax_percentage", + invoice_ids: ["invoice_ids"], + price_override_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + version: BigInt(1), + created_at: "2023-06-20T21:53:10Z", + card_id: "ccof:qy5x8hHGYsgLrp4Q4GB", + timezone: "America/Los_Angeles", + source: { name: "My Application" }, + actions: [{}], + monthly_billing_anchor_date: 1, + phases: [ + { + uid: "873451e0-745b-4e87-ab0b-c574933fe616", + ordinal: BigInt(0), + order_template_id: "U2NaowWxzXwpsZU697x7ZHOAnCNZY", + plan_phase_uid: "X2Q2AONPB3RB64Y27S25QCZP", + }, + ], + }, + actions: [ + { + id: "18ff74f4-3da4-30c5-929f-7d6fca84f115", + type: "RESUME", + effective_date: "2023-09-01", + monthly_billing_anchor_date: 1, + phases: [{}], + new_plan_variation_id: "new_plan_variation_id", + }, + ], + }; + server + .mockEndpoint() + .post("/v2/subscriptions/subscription_id/resume") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.subscriptions.resume({ + subscriptionId: "subscription_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + subscription: { + id: "56214fb2-cc85-47a1-93bc-44f3766bb56f", + locationId: "S8GWD5R9QB376", + planVariationId: "6JHXF3B2CW3YKHDV4XEM674H", + customerId: "CHFGVKYY8RSV93M5KCYTG4PN0G", + startDate: "2023-06-20", + canceledDate: "canceled_date", + chargedThroughDate: "charged_through_date", + status: "ACTIVE", + taxPercentage: "tax_percentage", + invoiceIds: ["invoice_ids"], + priceOverrideMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + version: BigInt("1"), + createdAt: "2023-06-20T21:53:10Z", + cardId: "ccof:qy5x8hHGYsgLrp4Q4GB", + timezone: "America/Los_Angeles", + source: { + name: "My Application", + }, + actions: [{}], + monthlyBillingAnchorDate: 1, + phases: [ + { + uid: "873451e0-745b-4e87-ab0b-c574933fe616", + ordinal: BigInt("0"), + orderTemplateId: "U2NaowWxzXwpsZU697x7ZHOAnCNZY", + planPhaseUid: "X2Q2AONPB3RB64Y27S25QCZP", + }, + ], + }, + actions: [ + { + id: "18ff74f4-3da4-30c5-929f-7d6fca84f115", + type: "RESUME", + effectiveDate: "2023-09-01", + monthlyBillingAnchorDate: 1, + phases: [{}], + newPlanVariationId: "new_plan_variation_id", + }, + ], + }); + }); + + test("SwapPlan", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + new_plan_variation_id: "FQ7CDXXWSLUJRPM3GFJSJGZ7", + phases: [{ ordinal: BigInt(0), order_template_id: "uhhnjH9osVv3shUADwaC0b3hNxQZY" }], + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + subscription: { + id: "9ba40961-995a-4a3d-8c53-048c40cafc13", + location_id: "S8GWD5R9QB376", + plan_variation_id: "FQ7CDXXWSLUJRPM3GFJSJGZ7", + customer_id: "CHFGVKYY8RSV93M5KCYTG4PN0G", + start_date: "start_date", + canceled_date: "canceled_date", + charged_through_date: "charged_through_date", + status: "ACTIVE", + tax_percentage: "tax_percentage", + invoice_ids: ["invoice_ids"], + price_override_money: { amount: BigInt(2000), currency: "USD" }, + version: BigInt(3), + created_at: "2023-06-20T21:53:10Z", + card_id: "card_id", + timezone: "America/Los_Angeles", + source: { name: "My Application" }, + actions: [{}], + monthly_billing_anchor_date: 1, + phases: [ + { + uid: "98d6f53b-40e1-4714-8827-032fd923be25", + ordinal: BigInt(0), + order_template_id: "E6oBY5WfQ2eN4pkYZwq4ka6n7KeZY", + plan_phase_uid: "C66BKH3ASTDYGJJCEZXQQSS7", + }, + ], + }, + actions: [ + { + id: "f0a1dfdc-675b-3a14-a640-99f7ac1cee83", + type: "SWAP_PLAN", + effective_date: "2023-11-17", + monthly_billing_anchor_date: 1, + phases: [{ ordinal: BigInt(0), order_template_id: "uhhnjH9osVv3shUADwaC0b3hNxQZY" }], + new_plan_variation_id: "FQ7CDXXWSLUJRPM3GFJSJGZ7", + }, + ], + }; + server + .mockEndpoint() + .post("/v2/subscriptions/subscription_id/swap-plan") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.subscriptions.swapPlan({ + subscriptionId: "subscription_id", + newPlanVariationId: "FQ7CDXXWSLUJRPM3GFJSJGZ7", + phases: [ + { + ordinal: BigInt("0"), + orderTemplateId: "uhhnjH9osVv3shUADwaC0b3hNxQZY", + }, + ], + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + subscription: { + id: "9ba40961-995a-4a3d-8c53-048c40cafc13", + locationId: "S8GWD5R9QB376", + planVariationId: "FQ7CDXXWSLUJRPM3GFJSJGZ7", + customerId: "CHFGVKYY8RSV93M5KCYTG4PN0G", + startDate: "start_date", + canceledDate: "canceled_date", + chargedThroughDate: "charged_through_date", + status: "ACTIVE", + taxPercentage: "tax_percentage", + invoiceIds: ["invoice_ids"], + priceOverrideMoney: { + amount: BigInt("2000"), + currency: "USD", + }, + version: BigInt("3"), + createdAt: "2023-06-20T21:53:10Z", + cardId: "card_id", + timezone: "America/Los_Angeles", + source: { + name: "My Application", + }, + actions: [{}], + monthlyBillingAnchorDate: 1, + phases: [ + { + uid: "98d6f53b-40e1-4714-8827-032fd923be25", + ordinal: BigInt("0"), + orderTemplateId: "E6oBY5WfQ2eN4pkYZwq4ka6n7KeZY", + planPhaseUid: "C66BKH3ASTDYGJJCEZXQQSS7", + }, + ], + }, + actions: [ + { + id: "f0a1dfdc-675b-3a14-a640-99f7ac1cee83", + type: "SWAP_PLAN", + effectiveDate: "2023-11-17", + monthlyBillingAnchorDate: 1, + phases: [ + { + ordinal: BigInt("0"), + orderTemplateId: "uhhnjH9osVv3shUADwaC0b3hNxQZY", + }, + ], + newPlanVariationId: "FQ7CDXXWSLUJRPM3GFJSJGZ7", + }, + ], + }); + }); +}); diff --git a/tests/wire/team.test.ts b/tests/wire/team.test.ts new file mode 100644 index 000000000..6d885317e --- /dev/null +++ b/tests/wire/team.test.ts @@ -0,0 +1,225 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Team", () => { + test("ListJobs", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + jobs: [ + { + id: "VDNpRv8da51NU8qZFC5zDWpF", + title: "Cashier", + is_tip_eligible: true, + created_at: "2021-06-11T22:55:45Z", + updated_at: "2021-06-11T22:55:45Z", + version: 2, + }, + { + id: "FjS8x95cqHiMenw4f1NAUH4P", + title: "Chef", + is_tip_eligible: false, + created_at: "2021-06-11T22:55:45Z", + updated_at: "2021-06-11T22:55:45Z", + version: 1, + }, + ], + cursor: "cursor", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/team-members/jobs") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.team.listJobs(); + expect(response).toEqual({ + jobs: [ + { + id: "VDNpRv8da51NU8qZFC5zDWpF", + title: "Cashier", + isTipEligible: true, + createdAt: "2021-06-11T22:55:45Z", + updatedAt: "2021-06-11T22:55:45Z", + version: 2, + }, + { + id: "FjS8x95cqHiMenw4f1NAUH4P", + title: "Chef", + isTipEligible: false, + createdAt: "2021-06-11T22:55:45Z", + updatedAt: "2021-06-11T22:55:45Z", + version: 1, + }, + ], + cursor: "cursor", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("CreateJob", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + job: { title: "Cashier", is_tip_eligible: true }, + idempotency_key: "idempotency-key-0", + }; + const rawResponseBody = { + job: { + id: "1yJlHapkseYnNPETIU1B", + title: "Cashier", + is_tip_eligible: true, + created_at: "2021-06-11T22:55:45Z", + updated_at: "2021-06-11T22:55:45Z", + version: 1, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/team-members/jobs") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.team.createJob({ + job: { + title: "Cashier", + isTipEligible: true, + }, + idempotencyKey: "idempotency-key-0", + }); + expect(response).toEqual({ + job: { + id: "1yJlHapkseYnNPETIU1B", + title: "Cashier", + isTipEligible: true, + createdAt: "2021-06-11T22:55:45Z", + updatedAt: "2021-06-11T22:55:45Z", + version: 1, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("RetrieveJob", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + job: { + id: "1yJlHapkseYnNPETIU1B", + title: "Cashier 1", + is_tip_eligible: true, + created_at: "2021-06-11T22:55:45Z", + updated_at: "2021-06-11T22:55:45Z", + version: 2, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/team-members/jobs/job_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.team.retrieveJob({ + jobId: "job_id", + }); + expect(response).toEqual({ + job: { + id: "1yJlHapkseYnNPETIU1B", + title: "Cashier 1", + isTipEligible: true, + createdAt: "2021-06-11T22:55:45Z", + updatedAt: "2021-06-11T22:55:45Z", + version: 2, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("UpdateJob", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { job: { title: "Cashier 1", is_tip_eligible: true } }; + const rawResponseBody = { + job: { + id: "1yJlHapkseYnNPETIU1B", + title: "Cashier 1", + is_tip_eligible: true, + created_at: "2021-06-11T22:55:45Z", + updated_at: "2021-06-13T12:55:45Z", + version: 2, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .put("/v2/team-members/jobs/job_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.team.updateJob({ + jobId: "job_id", + job: { + title: "Cashier 1", + isTipEligible: true, + }, + }); + expect(response).toEqual({ + job: { + id: "1yJlHapkseYnNPETIU1B", + title: "Cashier 1", + isTipEligible: true, + createdAt: "2021-06-11T22:55:45Z", + updatedAt: "2021-06-13T12:55:45Z", + version: 2, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/teamMembers.test.ts b/tests/wire/teamMembers.test.ts new file mode 100644 index 000000000..8133f3ebb --- /dev/null +++ b/tests/wire/teamMembers.test.ts @@ -0,0 +1,1338 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("TeamMembers", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "idempotency-key-0", + team_member: { + reference_id: "reference_id_1", + status: "ACTIVE", + given_name: "Joe", + family_name: "Doe", + email_address: "joe_doe@gmail.com", + phone_number: "+14159283333", + assigned_locations: { + assignment_type: "EXPLICIT_LOCATIONS", + location_ids: ["YSGH2WBKG94QZ", "GA2Y9HSJ8KRYT"], + }, + wage_setting: { + job_assignments: [ + { + pay_type: "SALARY", + annual_rate: { amount: BigInt(3000000), currency: "USD" }, + weekly_hours: 40, + job_id: "FjS8x95cqHiMenw4f1NAUH4P", + }, + { + pay_type: "HOURLY", + hourly_rate: { amount: BigInt(2000), currency: "USD" }, + job_id: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + is_overtime_exempt: true, + }, + }, + }; + const rawResponseBody = { + team_member: { + id: "1yJlHapkseYnNPETIU1B", + reference_id: "reference_id_1", + is_owner: false, + status: "ACTIVE", + given_name: "Joe", + family_name: "Doe", + email_address: "joe_doe@example.com", + phone_number: "+14159283333", + created_at: "2021-06-11T22:55:45Z", + updated_at: "2021-06-11T22:55:45Z", + assigned_locations: { + assignment_type: "EXPLICIT_LOCATIONS", + location_ids: ["GA2Y9HSJ8KRYT", "YSGH2WBKG94QZ"], + }, + wage_setting: { + team_member_id: "1yJlHapkseYnNPETIU1B", + job_assignments: [ + { + job_title: "Manager", + pay_type: "SALARY", + hourly_rate: { amount: BigInt(1443), currency: "USD" }, + annual_rate: { amount: BigInt(3000000), currency: "USD" }, + weekly_hours: 40, + job_id: "FjS8x95cqHiMenw4f1NAUH4P", + }, + { + job_title: "Cashier", + pay_type: "HOURLY", + hourly_rate: { amount: BigInt(2000), currency: "USD" }, + job_id: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + is_overtime_exempt: true, + version: 1, + created_at: "2021-06-11T22:55:45Z", + updated_at: "2021-06-11T22:55:45Z", + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/team-members") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.teamMembers.create({ + idempotencyKey: "idempotency-key-0", + teamMember: { + referenceId: "reference_id_1", + status: "ACTIVE", + givenName: "Joe", + familyName: "Doe", + emailAddress: "joe_doe@gmail.com", + phoneNumber: "+14159283333", + assignedLocations: { + assignmentType: "EXPLICIT_LOCATIONS", + locationIds: ["YSGH2WBKG94QZ", "GA2Y9HSJ8KRYT"], + }, + wageSetting: { + jobAssignments: [ + { + payType: "SALARY", + annualRate: { + amount: BigInt("3000000"), + currency: "USD", + }, + weeklyHours: 40, + jobId: "FjS8x95cqHiMenw4f1NAUH4P", + }, + { + payType: "HOURLY", + hourlyRate: { + amount: BigInt("2000"), + currency: "USD", + }, + jobId: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + isOvertimeExempt: true, + }, + }, + }); + expect(response).toEqual({ + teamMember: { + id: "1yJlHapkseYnNPETIU1B", + referenceId: "reference_id_1", + isOwner: false, + status: "ACTIVE", + givenName: "Joe", + familyName: "Doe", + emailAddress: "joe_doe@example.com", + phoneNumber: "+14159283333", + createdAt: "2021-06-11T22:55:45Z", + updatedAt: "2021-06-11T22:55:45Z", + assignedLocations: { + assignmentType: "EXPLICIT_LOCATIONS", + locationIds: ["GA2Y9HSJ8KRYT", "YSGH2WBKG94QZ"], + }, + wageSetting: { + teamMemberId: "1yJlHapkseYnNPETIU1B", + jobAssignments: [ + { + jobTitle: "Manager", + payType: "SALARY", + hourlyRate: { + amount: BigInt("1443"), + currency: "USD", + }, + annualRate: { + amount: BigInt("3000000"), + currency: "USD", + }, + weeklyHours: 40, + jobId: "FjS8x95cqHiMenw4f1NAUH4P", + }, + { + jobTitle: "Cashier", + payType: "HOURLY", + hourlyRate: { + amount: BigInt("2000"), + currency: "USD", + }, + jobId: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + isOvertimeExempt: true, + version: 1, + createdAt: "2021-06-11T22:55:45Z", + updatedAt: "2021-06-11T22:55:45Z", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("batchCreate", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + team_members: { + "idempotency-key-1": { + team_member: { + reference_id: "reference_id_1", + given_name: "Joe", + family_name: "Doe", + email_address: "joe_doe@gmail.com", + phone_number: "+14159283333", + assigned_locations: { + assignment_type: "EXPLICIT_LOCATIONS", + location_ids: ["YSGH2WBKG94QZ", "GA2Y9HSJ8KRYT"], + }, + }, + }, + "idempotency-key-2": { + team_member: { + reference_id: "reference_id_2", + given_name: "Jane", + family_name: "Smith", + email_address: "jane_smith@gmail.com", + phone_number: "+14159223334", + assigned_locations: { assignment_type: "ALL_CURRENT_AND_FUTURE_LOCATIONS" }, + }, + }, + }, + }; + const rawResponseBody = { + team_members: { + "idempotency-key-1": { + team_member: { + id: "ywhG1qfIOoqsHfVRubFV", + reference_id: "reference_id_1", + is_owner: false, + status: "ACTIVE", + given_name: "Joe", + family_name: "Doe", + email_address: "joe_doe@gmail.com", + phone_number: "+14159283333", + assigned_locations: { + assignment_type: "EXPLICIT_LOCATIONS", + location_ids: ["GA2Y9HSJ8KRYT", "YSGH2WBKG94QZ"], + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + "idempotency-key-2": { + team_member: { + id: "IF_Ncrg7fHhCqxVI9T6R", + reference_id: "reference_id_2", + is_owner: false, + status: "ACTIVE", + given_name: "Jane", + family_name: "Smith", + email_address: "jane_smith@gmail.com", + phone_number: "+14159223334", + assigned_locations: { assignment_type: "ALL_CURRENT_AND_FUTURE_LOCATIONS" }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/team-members/bulk-create") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.teamMembers.batchCreate({ + teamMembers: { + "idempotency-key-1": { + teamMember: { + referenceId: "reference_id_1", + givenName: "Joe", + familyName: "Doe", + emailAddress: "joe_doe@gmail.com", + phoneNumber: "+14159283333", + assignedLocations: { + assignmentType: "EXPLICIT_LOCATIONS", + locationIds: ["YSGH2WBKG94QZ", "GA2Y9HSJ8KRYT"], + }, + }, + }, + "idempotency-key-2": { + teamMember: { + referenceId: "reference_id_2", + givenName: "Jane", + familyName: "Smith", + emailAddress: "jane_smith@gmail.com", + phoneNumber: "+14159223334", + assignedLocations: { + assignmentType: "ALL_CURRENT_AND_FUTURE_LOCATIONS", + }, + }, + }, + }, + }); + expect(response).toEqual({ + teamMembers: { + "idempotency-key-1": { + teamMember: { + id: "ywhG1qfIOoqsHfVRubFV", + referenceId: "reference_id_1", + isOwner: false, + status: "ACTIVE", + givenName: "Joe", + familyName: "Doe", + emailAddress: "joe_doe@gmail.com", + phoneNumber: "+14159283333", + assignedLocations: { + assignmentType: "EXPLICIT_LOCATIONS", + locationIds: ["GA2Y9HSJ8KRYT", "YSGH2WBKG94QZ"], + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + "idempotency-key-2": { + teamMember: { + id: "IF_Ncrg7fHhCqxVI9T6R", + referenceId: "reference_id_2", + isOwner: false, + status: "ACTIVE", + givenName: "Jane", + familyName: "Smith", + emailAddress: "jane_smith@gmail.com", + phoneNumber: "+14159223334", + assignedLocations: { + assignmentType: "ALL_CURRENT_AND_FUTURE_LOCATIONS", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("batchUpdate", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + team_members: { + "AFMwA08kR-MIF-3Vs0OE": { + team_member: { + reference_id: "reference_id_2", + is_owner: false, + status: "ACTIVE", + given_name: "Jane", + family_name: "Smith", + email_address: "jane_smith@gmail.com", + phone_number: "+14159223334", + assigned_locations: { assignment_type: "ALL_CURRENT_AND_FUTURE_LOCATIONS" }, + }, + }, + "fpgteZNMaf0qOK-a4t6P": { + team_member: { + reference_id: "reference_id_1", + is_owner: false, + status: "ACTIVE", + given_name: "Joe", + family_name: "Doe", + email_address: "joe_doe@gmail.com", + phone_number: "+14159283333", + assigned_locations: { + assignment_type: "EXPLICIT_LOCATIONS", + location_ids: ["YSGH2WBKG94QZ", "GA2Y9HSJ8KRYT"], + }, + }, + }, + }, + }; + const rawResponseBody = { + team_members: { + "AFMwA08kR-MIF-3Vs0OE": { + team_member: { + id: "AFMwA08kR-MIF-3Vs0OE", + reference_id: "reference_id_2", + is_owner: false, + status: "ACTIVE", + given_name: "Jane", + family_name: "Smith", + email_address: "jane_smith@example.com", + phone_number: "+14159223334", + created_at: "2020-03-24T18:14:00Z", + updated_at: "2020-03-24T18:18:00Z", + assigned_locations: { assignment_type: "ALL_CURRENT_AND_FUTURE_LOCATIONS" }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + "fpgteZNMaf0qOK-a4t6P": { + team_member: { + id: "fpgteZNMaf0qOK-a4t6P", + reference_id: "reference_id_1", + is_owner: false, + status: "ACTIVE", + given_name: "Joe", + family_name: "Doe", + email_address: "joe_doe@example.com", + phone_number: "+14159283333", + created_at: "2020-03-24T18:14:00Z", + updated_at: "2020-03-24T18:18:00Z", + assigned_locations: { + assignment_type: "EXPLICIT_LOCATIONS", + location_ids: ["GA2Y9HSJ8KRYT", "YSGH2WBKG94QZ"], + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/team-members/bulk-update") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.teamMembers.batchUpdate({ + teamMembers: { + "AFMwA08kR-MIF-3Vs0OE": { + teamMember: { + referenceId: "reference_id_2", + isOwner: false, + status: "ACTIVE", + givenName: "Jane", + familyName: "Smith", + emailAddress: "jane_smith@gmail.com", + phoneNumber: "+14159223334", + assignedLocations: { + assignmentType: "ALL_CURRENT_AND_FUTURE_LOCATIONS", + }, + }, + }, + "fpgteZNMaf0qOK-a4t6P": { + teamMember: { + referenceId: "reference_id_1", + isOwner: false, + status: "ACTIVE", + givenName: "Joe", + familyName: "Doe", + emailAddress: "joe_doe@gmail.com", + phoneNumber: "+14159283333", + assignedLocations: { + assignmentType: "EXPLICIT_LOCATIONS", + locationIds: ["YSGH2WBKG94QZ", "GA2Y9HSJ8KRYT"], + }, + }, + }, + }, + }); + expect(response).toEqual({ + teamMembers: { + "AFMwA08kR-MIF-3Vs0OE": { + teamMember: { + id: "AFMwA08kR-MIF-3Vs0OE", + referenceId: "reference_id_2", + isOwner: false, + status: "ACTIVE", + givenName: "Jane", + familyName: "Smith", + emailAddress: "jane_smith@example.com", + phoneNumber: "+14159223334", + createdAt: "2020-03-24T18:14:00Z", + updatedAt: "2020-03-24T18:18:00Z", + assignedLocations: { + assignmentType: "ALL_CURRENT_AND_FUTURE_LOCATIONS", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + "fpgteZNMaf0qOK-a4t6P": { + teamMember: { + id: "fpgteZNMaf0qOK-a4t6P", + referenceId: "reference_id_1", + isOwner: false, + status: "ACTIVE", + givenName: "Joe", + familyName: "Doe", + emailAddress: "joe_doe@example.com", + phoneNumber: "+14159283333", + createdAt: "2020-03-24T18:14:00Z", + updatedAt: "2020-03-24T18:18:00Z", + assignedLocations: { + assignmentType: "EXPLICIT_LOCATIONS", + locationIds: ["GA2Y9HSJ8KRYT", "YSGH2WBKG94QZ"], + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("search", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { query: { filter: { location_ids: ["0G5P3VGACMMQZ"], status: "ACTIVE" } }, limit: 10 }; + const rawResponseBody = { + team_members: [ + { + id: "-3oZQKPKVk6gUXU_V5Qa", + reference_id: "12345678", + is_owner: false, + status: "ACTIVE", + given_name: "Johnny", + family_name: "Cash", + email_address: "johnny_cash@squareup.com", + phone_number: "phone_number", + created_at: "2019-07-10T17:26:48Z", + updated_at: "2020-04-28T21:49:28Z", + assigned_locations: { assignment_type: "ALL_CURRENT_AND_FUTURE_LOCATIONS" }, + wage_setting: { + team_member_id: "-3oZQKPKVk6gUXU_V5Qa", + job_assignments: [ + { + job_title: "Manager", + pay_type: "SALARY", + hourly_rate: { amount: BigInt(1443), currency: "USD" }, + annual_rate: { amount: BigInt(3000000), currency: "USD" }, + weekly_hours: 40, + job_id: "FjS8x95cqHiMenw4f1NAUH4P", + }, + { + job_title: "Cashier", + pay_type: "HOURLY", + hourly_rate: { amount: BigInt(2000), currency: "USD" }, + job_id: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + is_overtime_exempt: true, + version: 1, + created_at: "2021-06-11T22:55:45Z", + updated_at: "2021-06-11T22:55:45Z", + }, + }, + { + id: "1AVJj0DjkzbmbJw5r4KK", + reference_id: "abcded", + is_owner: false, + status: "ACTIVE", + given_name: "Lombard", + family_name: "Smith", + email_address: "email_address", + phone_number: "+14155552671", + created_at: "2020-03-24T18:14:01Z", + updated_at: "2020-06-09T17:38:05Z", + assigned_locations: { assignment_type: "ALL_CURRENT_AND_FUTURE_LOCATIONS" }, + wage_setting: { + team_member_id: "1AVJj0DjkzbmbJw5r4KK", + job_assignments: [ + { + job_title: "Cashier", + pay_type: "HOURLY", + hourly_rate: { amount: BigInt(2400), currency: "USD" }, + job_id: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + is_overtime_exempt: true, + version: 2, + created_at: "2020-03-24T18:14:01Z", + updated_at: "2020-06-09T17:38:05Z", + }, + }, + { + id: "2JCmiJol_KKFs9z2Evim", + reference_id: "reference_id", + is_owner: false, + status: "ACTIVE", + given_name: "Monica", + family_name: "Sway", + email_address: "email_address", + phone_number: "phone_number", + created_at: "2020-03-24T01:09:25Z", + updated_at: "2020-03-24T01:11:25Z", + assigned_locations: { assignment_type: "ALL_CURRENT_AND_FUTURE_LOCATIONS" }, + wage_setting: { + team_member_id: "2JCmiJol_KKFs9z2Evim", + job_assignments: [ + { + job_title: "Cashier", + pay_type: "HOURLY", + hourly_rate: { amount: BigInt(2400), currency: "USD" }, + job_id: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + is_overtime_exempt: true, + version: 1, + created_at: "2020-03-24T01:09:25Z", + updated_at: "2020-03-24T01:09:25Z", + }, + }, + { + id: "4uXcJQSLtbk3F0UQHFNQ", + reference_id: "reference_id", + is_owner: false, + status: "ACTIVE", + given_name: "Elton", + family_name: "Ipsum", + email_address: "email_address", + phone_number: "phone_number", + created_at: "2020-03-24T01:09:23Z", + updated_at: "2020-03-24T01:15:23Z", + assigned_locations: { assignment_type: "ALL_CURRENT_AND_FUTURE_LOCATIONS" }, + }, + { + id: "5CoUpyrw1YwGWcRd-eDL", + reference_id: "reference_id", + is_owner: false, + status: "ACTIVE", + given_name: "Steven", + family_name: "Lo", + email_address: "email_address", + phone_number: "phone_number", + created_at: "2020-03-24T01:09:23Z", + updated_at: "2020-03-24T01:19:23Z", + assigned_locations: { assignment_type: "ALL_CURRENT_AND_FUTURE_LOCATIONS" }, + }, + { + id: "5MRPTTp8MMBLVSmzrGha", + reference_id: "reference_id", + is_owner: false, + status: "ACTIVE", + given_name: "Patrick", + family_name: "Steward", + email_address: "email_address", + phone_number: "+14155552671", + created_at: "2020-03-24T18:14:03Z", + updated_at: "2020-03-24T18:18:03Z", + assigned_locations: { assignment_type: "ALL_CURRENT_AND_FUTURE_LOCATIONS" }, + wage_setting: { + team_member_id: "5MRPTTp8MMBLVSmzrGha", + job_assignments: [ + { + job_title: "Cashier", + pay_type: "HOURLY", + hourly_rate: { amount: BigInt(2000), currency: "USD" }, + job_id: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + is_overtime_exempt: true, + version: 1, + created_at: "2020-03-24T18:14:03Z", + updated_at: "2020-03-24T18:14:03Z", + }, + }, + { + id: "7F5ZxsfRnkexhu1PTbfh", + reference_id: "reference_id", + is_owner: false, + status: "ACTIVE", + given_name: "Ivy", + family_name: "Manny", + email_address: "email_address", + phone_number: "phone_number", + created_at: "2020-03-24T01:09:25Z", + updated_at: "2020-03-24T01:09:25Z", + assigned_locations: { assignment_type: "ALL_CURRENT_AND_FUTURE_LOCATIONS" }, + }, + { + id: "808X9HR72yKvVaigQXf4", + reference_id: "reference_id", + is_owner: false, + status: "ACTIVE", + given_name: "John", + family_name: "Smith", + email_address: "john_smith@example.com", + phone_number: "+14155552671", + created_at: "2020-03-24T18:14:02Z", + updated_at: "2020-03-24T18:14:02Z", + assigned_locations: { assignment_type: "ALL_CURRENT_AND_FUTURE_LOCATIONS" }, + }, + { + id: "9MVDVoY4hazkWKGo_OuZ", + reference_id: "reference_id", + is_owner: false, + status: "ACTIVE", + given_name: "Robert", + family_name: "Wen", + email_address: "r_wen@example.com", + phone_number: "+14155552671", + created_at: "2020-03-24T18:14:00Z", + updated_at: "2020-03-24T18:14:00Z", + assigned_locations: { assignment_type: "ALL_CURRENT_AND_FUTURE_LOCATIONS" }, + }, + { + id: "9UglUjOXQ13-hMFypCft", + reference_id: "reference_id", + is_owner: false, + status: "ACTIVE", + given_name: "Ashley", + family_name: "Simpson", + email_address: "asimpson@example.com", + phone_number: "+14155552671", + created_at: "2020-03-24T18:14:00Z", + updated_at: "2020-03-24T18:18:00Z", + assigned_locations: { assignment_type: "ALL_CURRENT_AND_FUTURE_LOCATIONS" }, + wage_setting: { + team_member_id: "9UglUjOXQ13-hMFypCft", + job_assignments: [ + { + job_title: "Cashier", + pay_type: "HOURLY", + hourly_rate: { amount: BigInt(2000), currency: "USD" }, + job_id: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + is_overtime_exempt: true, + version: 1, + created_at: "2020-03-24T18:14:00Z", + updated_at: "2020-03-24T18:14:03Z", + }, + }, + ], + cursor: "N:9UglUjOXQ13-hMFypCft", + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .post("/v2/team-members/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.teamMembers.search({ + query: { + filter: { + locationIds: ["0G5P3VGACMMQZ"], + status: "ACTIVE", + }, + }, + limit: 10, + }); + expect(response).toEqual({ + teamMembers: [ + { + id: "-3oZQKPKVk6gUXU_V5Qa", + referenceId: "12345678", + isOwner: false, + status: "ACTIVE", + givenName: "Johnny", + familyName: "Cash", + emailAddress: "johnny_cash@squareup.com", + phoneNumber: "phone_number", + createdAt: "2019-07-10T17:26:48Z", + updatedAt: "2020-04-28T21:49:28Z", + assignedLocations: { + assignmentType: "ALL_CURRENT_AND_FUTURE_LOCATIONS", + }, + wageSetting: { + teamMemberId: "-3oZQKPKVk6gUXU_V5Qa", + jobAssignments: [ + { + jobTitle: "Manager", + payType: "SALARY", + hourlyRate: { + amount: BigInt("1443"), + currency: "USD", + }, + annualRate: { + amount: BigInt("3000000"), + currency: "USD", + }, + weeklyHours: 40, + jobId: "FjS8x95cqHiMenw4f1NAUH4P", + }, + { + jobTitle: "Cashier", + payType: "HOURLY", + hourlyRate: { + amount: BigInt("2000"), + currency: "USD", + }, + jobId: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + isOvertimeExempt: true, + version: 1, + createdAt: "2021-06-11T22:55:45Z", + updatedAt: "2021-06-11T22:55:45Z", + }, + }, + { + id: "1AVJj0DjkzbmbJw5r4KK", + referenceId: "abcded", + isOwner: false, + status: "ACTIVE", + givenName: "Lombard", + familyName: "Smith", + emailAddress: "email_address", + phoneNumber: "+14155552671", + createdAt: "2020-03-24T18:14:01Z", + updatedAt: "2020-06-09T17:38:05Z", + assignedLocations: { + assignmentType: "ALL_CURRENT_AND_FUTURE_LOCATIONS", + }, + wageSetting: { + teamMemberId: "1AVJj0DjkzbmbJw5r4KK", + jobAssignments: [ + { + jobTitle: "Cashier", + payType: "HOURLY", + hourlyRate: { + amount: BigInt("2400"), + currency: "USD", + }, + jobId: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + isOvertimeExempt: true, + version: 2, + createdAt: "2020-03-24T18:14:01Z", + updatedAt: "2020-06-09T17:38:05Z", + }, + }, + { + id: "2JCmiJol_KKFs9z2Evim", + referenceId: "reference_id", + isOwner: false, + status: "ACTIVE", + givenName: "Monica", + familyName: "Sway", + emailAddress: "email_address", + phoneNumber: "phone_number", + createdAt: "2020-03-24T01:09:25Z", + updatedAt: "2020-03-24T01:11:25Z", + assignedLocations: { + assignmentType: "ALL_CURRENT_AND_FUTURE_LOCATIONS", + }, + wageSetting: { + teamMemberId: "2JCmiJol_KKFs9z2Evim", + jobAssignments: [ + { + jobTitle: "Cashier", + payType: "HOURLY", + hourlyRate: { + amount: BigInt("2400"), + currency: "USD", + }, + jobId: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + isOvertimeExempt: true, + version: 1, + createdAt: "2020-03-24T01:09:25Z", + updatedAt: "2020-03-24T01:09:25Z", + }, + }, + { + id: "4uXcJQSLtbk3F0UQHFNQ", + referenceId: "reference_id", + isOwner: false, + status: "ACTIVE", + givenName: "Elton", + familyName: "Ipsum", + emailAddress: "email_address", + phoneNumber: "phone_number", + createdAt: "2020-03-24T01:09:23Z", + updatedAt: "2020-03-24T01:15:23Z", + assignedLocations: { + assignmentType: "ALL_CURRENT_AND_FUTURE_LOCATIONS", + }, + }, + { + id: "5CoUpyrw1YwGWcRd-eDL", + referenceId: "reference_id", + isOwner: false, + status: "ACTIVE", + givenName: "Steven", + familyName: "Lo", + emailAddress: "email_address", + phoneNumber: "phone_number", + createdAt: "2020-03-24T01:09:23Z", + updatedAt: "2020-03-24T01:19:23Z", + assignedLocations: { + assignmentType: "ALL_CURRENT_AND_FUTURE_LOCATIONS", + }, + }, + { + id: "5MRPTTp8MMBLVSmzrGha", + referenceId: "reference_id", + isOwner: false, + status: "ACTIVE", + givenName: "Patrick", + familyName: "Steward", + emailAddress: "email_address", + phoneNumber: "+14155552671", + createdAt: "2020-03-24T18:14:03Z", + updatedAt: "2020-03-24T18:18:03Z", + assignedLocations: { + assignmentType: "ALL_CURRENT_AND_FUTURE_LOCATIONS", + }, + wageSetting: { + teamMemberId: "5MRPTTp8MMBLVSmzrGha", + jobAssignments: [ + { + jobTitle: "Cashier", + payType: "HOURLY", + hourlyRate: { + amount: BigInt("2000"), + currency: "USD", + }, + jobId: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + isOvertimeExempt: true, + version: 1, + createdAt: "2020-03-24T18:14:03Z", + updatedAt: "2020-03-24T18:14:03Z", + }, + }, + { + id: "7F5ZxsfRnkexhu1PTbfh", + referenceId: "reference_id", + isOwner: false, + status: "ACTIVE", + givenName: "Ivy", + familyName: "Manny", + emailAddress: "email_address", + phoneNumber: "phone_number", + createdAt: "2020-03-24T01:09:25Z", + updatedAt: "2020-03-24T01:09:25Z", + assignedLocations: { + assignmentType: "ALL_CURRENT_AND_FUTURE_LOCATIONS", + }, + }, + { + id: "808X9HR72yKvVaigQXf4", + referenceId: "reference_id", + isOwner: false, + status: "ACTIVE", + givenName: "John", + familyName: "Smith", + emailAddress: "john_smith@example.com", + phoneNumber: "+14155552671", + createdAt: "2020-03-24T18:14:02Z", + updatedAt: "2020-03-24T18:14:02Z", + assignedLocations: { + assignmentType: "ALL_CURRENT_AND_FUTURE_LOCATIONS", + }, + }, + { + id: "9MVDVoY4hazkWKGo_OuZ", + referenceId: "reference_id", + isOwner: false, + status: "ACTIVE", + givenName: "Robert", + familyName: "Wen", + emailAddress: "r_wen@example.com", + phoneNumber: "+14155552671", + createdAt: "2020-03-24T18:14:00Z", + updatedAt: "2020-03-24T18:14:00Z", + assignedLocations: { + assignmentType: "ALL_CURRENT_AND_FUTURE_LOCATIONS", + }, + }, + { + id: "9UglUjOXQ13-hMFypCft", + referenceId: "reference_id", + isOwner: false, + status: "ACTIVE", + givenName: "Ashley", + familyName: "Simpson", + emailAddress: "asimpson@example.com", + phoneNumber: "+14155552671", + createdAt: "2020-03-24T18:14:00Z", + updatedAt: "2020-03-24T18:18:00Z", + assignedLocations: { + assignmentType: "ALL_CURRENT_AND_FUTURE_LOCATIONS", + }, + wageSetting: { + teamMemberId: "9UglUjOXQ13-hMFypCft", + jobAssignments: [ + { + jobTitle: "Cashier", + payType: "HOURLY", + hourlyRate: { + amount: BigInt("2000"), + currency: "USD", + }, + jobId: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + isOvertimeExempt: true, + version: 1, + createdAt: "2020-03-24T18:14:00Z", + updatedAt: "2020-03-24T18:14:03Z", + }, + }, + ], + cursor: "N:9UglUjOXQ13-hMFypCft", + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + team_member: { + id: "1yJlHapkseYnNPETIU1B", + reference_id: "reference_id_1", + is_owner: false, + status: "ACTIVE", + given_name: "Joe", + family_name: "Doe", + email_address: "joe_doe@example.com", + phone_number: "+14159283333", + created_at: "2021-06-11T22:55:45Z", + updated_at: "2021-06-15T17:38:05Z", + assigned_locations: { + assignment_type: "EXPLICIT_LOCATIONS", + location_ids: ["GA2Y9HSJ8KRYT", "YSGH2WBKG94QZ"], + }, + wage_setting: { + team_member_id: "1yJlHapkseYnNPETIU1B", + job_assignments: [ + { + job_title: "Manager", + pay_type: "SALARY", + hourly_rate: { amount: BigInt(1443), currency: "USD" }, + annual_rate: { amount: BigInt(3000000), currency: "USD" }, + weekly_hours: 40, + job_id: "FjS8x95cqHiMenw4f1NAUH4P", + }, + { + job_title: "Cashier", + pay_type: "HOURLY", + hourly_rate: { amount: BigInt(2000), currency: "USD" }, + job_id: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + is_overtime_exempt: true, + version: 1, + created_at: "2021-06-11T22:55:45Z", + updated_at: "2021-06-11T22:55:45Z", + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/team-members/team_member_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.teamMembers.get({ + teamMemberId: "team_member_id", + }); + expect(response).toEqual({ + teamMember: { + id: "1yJlHapkseYnNPETIU1B", + referenceId: "reference_id_1", + isOwner: false, + status: "ACTIVE", + givenName: "Joe", + familyName: "Doe", + emailAddress: "joe_doe@example.com", + phoneNumber: "+14159283333", + createdAt: "2021-06-11T22:55:45Z", + updatedAt: "2021-06-15T17:38:05Z", + assignedLocations: { + assignmentType: "EXPLICIT_LOCATIONS", + locationIds: ["GA2Y9HSJ8KRYT", "YSGH2WBKG94QZ"], + }, + wageSetting: { + teamMemberId: "1yJlHapkseYnNPETIU1B", + jobAssignments: [ + { + jobTitle: "Manager", + payType: "SALARY", + hourlyRate: { + amount: BigInt("1443"), + currency: "USD", + }, + annualRate: { + amount: BigInt("3000000"), + currency: "USD", + }, + weeklyHours: 40, + jobId: "FjS8x95cqHiMenw4f1NAUH4P", + }, + { + jobTitle: "Cashier", + payType: "HOURLY", + hourlyRate: { + amount: BigInt("2000"), + currency: "USD", + }, + jobId: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + isOvertimeExempt: true, + version: 1, + createdAt: "2021-06-11T22:55:45Z", + updatedAt: "2021-06-11T22:55:45Z", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + team_member: { + reference_id: "reference_id_1", + status: "ACTIVE", + given_name: "Joe", + family_name: "Doe", + email_address: "joe_doe@gmail.com", + phone_number: "+14159283333", + assigned_locations: { + assignment_type: "EXPLICIT_LOCATIONS", + location_ids: ["YSGH2WBKG94QZ", "GA2Y9HSJ8KRYT"], + }, + wage_setting: { + job_assignments: [ + { + pay_type: "SALARY", + annual_rate: { amount: BigInt(3000000), currency: "USD" }, + weekly_hours: 40, + job_id: "FjS8x95cqHiMenw4f1NAUH4P", + }, + { + pay_type: "HOURLY", + hourly_rate: { amount: BigInt(1200), currency: "USD" }, + job_id: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + is_overtime_exempt: true, + }, + }, + }; + const rawResponseBody = { + team_member: { + id: "1yJlHapkseYnNPETIU1B", + reference_id: "reference_id_1", + is_owner: false, + status: "ACTIVE", + given_name: "Joe", + family_name: "Doe", + email_address: "joe_doe@example.com", + phone_number: "+14159283333", + created_at: "2021-06-11T22:55:45Z", + updated_at: "2021-06-15T17:38:05Z", + assigned_locations: { + assignment_type: "EXPLICIT_LOCATIONS", + location_ids: ["GA2Y9HSJ8KRYT", "YSGH2WBKG94QZ"], + }, + wage_setting: { + team_member_id: "1yJlHapkseYnNPETIU1B", + job_assignments: [ + { + job_title: "Manager", + pay_type: "SALARY", + hourly_rate: { amount: BigInt(1443), currency: "USD" }, + annual_rate: { amount: BigInt(3000000), currency: "USD" }, + weekly_hours: 40, + job_id: "FjS8x95cqHiMenw4f1NAUH4P", + }, + { + job_title: "Cashier", + pay_type: "HOURLY", + hourly_rate: { amount: BigInt(1200), currency: "USD" }, + job_id: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + is_overtime_exempt: true, + version: 1, + created_at: "2021-06-11T22:55:45Z", + updated_at: "2021-06-11T22:55:45Z", + }, + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .put("/v2/team-members/team_member_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.teamMembers.update({ + teamMemberId: "team_member_id", + body: { + teamMember: { + referenceId: "reference_id_1", + status: "ACTIVE", + givenName: "Joe", + familyName: "Doe", + emailAddress: "joe_doe@gmail.com", + phoneNumber: "+14159283333", + assignedLocations: { + assignmentType: "EXPLICIT_LOCATIONS", + locationIds: ["YSGH2WBKG94QZ", "GA2Y9HSJ8KRYT"], + }, + wageSetting: { + jobAssignments: [ + { + payType: "SALARY", + annualRate: { + amount: BigInt("3000000"), + currency: "USD", + }, + weeklyHours: 40, + jobId: "FjS8x95cqHiMenw4f1NAUH4P", + }, + { + payType: "HOURLY", + hourlyRate: { + amount: BigInt("1200"), + currency: "USD", + }, + jobId: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + isOvertimeExempt: true, + }, + }, + }, + }); + expect(response).toEqual({ + teamMember: { + id: "1yJlHapkseYnNPETIU1B", + referenceId: "reference_id_1", + isOwner: false, + status: "ACTIVE", + givenName: "Joe", + familyName: "Doe", + emailAddress: "joe_doe@example.com", + phoneNumber: "+14159283333", + createdAt: "2021-06-11T22:55:45Z", + updatedAt: "2021-06-15T17:38:05Z", + assignedLocations: { + assignmentType: "EXPLICIT_LOCATIONS", + locationIds: ["GA2Y9HSJ8KRYT", "YSGH2WBKG94QZ"], + }, + wageSetting: { + teamMemberId: "1yJlHapkseYnNPETIU1B", + jobAssignments: [ + { + jobTitle: "Manager", + payType: "SALARY", + hourlyRate: { + amount: BigInt("1443"), + currency: "USD", + }, + annualRate: { + amount: BigInt("3000000"), + currency: "USD", + }, + weeklyHours: 40, + jobId: "FjS8x95cqHiMenw4f1NAUH4P", + }, + { + jobTitle: "Cashier", + payType: "HOURLY", + hourlyRate: { + amount: BigInt("1200"), + currency: "USD", + }, + jobId: "VDNpRv8da51NU8qZFC5zDWpF", + }, + ], + isOvertimeExempt: true, + version: 1, + createdAt: "2021-06-11T22:55:45Z", + updatedAt: "2021-06-11T22:55:45Z", + }, + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/teamMembers/wageSetting.test.ts b/tests/wire/teamMembers/wageSetting.test.ts new file mode 100644 index 000000000..84d31a474 --- /dev/null +++ b/tests/wire/teamMembers/wageSetting.test.ts @@ -0,0 +1,197 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("WageSetting", () => { + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + wage_setting: { + team_member_id: "1yJlHapkseYnNPETIU1B", + job_assignments: [ + { + job_title: "Manager", + pay_type: "SALARY", + hourly_rate: { amount: BigInt(2164), currency: "USD" }, + annual_rate: { amount: BigInt(4500000), currency: "USD" }, + weekly_hours: 40, + }, + ], + is_overtime_exempt: false, + version: 1, + created_at: "2020-06-11T23:01:21+00:00", + updated_at: "2020-06-11T23:01:21+00:00", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .get("/v2/team-members/team_member_id/wage-setting") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.teamMembers.wageSetting.get({ + teamMemberId: "team_member_id", + }); + expect(response).toEqual({ + wageSetting: { + teamMemberId: "1yJlHapkseYnNPETIU1B", + jobAssignments: [ + { + jobTitle: "Manager", + payType: "SALARY", + hourlyRate: { + amount: BigInt("2164"), + currency: "USD", + }, + annualRate: { + amount: BigInt("4500000"), + currency: "USD", + }, + weeklyHours: 40, + }, + ], + isOvertimeExempt: false, + version: 1, + createdAt: "2020-06-11T23:01:21+00:00", + updatedAt: "2020-06-11T23:01:21+00:00", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + wage_setting: { + job_assignments: [ + { + job_title: "Manager", + pay_type: "SALARY", + annual_rate: { amount: BigInt(3000000), currency: "USD" }, + weekly_hours: 40, + }, + { + job_title: "Cashier", + pay_type: "HOURLY", + hourly_rate: { amount: BigInt(2000), currency: "USD" }, + }, + ], + is_overtime_exempt: true, + }, + }; + const rawResponseBody = { + wage_setting: { + team_member_id: "-3oZQKPKVk6gUXU_V5Qa", + job_assignments: [ + { + job_title: "Manager", + pay_type: "SALARY", + hourly_rate: { amount: BigInt(1443), currency: "USD" }, + annual_rate: { amount: BigInt(3000000), currency: "USD" }, + weekly_hours: 40, + }, + { + job_title: "Cashier", + pay_type: "HOURLY", + hourly_rate: { amount: BigInt(2000), currency: "USD" }, + }, + ], + is_overtime_exempt: true, + version: 1, + created_at: "2019-07-10T17:26:48+00:00", + updated_at: "2020-06-11T23:12:04+00:00", + }, + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .put("/v2/team-members/team_member_id/wage-setting") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.teamMembers.wageSetting.update({ + teamMemberId: "team_member_id", + wageSetting: { + jobAssignments: [ + { + jobTitle: "Manager", + payType: "SALARY", + annualRate: { + amount: BigInt("3000000"), + currency: "USD", + }, + weeklyHours: 40, + }, + { + jobTitle: "Cashier", + payType: "HOURLY", + hourlyRate: { + amount: BigInt("2000"), + currency: "USD", + }, + }, + ], + isOvertimeExempt: true, + }, + }); + expect(response).toEqual({ + wageSetting: { + teamMemberId: "-3oZQKPKVk6gUXU_V5Qa", + jobAssignments: [ + { + jobTitle: "Manager", + payType: "SALARY", + hourlyRate: { + amount: BigInt("1443"), + currency: "USD", + }, + annualRate: { + amount: BigInt("3000000"), + currency: "USD", + }, + weeklyHours: 40, + }, + { + jobTitle: "Cashier", + payType: "HOURLY", + hourlyRate: { + amount: BigInt("2000"), + currency: "USD", + }, + }, + ], + isOvertimeExempt: true, + version: 1, + createdAt: "2019-07-10T17:26:48+00:00", + updatedAt: "2020-06-11T23:12:04+00:00", + }, + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); +}); diff --git a/tests/wire/terminal.test.ts b/tests/wire/terminal.test.ts new file mode 100644 index 000000000..1b051a6c9 --- /dev/null +++ b/tests/wire/terminal.test.ts @@ -0,0 +1,336 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Terminal", () => { + test("DismissTerminalAction", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + action: { + id: "termapia:abcdefg1234567", + device_id: "DEVICE_ID", + deadline_duration: "PT5M", + status: "COMPLETED", + cancel_reason: "BUYER_CANCELED", + created_at: "2021-07-28T23:22:07.476Z", + updated_at: "2021-07-28T23:22:29.511Z", + app_id: "APP_ID", + location_id: "location_id", + type: "CONFIRMATION", + qr_code_options: { title: "title", body: "body", barcode_contents: "barcode_contents" }, + save_card_options: { customer_id: "customer_id", card_id: "card_id", reference_id: "reference_id" }, + signature_options: { title: "title", body: "body", signature: [{}] }, + confirmation_options: { + title: "Marketing communications", + body: "I agree to receive promotional emails about future events and activities.", + agree_button_text: "Agree", + disagree_button_text: "Decline", + decision: { has_agreed: true }, + }, + receipt_options: { payment_id: "payment_id", print_only: true, is_duplicate: true }, + data_collection_options: { title: "title", body: "body", input_type: "EMAIL" }, + select_options: { + title: "title", + body: "body", + options: [{ reference_id: "reference_id", title: "title" }], + selected_option: { reference_id: "reference_id", title: "title" }, + }, + device_metadata: { + battery_percentage: "battery_percentage", + charging_state: "charging_state", + location_id: "location_id", + merchant_id: "merchant_id", + network_connection_type: "network_connection_type", + payment_region: "payment_region", + serial_number: "serial_number", + os_version: "os_version", + app_version: "app_version", + wifi_network_name: "wifi_network_name", + wifi_network_strength: "wifi_network_strength", + ip_address: "ip_address", + }, + await_next_action: true, + await_next_action_duration: "PT5M", + }, + }; + server + .mockEndpoint() + .post("/v2/terminals/actions/action_id/dismiss") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.terminal.dismissTerminalAction({ + actionId: "action_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + action: { + id: "termapia:abcdefg1234567", + deviceId: "DEVICE_ID", + deadlineDuration: "PT5M", + status: "COMPLETED", + cancelReason: "BUYER_CANCELED", + createdAt: "2021-07-28T23:22:07.476Z", + updatedAt: "2021-07-28T23:22:29.511Z", + appId: "APP_ID", + locationId: "location_id", + type: "CONFIRMATION", + qrCodeOptions: { + title: "title", + body: "body", + barcodeContents: "barcode_contents", + }, + saveCardOptions: { + customerId: "customer_id", + cardId: "card_id", + referenceId: "reference_id", + }, + signatureOptions: { + title: "title", + body: "body", + signature: [{}], + }, + confirmationOptions: { + title: "Marketing communications", + body: "I agree to receive promotional emails about future events and activities.", + agreeButtonText: "Agree", + disagreeButtonText: "Decline", + decision: { + hasAgreed: true, + }, + }, + receiptOptions: { + paymentId: "payment_id", + printOnly: true, + isDuplicate: true, + }, + dataCollectionOptions: { + title: "title", + body: "body", + inputType: "EMAIL", + }, + selectOptions: { + title: "title", + body: "body", + options: [ + { + referenceId: "reference_id", + title: "title", + }, + ], + selectedOption: { + referenceId: "reference_id", + title: "title", + }, + }, + deviceMetadata: { + batteryPercentage: "battery_percentage", + chargingState: "charging_state", + locationId: "location_id", + merchantId: "merchant_id", + networkConnectionType: "network_connection_type", + paymentRegion: "payment_region", + serialNumber: "serial_number", + osVersion: "os_version", + appVersion: "app_version", + wifiNetworkName: "wifi_network_name", + wifiNetworkStrength: "wifi_network_strength", + ipAddress: "ip_address", + }, + awaitNextAction: true, + awaitNextActionDuration: "PT5M", + }, + }); + }); + + test("DismissTerminalCheckout", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + checkout: { + id: "LmZEKbo3SBfqO", + amount_money: { amount: BigInt(2610), currency: "USD" }, + reference_id: "reference_id", + note: "note", + order_id: "order_id", + payment_options: { + autocomplete: true, + delay_duration: "delay_duration", + accept_partial_authorization: true, + delay_action: "CANCEL", + }, + device_options: { + device_id: "dbb5d83a-7838-11ea-bc55-0242ac130003", + skip_receipt_screen: false, + collect_signature: true, + tip_settings: { allow_tipping: true, separate_tip_screen: true, custom_tip_field: false }, + show_itemized_cart: true, + }, + deadline_duration: "PT5M", + status: "COMPLETED", + cancel_reason: "BUYER_CANCELED", + payment_ids: ["D7vLJqMkvSoAlX4yyFzUitOy4EPZY"], + created_at: "2023-11-29T14:59:50.682Z", + updated_at: "2023-11-29T15:00:18.936Z", + app_id: "APP_ID", + location_id: "LOCATION_ID", + payment_type: "CARD_PRESENT", + team_member_id: "team_member_id", + customer_id: "customer_id", + app_fee_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + statement_description_identifier: "statement_description_identifier", + tip_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + }, + }; + server + .mockEndpoint() + .post("/v2/terminals/checkouts/checkout_id/dismiss") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.terminal.dismissTerminalCheckout({ + checkoutId: "checkout_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + checkout: { + id: "LmZEKbo3SBfqO", + amountMoney: { + amount: BigInt("2610"), + currency: "USD", + }, + referenceId: "reference_id", + note: "note", + orderId: "order_id", + paymentOptions: { + autocomplete: true, + delayDuration: "delay_duration", + acceptPartialAuthorization: true, + delayAction: "CANCEL", + }, + deviceOptions: { + deviceId: "dbb5d83a-7838-11ea-bc55-0242ac130003", + skipReceiptScreen: false, + collectSignature: true, + tipSettings: { + allowTipping: true, + separateTipScreen: true, + customTipField: false, + }, + showItemizedCart: true, + }, + deadlineDuration: "PT5M", + status: "COMPLETED", + cancelReason: "BUYER_CANCELED", + paymentIds: ["D7vLJqMkvSoAlX4yyFzUitOy4EPZY"], + createdAt: "2023-11-29T14:59:50.682Z", + updatedAt: "2023-11-29T15:00:18.936Z", + appId: "APP_ID", + locationId: "LOCATION_ID", + paymentType: "CARD_PRESENT", + teamMemberId: "team_member_id", + customerId: "customer_id", + appFeeMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + statementDescriptionIdentifier: "statement_description_identifier", + tipMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + }, + }); + }); + + test("DismissTerminalRefund", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + refund: { + id: "vjkNb2HD-xq5kiWWiJ7RhwrQnkxIn2N0l1nPZY", + refund_id: "refund_id", + payment_id: "xq5kiWWiJ7RhwrQnkxIn2N0l1nPZY", + order_id: "s8OMhQcpEp1b61YywlccSHWqUaQZY", + amount_money: { amount: BigInt(111), currency: "CAD" }, + reason: "Returning item", + device_id: "47776348fd8b32b9", + deadline_duration: "PT5M", + status: "IN_PROGRESS", + cancel_reason: "BUYER_CANCELED", + created_at: "2023-11-30T16:16:39.299Z", + updated_at: "2023-11-30T16:16:57.863Z", + app_id: "APP_ID", + location_id: "location_id", + }, + }; + server + .mockEndpoint() + .post("/v2/terminals/refunds/terminal_refund_id/dismiss") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.terminal.dismissTerminalRefund({ + terminalRefundId: "terminal_refund_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + refund: { + id: "vjkNb2HD-xq5kiWWiJ7RhwrQnkxIn2N0l1nPZY", + refundId: "refund_id", + paymentId: "xq5kiWWiJ7RhwrQnkxIn2N0l1nPZY", + orderId: "s8OMhQcpEp1b61YywlccSHWqUaQZY", + amountMoney: { + amount: BigInt("111"), + currency: "CAD", + }, + reason: "Returning item", + deviceId: "47776348fd8b32b9", + deadlineDuration: "PT5M", + status: "IN_PROGRESS", + cancelReason: "BUYER_CANCELED", + createdAt: "2023-11-30T16:16:39.299Z", + updatedAt: "2023-11-30T16:16:57.863Z", + appId: "APP_ID", + locationId: "location_id", + }, + }); + }); +}); diff --git a/tests/wire/terminal/actions.test.ts b/tests/wire/terminal/actions.test.ts new file mode 100644 index 000000000..13989967a --- /dev/null +++ b/tests/wire/terminal/actions.test.ts @@ -0,0 +1,675 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("Actions", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "thahn-70e75c10-47f7-4ab6-88cc-aaa4076d065e", + action: { + device_id: "{{DEVICE_ID}}", + deadline_duration: "PT5M", + type: "SAVE_CARD", + save_card_options: { customer_id: "{{CUSTOMER_ID}}", reference_id: "user-id-1" }, + }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + action: { + id: "termapia:jveJIAkkAjILHkdCE", + device_id: "DEVICE_ID", + deadline_duration: "PT5M", + status: "PENDING", + cancel_reason: "BUYER_CANCELED", + created_at: "2021-07-28T23:22:07.476Z", + updated_at: "2021-07-28T23:22:07.476Z", + app_id: "APP_ID", + location_id: "LOCATION_ID", + type: "SAVE_CARD", + qr_code_options: { title: "title", body: "body", barcode_contents: "barcode_contents" }, + save_card_options: { customer_id: "CUSTOMER_ID", card_id: "card_id", reference_id: "user-id-1" }, + signature_options: { title: "title", body: "body", signature: [{}] }, + confirmation_options: { + title: "title", + body: "body", + agree_button_text: "agree_button_text", + disagree_button_text: "disagree_button_text", + }, + receipt_options: { payment_id: "payment_id", print_only: true, is_duplicate: true }, + data_collection_options: { title: "title", body: "body", input_type: "EMAIL" }, + select_options: { + title: "title", + body: "body", + options: [{ reference_id: "reference_id", title: "title" }], + selected_option: { reference_id: "reference_id", title: "title" }, + }, + device_metadata: { + battery_percentage: "battery_percentage", + charging_state: "charging_state", + location_id: "location_id", + merchant_id: "merchant_id", + network_connection_type: "network_connection_type", + payment_region: "payment_region", + serial_number: "serial_number", + os_version: "os_version", + app_version: "app_version", + wifi_network_name: "wifi_network_name", + wifi_network_strength: "wifi_network_strength", + ip_address: "ip_address", + }, + await_next_action: true, + await_next_action_duration: "await_next_action_duration", + }, + }; + server + .mockEndpoint() + .post("/v2/terminals/actions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.terminal.actions.create({ + idempotencyKey: "thahn-70e75c10-47f7-4ab6-88cc-aaa4076d065e", + action: { + deviceId: "{{DEVICE_ID}}", + deadlineDuration: "PT5M", + type: "SAVE_CARD", + saveCardOptions: { + customerId: "{{CUSTOMER_ID}}", + referenceId: "user-id-1", + }, + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + action: { + id: "termapia:jveJIAkkAjILHkdCE", + deviceId: "DEVICE_ID", + deadlineDuration: "PT5M", + status: "PENDING", + cancelReason: "BUYER_CANCELED", + createdAt: "2021-07-28T23:22:07.476Z", + updatedAt: "2021-07-28T23:22:07.476Z", + appId: "APP_ID", + locationId: "LOCATION_ID", + type: "SAVE_CARD", + qrCodeOptions: { + title: "title", + body: "body", + barcodeContents: "barcode_contents", + }, + saveCardOptions: { + customerId: "CUSTOMER_ID", + cardId: "card_id", + referenceId: "user-id-1", + }, + signatureOptions: { + title: "title", + body: "body", + signature: [{}], + }, + confirmationOptions: { + title: "title", + body: "body", + agreeButtonText: "agree_button_text", + disagreeButtonText: "disagree_button_text", + }, + receiptOptions: { + paymentId: "payment_id", + printOnly: true, + isDuplicate: true, + }, + dataCollectionOptions: { + title: "title", + body: "body", + inputType: "EMAIL", + }, + selectOptions: { + title: "title", + body: "body", + options: [ + { + referenceId: "reference_id", + title: "title", + }, + ], + selectedOption: { + referenceId: "reference_id", + title: "title", + }, + }, + deviceMetadata: { + batteryPercentage: "battery_percentage", + chargingState: "charging_state", + locationId: "location_id", + merchantId: "merchant_id", + networkConnectionType: "network_connection_type", + paymentRegion: "payment_region", + serialNumber: "serial_number", + osVersion: "os_version", + appVersion: "app_version", + wifiNetworkName: "wifi_network_name", + wifiNetworkStrength: "wifi_network_strength", + ipAddress: "ip_address", + }, + awaitNextAction: true, + awaitNextActionDuration: "await_next_action_duration", + }, + }); + }); + + test("search", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + query: { filter: { created_at: { start_at: "2022-04-01T00:00:00.000Z" } }, sort: { sort_order: "DESC" } }, + limit: 2, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + action: [ + { + id: "termapia:oBGWlAats8xWCiCE", + device_id: "DEVICE_ID", + deadline_duration: "PT5M", + status: "IN_PROGRESS", + cancel_reason: "BUYER_CANCELED", + created_at: "2022-04-08T15:14:04.895Z", + updated_at: "2022-04-08T15:14:05.446Z", + app_id: "APP_ID", + location_id: "LOCATION_ID", + type: "SAVE_CARD", + qr_code_options: { title: "title", body: "body", barcode_contents: "barcode_contents" }, + save_card_options: { customer_id: "CUSTOMER_ID", reference_id: "user-id-1" }, + signature_options: { title: "title", body: "body" }, + confirmation_options: { title: "title", body: "body", agree_button_text: "agree_button_text" }, + receipt_options: { payment_id: "payment_id" }, + data_collection_options: { title: "title", body: "body", input_type: "EMAIL" }, + select_options: { + title: "title", + body: "body", + options: [{ reference_id: "reference_id", title: "title" }], + }, + await_next_action: true, + await_next_action_duration: "await_next_action_duration", + }, + { + id: "termapia:K2NY2YSSml3lTiCE", + device_id: "DEVICE_ID", + deadline_duration: "PT5M", + status: "COMPLETED", + cancel_reason: "BUYER_CANCELED", + created_at: "2022-04-08T15:14:01.210Z", + updated_at: "2022-04-08T15:14:09.861Z", + app_id: "APP_ID", + location_id: "LOCATION_ID", + type: "SAVE_CARD", + qr_code_options: { title: "title", body: "body", barcode_contents: "barcode_contents" }, + save_card_options: { + customer_id: "CUSTOMER_ID", + card_id: "ccof:CARD_ID", + reference_id: "user-id-1", + }, + signature_options: { title: "title", body: "body" }, + confirmation_options: { title: "title", body: "body", agree_button_text: "agree_button_text" }, + receipt_options: { payment_id: "payment_id" }, + data_collection_options: { title: "title", body: "body", input_type: "EMAIL" }, + select_options: { + title: "title", + body: "body", + options: [{ reference_id: "reference_id", title: "title" }], + }, + await_next_action: true, + await_next_action_duration: "await_next_action_duration", + }, + ], + cursor: "CURSOR", + }; + server + .mockEndpoint() + .post("/v2/terminals/actions/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.terminal.actions.search({ + query: { + filter: { + createdAt: { + startAt: "2022-04-01T00:00:00.000Z", + }, + }, + sort: { + sortOrder: "DESC", + }, + }, + limit: 2, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + action: [ + { + id: "termapia:oBGWlAats8xWCiCE", + deviceId: "DEVICE_ID", + deadlineDuration: "PT5M", + status: "IN_PROGRESS", + cancelReason: "BUYER_CANCELED", + createdAt: "2022-04-08T15:14:04.895Z", + updatedAt: "2022-04-08T15:14:05.446Z", + appId: "APP_ID", + locationId: "LOCATION_ID", + type: "SAVE_CARD", + qrCodeOptions: { + title: "title", + body: "body", + barcodeContents: "barcode_contents", + }, + saveCardOptions: { + customerId: "CUSTOMER_ID", + referenceId: "user-id-1", + }, + signatureOptions: { + title: "title", + body: "body", + }, + confirmationOptions: { + title: "title", + body: "body", + agreeButtonText: "agree_button_text", + }, + receiptOptions: { + paymentId: "payment_id", + }, + dataCollectionOptions: { + title: "title", + body: "body", + inputType: "EMAIL", + }, + selectOptions: { + title: "title", + body: "body", + options: [ + { + referenceId: "reference_id", + title: "title", + }, + ], + }, + awaitNextAction: true, + awaitNextActionDuration: "await_next_action_duration", + }, + { + id: "termapia:K2NY2YSSml3lTiCE", + deviceId: "DEVICE_ID", + deadlineDuration: "PT5M", + status: "COMPLETED", + cancelReason: "BUYER_CANCELED", + createdAt: "2022-04-08T15:14:01.210Z", + updatedAt: "2022-04-08T15:14:09.861Z", + appId: "APP_ID", + locationId: "LOCATION_ID", + type: "SAVE_CARD", + qrCodeOptions: { + title: "title", + body: "body", + barcodeContents: "barcode_contents", + }, + saveCardOptions: { + customerId: "CUSTOMER_ID", + cardId: "ccof:CARD_ID", + referenceId: "user-id-1", + }, + signatureOptions: { + title: "title", + body: "body", + }, + confirmationOptions: { + title: "title", + body: "body", + agreeButtonText: "agree_button_text", + }, + receiptOptions: { + paymentId: "payment_id", + }, + dataCollectionOptions: { + title: "title", + body: "body", + inputType: "EMAIL", + }, + selectOptions: { + title: "title", + body: "body", + options: [ + { + referenceId: "reference_id", + title: "title", + }, + ], + }, + awaitNextAction: true, + awaitNextActionDuration: "await_next_action_duration", + }, + ], + cursor: "CURSOR", + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + action: { + id: "termapia:jveJIAkkAjILHkdCE", + device_id: "DEVICE_ID", + deadline_duration: "PT5M", + status: "IN_PROGRESS", + cancel_reason: "BUYER_CANCELED", + created_at: "2021-07-28T23:22:07.476Z", + updated_at: "2021-07-28T23:22:08.301Z", + app_id: "APP_ID", + location_id: "LOCATION_ID", + type: "SAVE_CARD", + qr_code_options: { title: "title", body: "body", barcode_contents: "barcode_contents" }, + save_card_options: { customer_id: "CUSTOMER_ID", card_id: "card_id", reference_id: "user-id-1" }, + signature_options: { title: "title", body: "body", signature: [{}] }, + confirmation_options: { + title: "title", + body: "body", + agree_button_text: "agree_button_text", + disagree_button_text: "disagree_button_text", + }, + receipt_options: { payment_id: "payment_id", print_only: true, is_duplicate: true }, + data_collection_options: { title: "title", body: "body", input_type: "EMAIL" }, + select_options: { + title: "title", + body: "body", + options: [{ reference_id: "reference_id", title: "title" }], + selected_option: { reference_id: "reference_id", title: "title" }, + }, + device_metadata: { + battery_percentage: "battery_percentage", + charging_state: "charging_state", + location_id: "location_id", + merchant_id: "merchant_id", + network_connection_type: "network_connection_type", + payment_region: "payment_region", + serial_number: "serial_number", + os_version: "os_version", + app_version: "app_version", + wifi_network_name: "wifi_network_name", + wifi_network_strength: "wifi_network_strength", + ip_address: "ip_address", + }, + await_next_action: true, + await_next_action_duration: "await_next_action_duration", + }, + }; + server + .mockEndpoint() + .get("/v2/terminals/actions/action_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.terminal.actions.get({ + actionId: "action_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + action: { + id: "termapia:jveJIAkkAjILHkdCE", + deviceId: "DEVICE_ID", + deadlineDuration: "PT5M", + status: "IN_PROGRESS", + cancelReason: "BUYER_CANCELED", + createdAt: "2021-07-28T23:22:07.476Z", + updatedAt: "2021-07-28T23:22:08.301Z", + appId: "APP_ID", + locationId: "LOCATION_ID", + type: "SAVE_CARD", + qrCodeOptions: { + title: "title", + body: "body", + barcodeContents: "barcode_contents", + }, + saveCardOptions: { + customerId: "CUSTOMER_ID", + cardId: "card_id", + referenceId: "user-id-1", + }, + signatureOptions: { + title: "title", + body: "body", + signature: [{}], + }, + confirmationOptions: { + title: "title", + body: "body", + agreeButtonText: "agree_button_text", + disagreeButtonText: "disagree_button_text", + }, + receiptOptions: { + paymentId: "payment_id", + printOnly: true, + isDuplicate: true, + }, + dataCollectionOptions: { + title: "title", + body: "body", + inputType: "EMAIL", + }, + selectOptions: { + title: "title", + body: "body", + options: [ + { + referenceId: "reference_id", + title: "title", + }, + ], + selectedOption: { + referenceId: "reference_id", + title: "title", + }, + }, + deviceMetadata: { + batteryPercentage: "battery_percentage", + chargingState: "charging_state", + locationId: "location_id", + merchantId: "merchant_id", + networkConnectionType: "network_connection_type", + paymentRegion: "payment_region", + serialNumber: "serial_number", + osVersion: "os_version", + appVersion: "app_version", + wifiNetworkName: "wifi_network_name", + wifiNetworkStrength: "wifi_network_strength", + ipAddress: "ip_address", + }, + awaitNextAction: true, + awaitNextActionDuration: "await_next_action_duration", + }, + }); + }); + + test("cancel", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + action: { + id: "termapia:jveJIAkkAjILHkdCE", + device_id: "DEVICE_ID", + deadline_duration: "PT5M", + status: "CANCELED", + cancel_reason: "SELLER_CANCELED", + created_at: "2021-07-28T23:22:07.476Z", + updated_at: "2021-07-28T23:22:29.511Z", + app_id: "APP_ID", + location_id: "LOCATION_ID", + type: "SAVE_CARD", + qr_code_options: { title: "title", body: "body", barcode_contents: "barcode_contents" }, + save_card_options: { customer_id: "CUSTOMER_ID", card_id: "card_id", reference_id: "user-id-1" }, + signature_options: { title: "title", body: "body", signature: [{}] }, + confirmation_options: { + title: "title", + body: "body", + agree_button_text: "agree_button_text", + disagree_button_text: "disagree_button_text", + }, + receipt_options: { payment_id: "payment_id", print_only: true, is_duplicate: true }, + data_collection_options: { title: "title", body: "body", input_type: "EMAIL" }, + select_options: { + title: "title", + body: "body", + options: [{ reference_id: "reference_id", title: "title" }], + selected_option: { reference_id: "reference_id", title: "title" }, + }, + device_metadata: { + battery_percentage: "battery_percentage", + charging_state: "charging_state", + location_id: "location_id", + merchant_id: "merchant_id", + network_connection_type: "network_connection_type", + payment_region: "payment_region", + serial_number: "serial_number", + os_version: "os_version", + app_version: "app_version", + wifi_network_name: "wifi_network_name", + wifi_network_strength: "wifi_network_strength", + ip_address: "ip_address", + }, + await_next_action: true, + await_next_action_duration: "await_next_action_duration", + }, + }; + server + .mockEndpoint() + .post("/v2/terminals/actions/action_id/cancel") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.terminal.actions.cancel({ + actionId: "action_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + action: { + id: "termapia:jveJIAkkAjILHkdCE", + deviceId: "DEVICE_ID", + deadlineDuration: "PT5M", + status: "CANCELED", + cancelReason: "SELLER_CANCELED", + createdAt: "2021-07-28T23:22:07.476Z", + updatedAt: "2021-07-28T23:22:29.511Z", + appId: "APP_ID", + locationId: "LOCATION_ID", + type: "SAVE_CARD", + qrCodeOptions: { + title: "title", + body: "body", + barcodeContents: "barcode_contents", + }, + saveCardOptions: { + customerId: "CUSTOMER_ID", + cardId: "card_id", + referenceId: "user-id-1", + }, + signatureOptions: { + title: "title", + body: "body", + signature: [{}], + }, + confirmationOptions: { + title: "title", + body: "body", + agreeButtonText: "agree_button_text", + disagreeButtonText: "disagree_button_text", + }, + receiptOptions: { + paymentId: "payment_id", + printOnly: true, + isDuplicate: true, + }, + dataCollectionOptions: { + title: "title", + body: "body", + inputType: "EMAIL", + }, + selectOptions: { + title: "title", + body: "body", + options: [ + { + referenceId: "reference_id", + title: "title", + }, + ], + selectedOption: { + referenceId: "reference_id", + title: "title", + }, + }, + deviceMetadata: { + batteryPercentage: "battery_percentage", + chargingState: "charging_state", + locationId: "location_id", + merchantId: "merchant_id", + networkConnectionType: "network_connection_type", + paymentRegion: "payment_region", + serialNumber: "serial_number", + osVersion: "os_version", + appVersion: "app_version", + wifiNetworkName: "wifi_network_name", + wifiNetworkStrength: "wifi_network_strength", + ipAddress: "ip_address", + }, + awaitNextAction: true, + awaitNextActionDuration: "await_next_action_duration", + }, + }); + }); +}); diff --git a/tests/wire/terminal/checkouts.test.ts b/tests/wire/terminal/checkouts.test.ts new file mode 100644 index 000000000..39ba81c5b --- /dev/null +++ b/tests/wire/terminal/checkouts.test.ts @@ -0,0 +1,503 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("Checkouts", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "28a0c3bc-7839-11ea-bc55-0242ac130003", + checkout: { + amount_money: { amount: BigInt(2610), currency: "USD" }, + reference_id: "id11572", + note: "A brief note", + device_options: { device_id: "dbb5d83a-7838-11ea-bc55-0242ac130003" }, + }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + checkout: { + id: "08YceKh7B3ZqO", + amount_money: { amount: BigInt(2610), currency: "USD" }, + reference_id: "id11572", + note: "A brief note", + order_id: "order_id", + payment_options: { + autocomplete: true, + delay_duration: "delay_duration", + accept_partial_authorization: true, + delay_action: "CANCEL", + }, + device_options: { + device_id: "dbb5d83a-7838-11ea-bc55-0242ac130003", + skip_receipt_screen: false, + collect_signature: true, + tip_settings: { allow_tipping: false }, + show_itemized_cart: true, + }, + deadline_duration: "PT5M", + status: "PENDING", + cancel_reason: "BUYER_CANCELED", + payment_ids: ["payment_ids"], + created_at: "2020-04-06T16:39:32.545Z", + updated_at: "2020-04-06T16:39:32.545Z", + app_id: "APP_ID", + location_id: "LOCATION_ID", + payment_type: "CARD_PRESENT", + team_member_id: "team_member_id", + customer_id: "customer_id", + app_fee_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + statement_description_identifier: "statement_description_identifier", + tip_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + }, + }; + server + .mockEndpoint() + .post("/v2/terminals/checkouts") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.terminal.checkouts.create({ + idempotencyKey: "28a0c3bc-7839-11ea-bc55-0242ac130003", + checkout: { + amountMoney: { + amount: BigInt("2610"), + currency: "USD", + }, + referenceId: "id11572", + note: "A brief note", + deviceOptions: { + deviceId: "dbb5d83a-7838-11ea-bc55-0242ac130003", + }, + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + checkout: { + id: "08YceKh7B3ZqO", + amountMoney: { + amount: BigInt("2610"), + currency: "USD", + }, + referenceId: "id11572", + note: "A brief note", + orderId: "order_id", + paymentOptions: { + autocomplete: true, + delayDuration: "delay_duration", + acceptPartialAuthorization: true, + delayAction: "CANCEL", + }, + deviceOptions: { + deviceId: "dbb5d83a-7838-11ea-bc55-0242ac130003", + skipReceiptScreen: false, + collectSignature: true, + tipSettings: { + allowTipping: false, + }, + showItemizedCart: true, + }, + deadlineDuration: "PT5M", + status: "PENDING", + cancelReason: "BUYER_CANCELED", + paymentIds: ["payment_ids"], + createdAt: "2020-04-06T16:39:32.545Z", + updatedAt: "2020-04-06T16:39:32.545Z", + appId: "APP_ID", + locationId: "LOCATION_ID", + paymentType: "CARD_PRESENT", + teamMemberId: "team_member_id", + customerId: "customer_id", + appFeeMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + statementDescriptionIdentifier: "statement_description_identifier", + tipMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + }, + }); + }); + + test("search", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { query: { filter: { status: "COMPLETED" } }, limit: 2 }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + checkouts: [ + { + id: "tsQPvzwBpMqqO", + amount_money: { amount: BigInt(2610), currency: "USD" }, + reference_id: "id14467", + note: "A brief note", + order_id: "order_id", + device_options: { + device_id: "dbb5d83a-7838-11ea-bc55-0242ac130003", + skip_receipt_screen: false, + tip_settings: { allow_tipping: false }, + }, + deadline_duration: "PT5M", + status: "COMPLETED", + cancel_reason: "BUYER_CANCELED", + payment_ids: ["rXnhZzywrEk4vR6pw76fPZfgvaB"], + created_at: "2020-03-31T18:13:15.921Z", + updated_at: "2020-03-31T18:13:52.725Z", + app_id: "APP_ID", + location_id: "location_id", + payment_type: "CARD_PRESENT", + team_member_id: "team_member_id", + customer_id: "customer_id", + statement_description_identifier: "statement_description_identifier", + }, + { + id: "XlOPTgcEhrbqO", + amount_money: { amount: BigInt(2610), currency: "USD" }, + reference_id: "id41623", + note: "A brief note", + order_id: "order_id", + device_options: { + device_id: "dbb5d83a-7838-11ea-bc55-0242ac130003", + skip_receipt_screen: true, + tip_settings: { allow_tipping: false }, + }, + deadline_duration: "PT5M", + status: "COMPLETED", + cancel_reason: "BUYER_CANCELED", + payment_ids: ["VYBF861PaoKPP7Pih0TlbZiNvaB"], + created_at: "2020-03-31T18:08:31.882Z", + updated_at: "2020-03-31T18:08:41.635Z", + app_id: "APP_ID", + location_id: "location_id", + payment_type: "CARD_PRESENT", + team_member_id: "team_member_id", + customer_id: "customer_id", + statement_description_identifier: "statement_description_identifier", + }, + ], + cursor: "RiTJqBoTuXlbLmmrPvEkX9iG7XnQ4W4RjGnH", + }; + server + .mockEndpoint() + .post("/v2/terminals/checkouts/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.terminal.checkouts.search({ + query: { + filter: { + status: "COMPLETED", + }, + }, + limit: 2, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + checkouts: [ + { + id: "tsQPvzwBpMqqO", + amountMoney: { + amount: BigInt("2610"), + currency: "USD", + }, + referenceId: "id14467", + note: "A brief note", + orderId: "order_id", + deviceOptions: { + deviceId: "dbb5d83a-7838-11ea-bc55-0242ac130003", + skipReceiptScreen: false, + tipSettings: { + allowTipping: false, + }, + }, + deadlineDuration: "PT5M", + status: "COMPLETED", + cancelReason: "BUYER_CANCELED", + paymentIds: ["rXnhZzywrEk4vR6pw76fPZfgvaB"], + createdAt: "2020-03-31T18:13:15.921Z", + updatedAt: "2020-03-31T18:13:52.725Z", + appId: "APP_ID", + locationId: "location_id", + paymentType: "CARD_PRESENT", + teamMemberId: "team_member_id", + customerId: "customer_id", + statementDescriptionIdentifier: "statement_description_identifier", + }, + { + id: "XlOPTgcEhrbqO", + amountMoney: { + amount: BigInt("2610"), + currency: "USD", + }, + referenceId: "id41623", + note: "A brief note", + orderId: "order_id", + deviceOptions: { + deviceId: "dbb5d83a-7838-11ea-bc55-0242ac130003", + skipReceiptScreen: true, + tipSettings: { + allowTipping: false, + }, + }, + deadlineDuration: "PT5M", + status: "COMPLETED", + cancelReason: "BUYER_CANCELED", + paymentIds: ["VYBF861PaoKPP7Pih0TlbZiNvaB"], + createdAt: "2020-03-31T18:08:31.882Z", + updatedAt: "2020-03-31T18:08:41.635Z", + appId: "APP_ID", + locationId: "location_id", + paymentType: "CARD_PRESENT", + teamMemberId: "team_member_id", + customerId: "customer_id", + statementDescriptionIdentifier: "statement_description_identifier", + }, + ], + cursor: "RiTJqBoTuXlbLmmrPvEkX9iG7XnQ4W4RjGnH", + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + checkout: { + id: "08YceKh7B3ZqO", + amount_money: { amount: BigInt(2610), currency: "USD" }, + reference_id: "id11572", + note: "A brief note", + order_id: "order_id", + payment_options: { + autocomplete: true, + delay_duration: "delay_duration", + accept_partial_authorization: true, + delay_action: "CANCEL", + }, + device_options: { + device_id: "dbb5d83a-7838-11ea-bc55-0242ac130003", + skip_receipt_screen: false, + collect_signature: true, + tip_settings: { allow_tipping: false }, + show_itemized_cart: true, + }, + deadline_duration: "PT5M", + status: "IN_PROGRESS", + cancel_reason: "BUYER_CANCELED", + payment_ids: ["payment_ids"], + created_at: "2020-04-06T16:39:32.545Z", + updated_at: "2020-04-06T16:39:323.001Z", + app_id: "APP_ID", + location_id: "LOCATION_ID", + payment_type: "CARD_PRESENT", + team_member_id: "team_member_id", + customer_id: "customer_id", + app_fee_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + statement_description_identifier: "statement_description_identifier", + tip_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + }, + }; + server + .mockEndpoint() + .get("/v2/terminals/checkouts/checkout_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.terminal.checkouts.get({ + checkoutId: "checkout_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + checkout: { + id: "08YceKh7B3ZqO", + amountMoney: { + amount: BigInt("2610"), + currency: "USD", + }, + referenceId: "id11572", + note: "A brief note", + orderId: "order_id", + paymentOptions: { + autocomplete: true, + delayDuration: "delay_duration", + acceptPartialAuthorization: true, + delayAction: "CANCEL", + }, + deviceOptions: { + deviceId: "dbb5d83a-7838-11ea-bc55-0242ac130003", + skipReceiptScreen: false, + collectSignature: true, + tipSettings: { + allowTipping: false, + }, + showItemizedCart: true, + }, + deadlineDuration: "PT5M", + status: "IN_PROGRESS", + cancelReason: "BUYER_CANCELED", + paymentIds: ["payment_ids"], + createdAt: "2020-04-06T16:39:32.545Z", + updatedAt: "2020-04-06T16:39:323.001Z", + appId: "APP_ID", + locationId: "LOCATION_ID", + paymentType: "CARD_PRESENT", + teamMemberId: "team_member_id", + customerId: "customer_id", + appFeeMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + statementDescriptionIdentifier: "statement_description_identifier", + tipMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + }, + }); + }); + + test("cancel", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + checkout: { + id: "S1yDlPQx7slqO", + amount_money: { amount: BigInt(123), currency: "USD" }, + reference_id: "id36815", + note: "note", + order_id: "order_id", + payment_options: { + autocomplete: true, + delay_duration: "delay_duration", + accept_partial_authorization: true, + delay_action: "CANCEL", + }, + device_options: { + device_id: "dbb5d83a-7838-11ea-bc55-0242ac130003", + skip_receipt_screen: true, + collect_signature: true, + tip_settings: { allow_tipping: true }, + show_itemized_cart: true, + }, + deadline_duration: "PT5M", + status: "CANCELED", + cancel_reason: "SELLER_CANCELED", + payment_ids: ["payment_ids"], + created_at: "2020-03-16T15:31:19.934Z", + updated_at: "2020-03-16T15:31:45.787Z", + app_id: "APP_ID", + location_id: "LOCATION_ID", + payment_type: "CARD_PRESENT", + team_member_id: "team_member_id", + customer_id: "customer_id", + app_fee_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + statement_description_identifier: "statement_description_identifier", + tip_money: { amount: BigInt(1000000), currency: "UNKNOWN_CURRENCY" }, + }, + }; + server + .mockEndpoint() + .post("/v2/terminals/checkouts/checkout_id/cancel") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.terminal.checkouts.cancel({ + checkoutId: "checkout_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + checkout: { + id: "S1yDlPQx7slqO", + amountMoney: { + amount: BigInt("123"), + currency: "USD", + }, + referenceId: "id36815", + note: "note", + orderId: "order_id", + paymentOptions: { + autocomplete: true, + delayDuration: "delay_duration", + acceptPartialAuthorization: true, + delayAction: "CANCEL", + }, + deviceOptions: { + deviceId: "dbb5d83a-7838-11ea-bc55-0242ac130003", + skipReceiptScreen: true, + collectSignature: true, + tipSettings: { + allowTipping: true, + }, + showItemizedCart: true, + }, + deadlineDuration: "PT5M", + status: "CANCELED", + cancelReason: "SELLER_CANCELED", + paymentIds: ["payment_ids"], + createdAt: "2020-03-16T15:31:19.934Z", + updatedAt: "2020-03-16T15:31:45.787Z", + appId: "APP_ID", + locationId: "LOCATION_ID", + paymentType: "CARD_PRESENT", + teamMemberId: "team_member_id", + customerId: "customer_id", + appFeeMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + statementDescriptionIdentifier: "statement_description_identifier", + tipMoney: { + amount: BigInt("1000000"), + currency: "UNKNOWN_CURRENCY", + }, + }, + }); + }); +}); diff --git a/tests/wire/terminal/refunds.test.ts b/tests/wire/terminal/refunds.test.ts new file mode 100644 index 000000000..c21c4f0fe --- /dev/null +++ b/tests/wire/terminal/refunds.test.ts @@ -0,0 +1,298 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("Refunds", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "402a640b-b26f-401f-b406-46f839590c04", + refund: { + payment_id: "5O5OvgkcNUhl7JBuINflcjKqUzXZY", + amount_money: { amount: BigInt(111), currency: "CAD" }, + reason: "Returning items", + device_id: "f72dfb8e-4d65-4e56-aade-ec3fb8d33291", + }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + refund: { + id: "009DP5HD-5O5OvgkcNUhl7JBuINflcjKqUzXZY", + refund_id: "refund_id", + payment_id: "5O5OvgkcNUhl7JBuINflcjKqUzXZY", + order_id: "kcuKDKreRaI4gF4TjmEgZjHk8Z7YY", + amount_money: { amount: BigInt(111), currency: "CAD" }, + reason: "Returning items", + device_id: "f72dfb8e-4d65-4e56-aade-ec3fb8d33291", + deadline_duration: "PT5M", + status: "PENDING", + cancel_reason: "BUYER_CANCELED", + created_at: "2020-09-29T15:21:46.771Z", + updated_at: "2020-09-29T15:21:46.771Z", + app_id: "sandbox-sq0idb-c2OuYt13YaCAeJq_2cd8OQ", + location_id: "76C9W6K8CNNQ5", + }, + }; + server + .mockEndpoint() + .post("/v2/terminals/refunds") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.terminal.refunds.create({ + idempotencyKey: "402a640b-b26f-401f-b406-46f839590c04", + refund: { + paymentId: "5O5OvgkcNUhl7JBuINflcjKqUzXZY", + amountMoney: { + amount: BigInt("111"), + currency: "CAD", + }, + reason: "Returning items", + deviceId: "f72dfb8e-4d65-4e56-aade-ec3fb8d33291", + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + refund: { + id: "009DP5HD-5O5OvgkcNUhl7JBuINflcjKqUzXZY", + refundId: "refund_id", + paymentId: "5O5OvgkcNUhl7JBuINflcjKqUzXZY", + orderId: "kcuKDKreRaI4gF4TjmEgZjHk8Z7YY", + amountMoney: { + amount: BigInt("111"), + currency: "CAD", + }, + reason: "Returning items", + deviceId: "f72dfb8e-4d65-4e56-aade-ec3fb8d33291", + deadlineDuration: "PT5M", + status: "PENDING", + cancelReason: "BUYER_CANCELED", + createdAt: "2020-09-29T15:21:46.771Z", + updatedAt: "2020-09-29T15:21:46.771Z", + appId: "sandbox-sq0idb-c2OuYt13YaCAeJq_2cd8OQ", + locationId: "76C9W6K8CNNQ5", + }, + }); + }); + + test("search", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { query: { filter: { status: "COMPLETED" } }, limit: 1 }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + refunds: [ + { + id: "009DP5HD-5O5OvgkcNUhl7JBuINflcjKqUzXZY", + refund_id: "5O5OvgkcNUhl7JBuINflcjKqUzXZY_43Q4iGp7sNeATiWrUruA1EYeMRUXaddXXlDDJ1EQLvb", + payment_id: "5O5OvgkcNUhl7JBuINflcjKqUzXZY", + order_id: "kcuKDKreRaI4gF4TjmEgZjHk8Z7YY", + amount_money: { amount: BigInt(111), currency: "CAD" }, + reason: "Returning item", + device_id: "f72dfb8e-4d65-4e56-aade-ec3fb8d33291", + deadline_duration: "PT5M", + status: "COMPLETED", + cancel_reason: "BUYER_CANCELED", + created_at: "2020-09-29T15:21:46.771Z", + updated_at: "2020-09-29T15:21:48.675Z", + app_id: "sandbox-sq0idb-c2OuYt13YaCAeJq_2cd8OQ", + location_id: "76C9W6K8CNNQ5", + }, + ], + cursor: "cursor", + }; + server + .mockEndpoint() + .post("/v2/terminals/refunds/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.terminal.refunds.search({ + query: { + filter: { + status: "COMPLETED", + }, + }, + limit: 1, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + refunds: [ + { + id: "009DP5HD-5O5OvgkcNUhl7JBuINflcjKqUzXZY", + refundId: "5O5OvgkcNUhl7JBuINflcjKqUzXZY_43Q4iGp7sNeATiWrUruA1EYeMRUXaddXXlDDJ1EQLvb", + paymentId: "5O5OvgkcNUhl7JBuINflcjKqUzXZY", + orderId: "kcuKDKreRaI4gF4TjmEgZjHk8Z7YY", + amountMoney: { + amount: BigInt("111"), + currency: "CAD", + }, + reason: "Returning item", + deviceId: "f72dfb8e-4d65-4e56-aade-ec3fb8d33291", + deadlineDuration: "PT5M", + status: "COMPLETED", + cancelReason: "BUYER_CANCELED", + createdAt: "2020-09-29T15:21:46.771Z", + updatedAt: "2020-09-29T15:21:48.675Z", + appId: "sandbox-sq0idb-c2OuYt13YaCAeJq_2cd8OQ", + locationId: "76C9W6K8CNNQ5", + }, + ], + cursor: "cursor", + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + refund: { + id: "009DP5HD-5O5OvgkcNUhl7JBuINflcjKqUzXZY", + refund_id: "5O5OvgkcNUhl7JBuINflcjKqUzXZY_43Q4iGp7sNeATiWrUruA1EYeMRUXaddXXlDDJ1EQLvb", + payment_id: "5O5OvgkcNUhl7JBuINflcjKqUzXZY", + order_id: "kcuKDKreRaI4gF4TjmEgZjHk8Z7YY", + amount_money: { amount: BigInt(111), currency: "CAD" }, + reason: "Returning item", + device_id: "f72dfb8e-4d65-4e56-aade-ec3fb8d33291", + deadline_duration: "PT5M", + status: "COMPLETED", + cancel_reason: "BUYER_CANCELED", + created_at: "2020-09-29T15:21:46.771Z", + updated_at: "2020-09-29T15:21:48.675Z", + app_id: "sandbox-sq0idb-c2OuYt13YaCAeJq_2cd8OQ", + location_id: "76C9W6K8CNNQ5", + }, + }; + server + .mockEndpoint() + .get("/v2/terminals/refunds/terminal_refund_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.terminal.refunds.get({ + terminalRefundId: "terminal_refund_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + refund: { + id: "009DP5HD-5O5OvgkcNUhl7JBuINflcjKqUzXZY", + refundId: "5O5OvgkcNUhl7JBuINflcjKqUzXZY_43Q4iGp7sNeATiWrUruA1EYeMRUXaddXXlDDJ1EQLvb", + paymentId: "5O5OvgkcNUhl7JBuINflcjKqUzXZY", + orderId: "kcuKDKreRaI4gF4TjmEgZjHk8Z7YY", + amountMoney: { + amount: BigInt("111"), + currency: "CAD", + }, + reason: "Returning item", + deviceId: "f72dfb8e-4d65-4e56-aade-ec3fb8d33291", + deadlineDuration: "PT5M", + status: "COMPLETED", + cancelReason: "BUYER_CANCELED", + createdAt: "2020-09-29T15:21:46.771Z", + updatedAt: "2020-09-29T15:21:48.675Z", + appId: "sandbox-sq0idb-c2OuYt13YaCAeJq_2cd8OQ", + locationId: "76C9W6K8CNNQ5", + }, + }); + }); + + test("cancel", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + refund: { + id: "g6ycb6HD-5O5OvgkcNUhl7JBuINflcjKqUzXZY", + refund_id: "refund_id", + payment_id: "5O5OvgkcNUhl7JBuINflcjKqUzXZY", + order_id: "kcuKDKreRaI4gF4TjmEgZjHk8Z7YY", + amount_money: { amount: BigInt(100), currency: "CAD" }, + reason: "reason", + device_id: "42690809-faa2-4701-a24b-19d3d34c9aaa", + deadline_duration: "PT5M", + status: "CANCELED", + cancel_reason: "SELLER_CANCELED", + created_at: "2020-10-21T22:47:23.241Z", + updated_at: "2020-10-21T22:47:30.096Z", + app_id: "sandbox-sq0idb-c2OuYt13YaCAeJq_2cd8OQ", + location_id: "76C9W6K8CNNQ5", + }, + }; + server + .mockEndpoint() + .post("/v2/terminals/refunds/terminal_refund_id/cancel") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.terminal.refunds.cancel({ + terminalRefundId: "terminal_refund_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + refund: { + id: "g6ycb6HD-5O5OvgkcNUhl7JBuINflcjKqUzXZY", + refundId: "refund_id", + paymentId: "5O5OvgkcNUhl7JBuINflcjKqUzXZY", + orderId: "kcuKDKreRaI4gF4TjmEgZjHk8Z7YY", + amountMoney: { + amount: BigInt("100"), + currency: "CAD", + }, + reason: "reason", + deviceId: "42690809-faa2-4701-a24b-19d3d34c9aaa", + deadlineDuration: "PT5M", + status: "CANCELED", + cancelReason: "SELLER_CANCELED", + createdAt: "2020-10-21T22:47:23.241Z", + updatedAt: "2020-10-21T22:47:30.096Z", + appId: "sandbox-sq0idb-c2OuYt13YaCAeJq_2cd8OQ", + locationId: "76C9W6K8CNNQ5", + }, + }); + }); +}); diff --git a/tests/wire/v1Transactions.test.ts b/tests/wire/v1Transactions.test.ts new file mode 100644 index 000000000..5690f9569 --- /dev/null +++ b/tests/wire/v1Transactions.test.ts @@ -0,0 +1,511 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("V1Transactions", () => { + test("V1ListOrders", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = [ + { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + id: "id", + buyer_email: "buyer_email", + recipient_name: "recipient_name", + recipient_phone_number: "recipient_phone_number", + state: "PENDING", + shipping_address: { + address_line_1: "address_line_1", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "administrative_district_level_1", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "postal_code", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + subtotal_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + total_shipping_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + total_tax_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + total_price_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + total_discount_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + created_at: "created_at", + updated_at: "updated_at", + expires_at: "expires_at", + payment_id: "payment_id", + buyer_note: "buyer_note", + completed_note: "completed_note", + refunded_note: "refunded_note", + canceled_note: "canceled_note", + tender: { + id: "id", + type: "CREDIT_CARD", + name: "name", + employee_id: "employee_id", + receipt_url: "receipt_url", + card_brand: "OTHER_BRAND", + pan_suffix: "pan_suffix", + entry_method: "MANUAL", + payment_note: "payment_note", + tendered_at: "tendered_at", + settled_at: "settled_at", + is_exchange: true, + }, + order_history: [{}], + promo_code: "promo_code", + btc_receive_address: "btc_receive_address", + btc_price_satoshi: 1.1, + }, + ]; + server + .mockEndpoint() + .get("/v1/location_id/orders") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.v1Transactions.v1ListOrders({ + locationId: "location_id", + }); + expect(response).toEqual([ + { + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + id: "id", + buyerEmail: "buyer_email", + recipientName: "recipient_name", + recipientPhoneNumber: "recipient_phone_number", + state: "PENDING", + shippingAddress: { + addressLine1: "address_line_1", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "administrative_district_level_1", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "postal_code", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + subtotalMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + totalShippingMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + totalTaxMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + totalPriceMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + totalDiscountMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + createdAt: "created_at", + updatedAt: "updated_at", + expiresAt: "expires_at", + paymentId: "payment_id", + buyerNote: "buyer_note", + completedNote: "completed_note", + refundedNote: "refunded_note", + canceledNote: "canceled_note", + tender: { + id: "id", + type: "CREDIT_CARD", + name: "name", + employeeId: "employee_id", + receiptUrl: "receipt_url", + cardBrand: "OTHER_BRAND", + panSuffix: "pan_suffix", + entryMethod: "MANUAL", + paymentNote: "payment_note", + tenderedAt: "tendered_at", + settledAt: "settled_at", + isExchange: true, + }, + orderHistory: [{}], + promoCode: "promo_code", + btcReceiveAddress: "btc_receive_address", + btcPriceSatoshi: 1.1, + }, + ]); + }); + + test("V1RetrieveOrder", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + id: "id", + buyer_email: "buyer_email", + recipient_name: "recipient_name", + recipient_phone_number: "recipient_phone_number", + state: "PENDING", + shipping_address: { + address_line_1: "address_line_1", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "administrative_district_level_1", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "postal_code", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + subtotal_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + total_shipping_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + total_tax_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + total_price_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + total_discount_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + created_at: "created_at", + updated_at: "updated_at", + expires_at: "expires_at", + payment_id: "payment_id", + buyer_note: "buyer_note", + completed_note: "completed_note", + refunded_note: "refunded_note", + canceled_note: "canceled_note", + tender: { + id: "id", + type: "CREDIT_CARD", + name: "name", + employee_id: "employee_id", + receipt_url: "receipt_url", + card_brand: "OTHER_BRAND", + pan_suffix: "pan_suffix", + entry_method: "MANUAL", + payment_note: "payment_note", + total_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + tendered_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + tendered_at: "tendered_at", + settled_at: "settled_at", + change_back_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + refunded_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + is_exchange: true, + }, + order_history: [{ action: "ORDER_PLACED", created_at: "created_at" }], + promo_code: "promo_code", + btc_receive_address: "btc_receive_address", + btc_price_satoshi: 1.1, + }; + server + .mockEndpoint() + .get("/v1/location_id/orders/order_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.v1Transactions.v1RetrieveOrder({ + locationId: "location_id", + orderId: "order_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + id: "id", + buyerEmail: "buyer_email", + recipientName: "recipient_name", + recipientPhoneNumber: "recipient_phone_number", + state: "PENDING", + shippingAddress: { + addressLine1: "address_line_1", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "administrative_district_level_1", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "postal_code", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + subtotalMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + totalShippingMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + totalTaxMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + totalPriceMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + totalDiscountMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + createdAt: "created_at", + updatedAt: "updated_at", + expiresAt: "expires_at", + paymentId: "payment_id", + buyerNote: "buyer_note", + completedNote: "completed_note", + refundedNote: "refunded_note", + canceledNote: "canceled_note", + tender: { + id: "id", + type: "CREDIT_CARD", + name: "name", + employeeId: "employee_id", + receiptUrl: "receipt_url", + cardBrand: "OTHER_BRAND", + panSuffix: "pan_suffix", + entryMethod: "MANUAL", + paymentNote: "payment_note", + totalMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + tenderedMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + tenderedAt: "tendered_at", + settledAt: "settled_at", + changeBackMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + refundedMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + isExchange: true, + }, + orderHistory: [ + { + action: "ORDER_PLACED", + createdAt: "created_at", + }, + ], + promoCode: "promo_code", + btcReceiveAddress: "btc_receive_address", + btcPriceSatoshi: 1.1, + }); + }); + + test("V1UpdateOrder", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { action: "COMPLETE" }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + id: "id", + buyer_email: "buyer_email", + recipient_name: "recipient_name", + recipient_phone_number: "recipient_phone_number", + state: "PENDING", + shipping_address: { + address_line_1: "address_line_1", + address_line_2: "address_line_2", + address_line_3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "administrative_district_level_1", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "postal_code", + country: "ZZ", + first_name: "first_name", + last_name: "last_name", + }, + subtotal_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + total_shipping_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + total_tax_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + total_price_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + total_discount_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + created_at: "created_at", + updated_at: "updated_at", + expires_at: "expires_at", + payment_id: "payment_id", + buyer_note: "buyer_note", + completed_note: "completed_note", + refunded_note: "refunded_note", + canceled_note: "canceled_note", + tender: { + id: "id", + type: "CREDIT_CARD", + name: "name", + employee_id: "employee_id", + receipt_url: "receipt_url", + card_brand: "OTHER_BRAND", + pan_suffix: "pan_suffix", + entry_method: "MANUAL", + payment_note: "payment_note", + total_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + tendered_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + tendered_at: "tendered_at", + settled_at: "settled_at", + change_back_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + refunded_money: { amount: 1, currency_code: "UNKNOWN_CURRENCY" }, + is_exchange: true, + }, + order_history: [{ action: "ORDER_PLACED", created_at: "created_at" }], + promo_code: "promo_code", + btc_receive_address: "btc_receive_address", + btc_price_satoshi: 1.1, + }; + server + .mockEndpoint() + .put("/v1/location_id/orders/order_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.v1Transactions.v1UpdateOrder({ + locationId: "location_id", + orderId: "order_id", + action: "COMPLETE", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + id: "id", + buyerEmail: "buyer_email", + recipientName: "recipient_name", + recipientPhoneNumber: "recipient_phone_number", + state: "PENDING", + shippingAddress: { + addressLine1: "address_line_1", + addressLine2: "address_line_2", + addressLine3: "address_line_3", + locality: "locality", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "administrative_district_level_1", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "postal_code", + country: "ZZ", + firstName: "first_name", + lastName: "last_name", + }, + subtotalMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + totalShippingMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + totalTaxMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + totalPriceMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + totalDiscountMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + createdAt: "created_at", + updatedAt: "updated_at", + expiresAt: "expires_at", + paymentId: "payment_id", + buyerNote: "buyer_note", + completedNote: "completed_note", + refundedNote: "refunded_note", + canceledNote: "canceled_note", + tender: { + id: "id", + type: "CREDIT_CARD", + name: "name", + employeeId: "employee_id", + receiptUrl: "receipt_url", + cardBrand: "OTHER_BRAND", + panSuffix: "pan_suffix", + entryMethod: "MANUAL", + paymentNote: "payment_note", + totalMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + tenderedMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + tenderedAt: "tendered_at", + settledAt: "settled_at", + changeBackMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + refundedMoney: { + amount: 1, + currencyCode: "UNKNOWN_CURRENCY", + }, + isExchange: true, + }, + orderHistory: [ + { + action: "ORDER_PLACED", + createdAt: "created_at", + }, + ], + promoCode: "promo_code", + btcReceiveAddress: "btc_receive_address", + btcPriceSatoshi: 1.1, + }); + }); +}); diff --git a/tests/wire/vendors.test.ts b/tests/wire/vendors.test.ts new file mode 100644 index 000000000..13f6fcd36 --- /dev/null +++ b/tests/wire/vendors.test.ts @@ -0,0 +1,874 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../mock-server/MockServerPool"; +import { SquareClient } from "../../src/Client"; + +describe("Vendors", () => { + test("batchCreate", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + vendors: { + "8fc6a5b0-9fe8-4b46-b46b-2ef95793abbe": { + name: "Joe's Fresh Seafood", + address: { + address_line_1: "505 Electric Ave", + address_line_2: "Suite 600", + locality: "New York", + administrative_district_level_1: "NY", + postal_code: "10003", + country: "US", + }, + contacts: [ + { + name: "Joe Burrow", + email_address: "joe@joesfreshseafood.com", + phone_number: "1-212-555-4250", + ordinal: 1, + }, + ], + account_number: "4025391", + note: "a vendor", + }, + }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + responses: { + "8fc6a5b0-9fe8-4b46-b46b-2ef95793abbe": { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + vendor: { + id: "INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4", + created_at: "2022-03-16T10:21:54.859Z", + updated_at: "2022-03-16T10:21:54.859Z", + name: "Joe's Fresh Seafood", + address: { + address_line_1: "505 Electric Ave", + address_line_2: "Suite 600", + locality: "New York", + administrative_district_level_1: "NY", + postal_code: "10003", + country: "US", + }, + contacts: [ + { + id: "INV_VC_FMCYHBWT1TPL8MFH52PBMEN92A", + name: "Joe Burrow", + email_address: "joe@joesfreshseafood.com", + phone_number: "1-212-555-4250", + ordinal: 1, + }, + ], + account_number: "4025391", + note: "a vendor", + version: 0, + status: "ACTIVE", + }, + }, + }, + }; + server + .mockEndpoint() + .post("/v2/vendors/bulk-create") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.vendors.batchCreate({ + vendors: { + "8fc6a5b0-9fe8-4b46-b46b-2ef95793abbe": { + name: "Joe's Fresh Seafood", + address: { + addressLine1: "505 Electric Ave", + addressLine2: "Suite 600", + locality: "New York", + administrativeDistrictLevel1: "NY", + postalCode: "10003", + country: "US", + }, + contacts: [ + { + name: "Joe Burrow", + emailAddress: "joe@joesfreshseafood.com", + phoneNumber: "1-212-555-4250", + ordinal: 1, + }, + ], + accountNumber: "4025391", + note: "a vendor", + }, + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + responses: { + "8fc6a5b0-9fe8-4b46-b46b-2ef95793abbe": { + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + vendor: { + id: "INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4", + createdAt: "2022-03-16T10:21:54.859Z", + updatedAt: "2022-03-16T10:21:54.859Z", + name: "Joe's Fresh Seafood", + address: { + addressLine1: "505 Electric Ave", + addressLine2: "Suite 600", + locality: "New York", + administrativeDistrictLevel1: "NY", + postalCode: "10003", + country: "US", + }, + contacts: [ + { + id: "INV_VC_FMCYHBWT1TPL8MFH52PBMEN92A", + name: "Joe Burrow", + emailAddress: "joe@joesfreshseafood.com", + phoneNumber: "1-212-555-4250", + ordinal: 1, + }, + ], + accountNumber: "4025391", + note: "a vendor", + version: 0, + status: "ACTIVE", + }, + }, + }, + }); + }); + + test("batchGet", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { vendor_ids: ["INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4"] }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + responses: { + INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4: { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + vendor: { + id: "INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4", + created_at: "2022-03-16T10:21:54.859Z", + updated_at: "2022-03-16T10:21:54.859Z", + name: "Joe's Fresh Seafood", + address: { + address_line_1: "505 Electric Ave", + address_line_2: "Suite 600", + locality: "New York", + administrative_district_level_1: "NY", + postal_code: "10003", + country: "US", + }, + contacts: [ + { + id: "INV_VC_FMCYHBWT1TPL8MFH52PBMEN92A", + name: "Joe Burrow", + email_address: "joe@joesfreshseafood.com", + phone_number: "1-212-555-4250", + ordinal: 1, + }, + ], + account_number: "4025391", + note: "a vendor", + version: 1, + status: "ACTIVE", + }, + }, + }, + }; + server + .mockEndpoint() + .post("/v2/vendors/bulk-retrieve") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.vendors.batchGet({ + vendorIds: ["INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4"], + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + responses: { + INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4: { + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + vendor: { + id: "INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4", + createdAt: "2022-03-16T10:21:54.859Z", + updatedAt: "2022-03-16T10:21:54.859Z", + name: "Joe's Fresh Seafood", + address: { + addressLine1: "505 Electric Ave", + addressLine2: "Suite 600", + locality: "New York", + administrativeDistrictLevel1: "NY", + postalCode: "10003", + country: "US", + }, + contacts: [ + { + id: "INV_VC_FMCYHBWT1TPL8MFH52PBMEN92A", + name: "Joe Burrow", + emailAddress: "joe@joesfreshseafood.com", + phoneNumber: "1-212-555-4250", + ordinal: 1, + }, + ], + accountNumber: "4025391", + note: "a vendor", + version: 1, + status: "ACTIVE", + }, + }, + }, + }); + }); + + test("batchUpdate", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + vendors: { FMCYHBWT1TPL8MFH52PBMEN92A: { vendor: {} }, INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4: { vendor: {} } }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + responses: { + INV_V_FMCYHBWT1TPL8MFH52PBMEN92A: { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + vendor: { + id: "INV_V_FMCYHBWT1TPL8MFH52PBMEN92A", + created_at: "2022-03-16T10:21:54.859Z", + updated_at: "2022-03-16T20:21:54.859Z", + name: "Annie’s Hot Sauce", + address: { + address_line_1: "202 Mill St", + locality: "Moorestown", + administrative_district_level_1: "NJ", + postal_code: "08057", + country: "US", + }, + contacts: [ + { + id: "INV_VC_ABYYHBWT1TPL8MFH52PBMENPJ4", + name: "Annie Thomas", + email_address: "annie@annieshotsauce.com", + phone_number: "1-212-555-4250", + ordinal: 0, + }, + ], + version: 11, + status: "ACTIVE", + }, + }, + INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4: { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR" }], + vendor: { + id: "INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4", + created_at: "2022-03-16T10:10:54.859Z", + updated_at: "2022-03-16T20:21:54.859Z", + name: "Joe's Fresh Seafood", + address: { + address_line_1: "505 Electric Ave", + address_line_2: "Suite 600", + locality: "New York", + administrative_district_level_1: "NY", + postal_code: "10003", + country: "US", + }, + contacts: [ + { + id: "INV_VC_FMCYHBWT1TPL8MFH52PBMEN92A", + name: "Joe Burrow", + email_address: "joe@joesfreshseafood.com", + phone_number: "1-212-555-4250", + ordinal: 0, + }, + ], + account_number: "4025391", + note: "favorite vendor", + version: 31, + status: "ACTIVE", + }, + }, + }, + }; + server + .mockEndpoint() + .put("/v2/vendors/bulk-update") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.vendors.batchUpdate({ + vendors: { + FMCYHBWT1TPL8MFH52PBMEN92A: { + vendor: {}, + }, + INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4: { + vendor: {}, + }, + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + responses: { + INV_V_FMCYHBWT1TPL8MFH52PBMEN92A: { + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + vendor: { + id: "INV_V_FMCYHBWT1TPL8MFH52PBMEN92A", + createdAt: "2022-03-16T10:21:54.859Z", + updatedAt: "2022-03-16T20:21:54.859Z", + name: "Annie\u2019s Hot Sauce", + address: { + addressLine1: "202 Mill St", + locality: "Moorestown", + administrativeDistrictLevel1: "NJ", + postalCode: "08057", + country: "US", + }, + contacts: [ + { + id: "INV_VC_ABYYHBWT1TPL8MFH52PBMENPJ4", + name: "Annie Thomas", + emailAddress: "annie@annieshotsauce.com", + phoneNumber: "1-212-555-4250", + ordinal: 0, + }, + ], + version: 11, + status: "ACTIVE", + }, + }, + INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4: { + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + }, + ], + vendor: { + id: "INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4", + createdAt: "2022-03-16T10:10:54.859Z", + updatedAt: "2022-03-16T20:21:54.859Z", + name: "Joe's Fresh Seafood", + address: { + addressLine1: "505 Electric Ave", + addressLine2: "Suite 600", + locality: "New York", + administrativeDistrictLevel1: "NY", + postalCode: "10003", + country: "US", + }, + contacts: [ + { + id: "INV_VC_FMCYHBWT1TPL8MFH52PBMEN92A", + name: "Joe Burrow", + emailAddress: "joe@joesfreshseafood.com", + phoneNumber: "1-212-555-4250", + ordinal: 0, + }, + ], + accountNumber: "4025391", + note: "favorite vendor", + version: 31, + status: "ACTIVE", + }, + }, + }, + }); + }); + + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "8fc6a5b0-9fe8-4b46-b46b-2ef95793abbe", + vendor: { + name: "Joe's Fresh Seafood", + address: { + address_line_1: "505 Electric Ave", + address_line_2: "Suite 600", + locality: "New York", + administrative_district_level_1: "NY", + postal_code: "10003", + country: "US", + }, + contacts: [ + { + name: "Joe Burrow", + email_address: "joe@joesfreshseafood.com", + phone_number: "1-212-555-4250", + ordinal: 1, + }, + ], + account_number: "4025391", + note: "a vendor", + }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + vendor: { + id: "INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4", + created_at: "2022-03-16T10:21:54.859Z", + updated_at: "2022-03-16T10:21:54.859Z", + name: "Joe's Fresh Seafood", + address: { + address_line_1: "505 Electric Ave", + address_line_2: "Suite 600", + address_line_3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "NY", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "10003", + country: "US", + first_name: "first_name", + last_name: "last_name", + }, + contacts: [ + { + id: "INV_VC_FMCYHBWT1TPL8MFH52PBMEN92A", + name: "Joe Burrow", + email_address: "joe@joesfreshseafood.com", + phone_number: "1-212-555-4250", + ordinal: 1, + }, + ], + account_number: "4025391", + note: "a vendor", + version: 1, + status: "ACTIVE", + }, + }; + server + .mockEndpoint() + .post("/v2/vendors/create") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.vendors.create({ + idempotencyKey: "8fc6a5b0-9fe8-4b46-b46b-2ef95793abbe", + vendor: { + name: "Joe's Fresh Seafood", + address: { + addressLine1: "505 Electric Ave", + addressLine2: "Suite 600", + locality: "New York", + administrativeDistrictLevel1: "NY", + postalCode: "10003", + country: "US", + }, + contacts: [ + { + name: "Joe Burrow", + emailAddress: "joe@joesfreshseafood.com", + phoneNumber: "1-212-555-4250", + ordinal: 1, + }, + ], + accountNumber: "4025391", + note: "a vendor", + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + vendor: { + id: "INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4", + createdAt: "2022-03-16T10:21:54.859Z", + updatedAt: "2022-03-16T10:21:54.859Z", + name: "Joe's Fresh Seafood", + address: { + addressLine1: "505 Electric Ave", + addressLine2: "Suite 600", + addressLine3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "NY", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "10003", + country: "US", + firstName: "first_name", + lastName: "last_name", + }, + contacts: [ + { + id: "INV_VC_FMCYHBWT1TPL8MFH52PBMEN92A", + name: "Joe Burrow", + emailAddress: "joe@joesfreshseafood.com", + phoneNumber: "1-212-555-4250", + ordinal: 1, + }, + ], + accountNumber: "4025391", + note: "a vendor", + version: 1, + status: "ACTIVE", + }, + }); + }); + + test("search", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = {}; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + vendors: [ + { + id: "INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4", + created_at: "2022-03-16T10:21:54.859Z", + updated_at: "2022-03-16T10:21:54.859Z", + name: "Joe's Fresh Seafood", + address: { + address_line_1: "505 Electric Ave", + address_line_2: "Suite 600", + locality: "New York", + administrative_district_level_1: "NY", + postal_code: "10003", + country: "US", + }, + contacts: [ + { + id: "INV_VC_FMCYHBWT1TPL8MFH52PBMEN92A", + name: "Joe Burrow", + email_address: "joe@joesfreshseafood.com", + phone_number: "1-212-555-4250", + ordinal: 1, + }, + ], + account_number: "4025391", + note: "a vendor", + version: 1, + status: "ACTIVE", + }, + ], + cursor: "cursor", + }; + server + .mockEndpoint() + .post("/v2/vendors/search") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.vendors.search(); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + vendors: [ + { + id: "INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4", + createdAt: "2022-03-16T10:21:54.859Z", + updatedAt: "2022-03-16T10:21:54.859Z", + name: "Joe's Fresh Seafood", + address: { + addressLine1: "505 Electric Ave", + addressLine2: "Suite 600", + locality: "New York", + administrativeDistrictLevel1: "NY", + postalCode: "10003", + country: "US", + }, + contacts: [ + { + id: "INV_VC_FMCYHBWT1TPL8MFH52PBMEN92A", + name: "Joe Burrow", + emailAddress: "joe@joesfreshseafood.com", + phoneNumber: "1-212-555-4250", + ordinal: 1, + }, + ], + accountNumber: "4025391", + note: "a vendor", + version: 1, + status: "ACTIVE", + }, + ], + cursor: "cursor", + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + vendor: { + id: "INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4", + created_at: "2022-03-16T10:21:54.859Z", + updated_at: "2022-03-16T10:21:54.859Z", + name: "Joe's Fresh Seafood", + address: { + address_line_1: "505 Electric Ave", + address_line_2: "Suite 600", + address_line_3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "NY", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "10003", + country: "US", + first_name: "first_name", + last_name: "last_name", + }, + contacts: [ + { + id: "INV_VC_FMCYHBWT1TPL8MFH52PBMEN92A", + name: "Joe Burrow", + email_address: "joe@joesfreshseafood.com", + phone_number: "1-212-555-4250", + ordinal: 1, + }, + ], + account_number: "4025391", + note: "a vendor", + version: 1, + status: "ACTIVE", + }, + }; + server + .mockEndpoint() + .get("/v2/vendors/vendor_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.vendors.get({ + vendorId: "vendor_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + vendor: { + id: "INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4", + createdAt: "2022-03-16T10:21:54.859Z", + updatedAt: "2022-03-16T10:21:54.859Z", + name: "Joe's Fresh Seafood", + address: { + addressLine1: "505 Electric Ave", + addressLine2: "Suite 600", + addressLine3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "NY", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "10003", + country: "US", + firstName: "first_name", + lastName: "last_name", + }, + contacts: [ + { + id: "INV_VC_FMCYHBWT1TPL8MFH52PBMEN92A", + name: "Joe Burrow", + emailAddress: "joe@joesfreshseafood.com", + phoneNumber: "1-212-555-4250", + ordinal: 1, + }, + ], + accountNumber: "4025391", + note: "a vendor", + version: 1, + status: "ACTIVE", + }, + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "8fc6a5b0-9fe8-4b46-b46b-2ef95793abbe", + vendor: { + id: "INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4", + name: "Jack's Chicken Shack", + version: 1, + status: "ACTIVE", + }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + vendor: { + id: "INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4", + created_at: "2022-03-16T10:21:54.859Z", + updated_at: "2022-03-16T20:21:54.859Z", + name: "Jack's Chicken Shack", + address: { + address_line_1: "505 Electric Ave", + address_line_2: "Suite 600", + address_line_3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality_2: "sublocality_2", + sublocality_3: "sublocality_3", + administrative_district_level_1: "NY", + administrative_district_level_2: "administrative_district_level_2", + administrative_district_level_3: "administrative_district_level_3", + postal_code: "10003", + country: "US", + first_name: "first_name", + last_name: "last_name", + }, + contacts: [ + { + id: "INV_VC_FMCYHBWT1TPL8MFH52PBMEN92A", + name: "Joe Burrow", + email_address: "joe@joesfreshseafood.com", + phone_number: "1-212-555-4250", + ordinal: 0, + }, + ], + account_number: "4025391", + note: "note", + version: 2, + status: "ACTIVE", + }, + }; + server + .mockEndpoint() + .put("/v2/vendors/vendor_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.vendors.update({ + vendorId: "vendor_id", + body: { + idempotencyKey: "8fc6a5b0-9fe8-4b46-b46b-2ef95793abbe", + vendor: { + id: "INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4", + name: "Jack's Chicken Shack", + version: 1, + status: "ACTIVE", + }, + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + vendor: { + id: "INV_V_JDKYHBWT1D4F8MFH63DBMEN8Y4", + createdAt: "2022-03-16T10:21:54.859Z", + updatedAt: "2022-03-16T20:21:54.859Z", + name: "Jack's Chicken Shack", + address: { + addressLine1: "505 Electric Ave", + addressLine2: "Suite 600", + addressLine3: "address_line_3", + locality: "New York", + sublocality: "sublocality", + sublocality2: "sublocality_2", + sublocality3: "sublocality_3", + administrativeDistrictLevel1: "NY", + administrativeDistrictLevel2: "administrative_district_level_2", + administrativeDistrictLevel3: "administrative_district_level_3", + postalCode: "10003", + country: "US", + firstName: "first_name", + lastName: "last_name", + }, + contacts: [ + { + id: "INV_VC_FMCYHBWT1TPL8MFH52PBMEN92A", + name: "Joe Burrow", + emailAddress: "joe@joesfreshseafood.com", + phoneNumber: "1-212-555-4250", + ordinal: 0, + }, + ], + accountNumber: "4025391", + note: "note", + version: 2, + status: "ACTIVE", + }, + }); + }); +}); diff --git a/tests/wire/webhooks/eventTypes.test.ts b/tests/wire/webhooks/eventTypes.test.ts new file mode 100644 index 000000000..6d2b9b8d9 --- /dev/null +++ b/tests/wire/webhooks/eventTypes.test.ts @@ -0,0 +1,52 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("EventTypes", () => { + test("list", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + event_types: ["inventory.count.updated"], + metadata: [ + { + event_type: "inventory.count.updated", + api_version_introduced: "2018-07-12", + release_status: "PUBLIC", + }, + ], + }; + server + .mockEndpoint() + .get("/v2/webhooks/event-types") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.webhooks.eventTypes.list(); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + eventTypes: ["inventory.count.updated"], + metadata: [ + { + eventType: "inventory.count.updated", + apiVersionIntroduced: "2018-07-12", + releaseStatus: "PUBLIC", + }, + ], + }); + }); +}); diff --git a/tests/wire/webhooks/subscriptions.test.ts b/tests/wire/webhooks/subscriptions.test.ts new file mode 100644 index 000000000..79f019eab --- /dev/null +++ b/tests/wire/webhooks/subscriptions.test.ts @@ -0,0 +1,296 @@ +/** + * This file was auto-generated by Fern from our API Definition. + */ + +import { mockServerPool } from "../../mock-server/MockServerPool"; +import { SquareClient } from "../../../src/Client"; + +describe("Subscriptions", () => { + test("create", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { + idempotency_key: "63f84c6c-2200-4c99-846c-2670a1311fbf", + subscription: { + name: "Example Webhook Subscription", + event_types: ["payment.created", "payment.updated"], + notification_url: "https://example-webhook-url.com", + api_version: "2021-12-15", + }, + }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + subscription: { + id: "wbhk_b35f6b3145074cf9ad513610786c19d5", + name: "Example Webhook Subscription", + enabled: true, + event_types: ["payment.created", "payment.updated"], + notification_url: "https://example-webhook-url.com", + api_version: "2021-12-15", + signature_key: "1k9bIJKCeTmSQwyagtNRLg", + created_at: "2022-01-10 23:29:48 +0000 UTC", + updated_at: "2022-01-10 23:29:48 +0000 UTC", + }, + }; + server + .mockEndpoint() + .post("/v2/webhooks/subscriptions") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.webhooks.subscriptions.create({ + idempotencyKey: "63f84c6c-2200-4c99-846c-2670a1311fbf", + subscription: { + name: "Example Webhook Subscription", + eventTypes: ["payment.created", "payment.updated"], + notificationUrl: "https://example-webhook-url.com", + apiVersion: "2021-12-15", + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + subscription: { + id: "wbhk_b35f6b3145074cf9ad513610786c19d5", + name: "Example Webhook Subscription", + enabled: true, + eventTypes: ["payment.created", "payment.updated"], + notificationUrl: "https://example-webhook-url.com", + apiVersion: "2021-12-15", + signatureKey: "1k9bIJKCeTmSQwyagtNRLg", + createdAt: "2022-01-10 23:29:48 +0000 UTC", + updatedAt: "2022-01-10 23:29:48 +0000 UTC", + }, + }); + }); + + test("get", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + subscription: { + id: "wbhk_b35f6b3145074cf9ad513610786c19d5", + name: "Example Webhook Subscription", + enabled: true, + event_types: ["payment.created", "payment.updated"], + notification_url: "https://example-webhook-url.com", + api_version: "2021-12-15", + signature_key: "1k9bIJKCeTmSQwyagtNRLg", + created_at: "2022-01-10 23:29:48 +0000 UTC", + updated_at: "2022-01-10 23:29:48 +0000 UTC", + }, + }; + server + .mockEndpoint() + .get("/v2/webhooks/subscriptions/subscription_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.webhooks.subscriptions.get({ + subscriptionId: "subscription_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + subscription: { + id: "wbhk_b35f6b3145074cf9ad513610786c19d5", + name: "Example Webhook Subscription", + enabled: true, + eventTypes: ["payment.created", "payment.updated"], + notificationUrl: "https://example-webhook-url.com", + apiVersion: "2021-12-15", + signatureKey: "1k9bIJKCeTmSQwyagtNRLg", + createdAt: "2022-01-10 23:29:48 +0000 UTC", + updatedAt: "2022-01-10 23:29:48 +0000 UTC", + }, + }); + }); + + test("update", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { subscription: { name: "Updated Example Webhook Subscription", enabled: false } }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + subscription: { + id: "wbhk_b35f6b3145074cf9ad513610786c19d5", + name: "Updated Example Webhook Subscription", + enabled: false, + event_types: ["payment.created", "payment.updated"], + notification_url: "https://example-webhook-url.com", + api_version: "2021-12-15", + signature_key: "signature_key", + created_at: "2022-01-10 23:29:48 +0000 UTC", + updated_at: "2022-01-10 23:45:51 +0000 UTC", + }, + }; + server + .mockEndpoint() + .put("/v2/webhooks/subscriptions/subscription_id") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.webhooks.subscriptions.update({ + subscriptionId: "subscription_id", + subscription: { + name: "Updated Example Webhook Subscription", + enabled: false, + }, + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + subscription: { + id: "wbhk_b35f6b3145074cf9ad513610786c19d5", + name: "Updated Example Webhook Subscription", + enabled: false, + eventTypes: ["payment.created", "payment.updated"], + notificationUrl: "https://example-webhook-url.com", + apiVersion: "2021-12-15", + signatureKey: "signature_key", + createdAt: "2022-01-10 23:29:48 +0000 UTC", + updatedAt: "2022-01-10 23:45:51 +0000 UTC", + }, + }); + }); + + test("delete", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + }; + server + .mockEndpoint() + .delete("/v2/webhooks/subscriptions/subscription_id") + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.webhooks.subscriptions.delete({ + subscriptionId: "subscription_id", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + }); + }); + + test("updateSignatureKey", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { idempotency_key: "ed80ae6b-0654-473b-bbab-a39aee89a60d" }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + signature_key: "1k9bIJKCeTmSQwyagtNRLg", + }; + server + .mockEndpoint() + .post("/v2/webhooks/subscriptions/subscription_id/signature-key") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.webhooks.subscriptions.updateSignatureKey({ + subscriptionId: "subscription_id", + idempotencyKey: "ed80ae6b-0654-473b-bbab-a39aee89a60d", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + signatureKey: "1k9bIJKCeTmSQwyagtNRLg", + }); + }); + + test("test", async () => { + const server = mockServerPool.createServer(); + const client = new SquareClient({ token: "test", environment: server.baseUrl }); + const rawRequestBody = { event_type: "payment.created" }; + const rawResponseBody = { + errors: [{ category: "API_ERROR", code: "INTERNAL_SERVER_ERROR", detail: "detail", field: "field" }], + subscription_test_result: { + id: "23eed5a9-2b12-403e-b212-7e2889aea0f6", + status_code: 404, + payload: + '{"merchant_id":"1ZYMKZY1YFGBW","type":"payment.created","event_id":"23eed5a9-2b12-403e-b212-7e2889aea0f6","created_at":"2022-01-11T00:06:48.322945116Z","data":{"type":"payment","id":"KkAkhdMsgzn59SM8A89WgKwekxLZY","object":{"payment":{"amount_money":{"amount":100,"currency":"USD"},"approved_money":{"amount":100,"currency":"USD"},"capabilities":["EDIT_TIP_AMOUNT","EDIT_TIP_AMOUNT_UP","EDIT_TIP_AMOUNT_DOWN"],"card_details":{"avs_status":"AVS_ACCEPTED","card":{"bin":"540988","card_brand":"MASTERCARD","card_type":"CREDIT","exp_month":11,"exp_year":2022,"fingerprint":"sq-1-Tvruf3vPQxlvI6n0IcKYfBukrcv6IqWr8UyBdViWXU2yzGn5VMJvrsHMKpINMhPmVg","last_4":"9029","prepaid_type":"NOT_PREPAID"},"card_payment_timeline":{"authorized_at":"2020-11-22T21:16:51.198Z"},"cvv_status":"CVV_ACCEPTED","entry_method":"KEYED","statement_description":"SQ *DEFAULT TEST ACCOUNT","status":"AUTHORIZED"},"created_at":"2020-11-22T21:16:51.086Z","delay_action":"CANCEL","delay_duration":"PT168H","delayed_until":"2020-11-29T21:16:51.086Z","id":"hYy9pRFVxpDsO1FB05SunFWUe9JZY","location_id":"S8GWD5R9QB376","order_id":"03O3USaPaAaFnI6kkwB1JxGgBsUZY","receipt_number":"hYy9","risk_evaluation":{"created_at":"2020-11-22T21:16:51.198Z","risk_level":"NORMAL"},"source_type":"CARD","status":"APPROVED","total_money":{"amount":100,"currency":"USD"},"updated_at":"2020-11-22T21:16:51.198Z","version_token":"FfQhQJf9r3VSQIgyWBk1oqhIwiznLwVwJbVVA0bdyEv6o"}}}}', + created_at: "2022-01-11 00:06:48.322945116 +0000 UTC m=+3863.054453746", + updated_at: "2022-01-11 00:06:48.322945116 +0000 UTC m=+3863.054453746", + }, + }; + server + .mockEndpoint() + .post("/v2/webhooks/subscriptions/subscription_id/test") + .jsonBody(rawRequestBody) + .respondWith() + .statusCode(200) + .jsonBody(rawResponseBody) + .build(); + + const response = await client.webhooks.subscriptions.test({ + subscriptionId: "subscription_id", + eventType: "payment.created", + }); + expect(response).toEqual({ + errors: [ + { + category: "API_ERROR", + code: "INTERNAL_SERVER_ERROR", + detail: "detail", + field: "field", + }, + ], + subscriptionTestResult: { + id: "23eed5a9-2b12-403e-b212-7e2889aea0f6", + statusCode: 404, + payload: + '{"merchant_id":"1ZYMKZY1YFGBW","type":"payment.created","event_id":"23eed5a9-2b12-403e-b212-7e2889aea0f6","created_at":"2022-01-11T00:06:48.322945116Z","data":{"type":"payment","id":"KkAkhdMsgzn59SM8A89WgKwekxLZY","object":{"payment":{"amount_money":{"amount":100,"currency":"USD"},"approved_money":{"amount":100,"currency":"USD"},"capabilities":["EDIT_TIP_AMOUNT","EDIT_TIP_AMOUNT_UP","EDIT_TIP_AMOUNT_DOWN"],"card_details":{"avs_status":"AVS_ACCEPTED","card":{"bin":"540988","card_brand":"MASTERCARD","card_type":"CREDIT","exp_month":11,"exp_year":2022,"fingerprint":"sq-1-Tvruf3vPQxlvI6n0IcKYfBukrcv6IqWr8UyBdViWXU2yzGn5VMJvrsHMKpINMhPmVg","last_4":"9029","prepaid_type":"NOT_PREPAID"},"card_payment_timeline":{"authorized_at":"2020-11-22T21:16:51.198Z"},"cvv_status":"CVV_ACCEPTED","entry_method":"KEYED","statement_description":"SQ *DEFAULT TEST ACCOUNT","status":"AUTHORIZED"},"created_at":"2020-11-22T21:16:51.086Z","delay_action":"CANCEL","delay_duration":"PT168H","delayed_until":"2020-11-29T21:16:51.086Z","id":"hYy9pRFVxpDsO1FB05SunFWUe9JZY","location_id":"S8GWD5R9QB376","order_id":"03O3USaPaAaFnI6kkwB1JxGgBsUZY","receipt_number":"hYy9","risk_evaluation":{"created_at":"2020-11-22T21:16:51.198Z","risk_level":"NORMAL"},"source_type":"CARD","status":"APPROVED","total_money":{"amount":100,"currency":"USD"},"updated_at":"2020-11-22T21:16:51.198Z","version_token":"FfQhQJf9r3VSQIgyWBk1oqhIwiznLwVwJbVVA0bdyEv6o"}}}}', + createdAt: "2022-01-11 00:06:48.322945116 +0000 UTC m=+3863.054453746", + updatedAt: "2022-01-11 00:06:48.322945116 +0000 UTC m=+3863.054453746", + }, + }); + }); +}); diff --git a/yarn.lock b/yarn.lock index 889b02fdc..0b6fbcd78 100644 --- a/yarn.lock +++ b/yarn.lock @@ -377,6 +377,60 @@ resolved "https://registry.yarnpkg.com/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz#75a2e8b51cb758a7553d6804a5932d7aace75c39" integrity sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw== +"@bundled-es-modules/cookie@^2.0.1": + version "2.0.1" + resolved "https://registry.yarnpkg.com/@bundled-es-modules/cookie/-/cookie-2.0.1.tgz#b41376af6a06b3e32a15241d927b840a9b4de507" + integrity sha512-8o+5fRPLNbjbdGRRmJj3h6Hh1AQJf2dk3qQ/5ZFb+PXkRNiSoMGGUKlsgLfrxneb72axVJyIYji64E2+nNfYyw== + dependencies: + cookie "^0.7.2" + +"@bundled-es-modules/statuses@^1.0.1": + version "1.0.1" + resolved "https://registry.yarnpkg.com/@bundled-es-modules/statuses/-/statuses-1.0.1.tgz#761d10f44e51a94902c4da48675b71a76cc98872" + integrity sha512-yn7BklA5acgcBr+7w064fGV+SGIFySjCKpqjcWgBAIfrAkY+4GQTJJHQMeT3V/sgz23VTEVV8TtOmkvJAhFVfg== + dependencies: + statuses "^2.0.1" + +"@bundled-es-modules/tough-cookie@^0.1.6": + version "0.1.6" + resolved "https://registry.yarnpkg.com/@bundled-es-modules/tough-cookie/-/tough-cookie-0.1.6.tgz#fa9cd3cedfeecd6783e8b0d378b4a99e52bde5d3" + integrity sha512-dvMHbL464C0zI+Yqxbz6kZ5TOEp7GLW+pry/RWndAR8MJQAXZ2rPmIs8tziTZjeIyhSNZgZbCePtfSbdWqStJw== + dependencies: + "@types/tough-cookie" "^4.0.5" + tough-cookie "^4.1.4" + +"@inquirer/confirm@^5.0.0": + version "5.1.13" + resolved "https://registry.yarnpkg.com/@inquirer/confirm/-/confirm-5.1.13.tgz#4931515edc63e25d833c9a40ccf1855e8e822dbc" + integrity sha512-EkCtvp67ICIVVzjsquUiVSd+V5HRGOGQfsqA4E4vMWhYnB7InUL0pa0TIWt1i+OfP16Gkds8CdIu6yGZwOM1Yw== + dependencies: + "@inquirer/core" "^10.1.14" + "@inquirer/type" "^3.0.7" + +"@inquirer/core@^10.1.14": + version "10.1.14" + resolved "https://registry.yarnpkg.com/@inquirer/core/-/core-10.1.14.tgz#7678b2daaecf32fa2f6e02a03dc235f9620e197f" + integrity sha512-Ma+ZpOJPewtIYl6HZHZckeX1STvDnHTCB2GVINNUlSEn2Am6LddWwfPkIGY0IUFVjUUrr/93XlBwTK6mfLjf0A== + dependencies: + "@inquirer/figures" "^1.0.12" + "@inquirer/type" "^3.0.7" + ansi-escapes "^4.3.2" + cli-width "^4.1.0" + mute-stream "^2.0.0" + signal-exit "^4.1.0" + wrap-ansi "^6.2.0" + yoctocolors-cjs "^2.1.2" + +"@inquirer/figures@^1.0.12": + version "1.0.12" + resolved "https://registry.yarnpkg.com/@inquirer/figures/-/figures-1.0.12.tgz#667d6254cc7ba3b0c010a323d78024a1d30c6053" + integrity sha512-MJttijd8rMFcKJC8NYmprWr6hD3r9Gd9qUC0XwPNwoEPWSMVJwA2MlXxF+nhZZNMY+HXsWa+o7KY2emWYIn0jQ== + +"@inquirer/type@^3.0.7": + version "3.0.7" + resolved "https://registry.yarnpkg.com/@inquirer/type/-/type-3.0.7.tgz#b46bcf377b3172dbc768fdbd053e6492ad801a09" + integrity sha512-PfunHQcjwnju84L+ycmcMKB/pTPIngjUJvfnRhKY6FKPuYXlM4aQCb/nIdTFR6BEhMjFvngzvng/vBAJMZpLSA== + "@istanbuljs/load-nyc-config@^1.0.0": version "1.1.0" resolved "https://registry.yarnpkg.com/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz#fd3db1d59ecf7cf121e80650bb86712f9b55eced" @@ -619,6 +673,36 @@ "@jridgewell/resolve-uri" "^3.1.0" "@jridgewell/sourcemap-codec" "^1.4.14" +"@mswjs/interceptors@^0.39.1": + version "0.39.2" + resolved "https://registry.yarnpkg.com/@mswjs/interceptors/-/interceptors-0.39.2.tgz#de9de0ab23f99d387c7904df7219a92157d1d666" + integrity sha512-RuzCup9Ct91Y7V79xwCb146RaBRHZ7NBbrIUySumd1rpKqHL5OonaqrGIbug5hNwP/fRyxFMA6ISgw4FTtYFYg== + dependencies: + "@open-draft/deferred-promise" "^2.2.0" + "@open-draft/logger" "^0.3.0" + "@open-draft/until" "^2.0.0" + is-node-process "^1.2.0" + outvariant "^1.4.3" + strict-event-emitter "^0.5.1" + +"@open-draft/deferred-promise@^2.2.0": + version "2.2.0" + resolved "https://registry.yarnpkg.com/@open-draft/deferred-promise/-/deferred-promise-2.2.0.tgz#4a822d10f6f0e316be4d67b4d4f8c9a124b073bd" + integrity sha512-CecwLWx3rhxVQF6V4bAgPS5t+So2sTbPgAzafKkVizyi7tlwpcFpdFqq+wqF2OwNBmqFuu6tOyouTuxgpMfzmA== + +"@open-draft/logger@^0.3.0": + version "0.3.0" + resolved "https://registry.yarnpkg.com/@open-draft/logger/-/logger-0.3.0.tgz#2b3ab1242b360aa0adb28b85f5d7da1c133a0954" + integrity sha512-X2g45fzhxH238HKO4xbSr7+wBS8Fvw6ixhTDuvLd5mqh6bJJCFAPwU9mPDxbcrRtfxv4u5IHCEH77BmxvXmmxQ== + dependencies: + is-node-process "^1.2.0" + outvariant "^1.4.0" + +"@open-draft/until@^2.0.0", "@open-draft/until@^2.1.0": + version "2.1.0" + resolved "https://registry.yarnpkg.com/@open-draft/until/-/until-2.1.0.tgz#0acf32f470af2ceaf47f095cdecd40d68666efda" + integrity sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg== + "@sinclair/typebox@^0.27.8": version "0.27.8" resolved "https://registry.yarnpkg.com/@sinclair/typebox/-/typebox-0.27.8.tgz#6667fac16c436b5434a387a34dedb013198f6e6e" @@ -676,6 +760,11 @@ dependencies: "@babel/types" "^7.20.7" +"@types/cookie@^0.6.0": + version "0.6.0" + resolved "https://registry.yarnpkg.com/@types/cookie/-/cookie-0.6.0.tgz#eac397f28bf1d6ae0ae081363eca2f425bedf0d5" + integrity sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA== + "@types/eslint-scope@^3.7.7": version "3.7.7" resolved "https://registry.yarnpkg.com/@types/eslint-scope/-/eslint-scope-3.7.7.tgz#3108bd5f18b0cdb277c867b3dd449c9ed7079ac5" @@ -772,11 +861,6 @@ dependencies: undici-types "~5.26.4" -"@types/qs@^6.9.17": - version "6.14.0" - resolved "https://registry.yarnpkg.com/@types/qs/-/qs-6.14.0.tgz#d8b60cecf62f2db0fb68e5e006077b9178b85de5" - integrity sha512-eOunJqu0K1923aExK6y8p6fsihYEn/BYuQ4g0CxAAgFc4b/ZLN4CrsRZ55srTdqoiLzU2B2evC+apEIxprEzkQ== - "@types/readable-stream@^4.0.18": version "4.0.21" resolved "https://registry.yarnpkg.com/@types/readable-stream/-/readable-stream-4.0.21.tgz#716558454a5e0c3c0651520f8154efc3288f59cb" @@ -789,16 +873,16 @@ resolved "https://registry.yarnpkg.com/@types/stack-utils/-/stack-utils-2.0.3.tgz#6209321eb2c1712a7e7466422b8cb1fc0d9dd5d8" integrity sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw== -"@types/tough-cookie@*": +"@types/statuses@^2.0.4": + version "2.0.6" + resolved "https://registry.yarnpkg.com/@types/statuses/-/statuses-2.0.6.tgz#66748315cc9a96d63403baa8671b2c124f8633aa" + integrity sha512-xMAgYwceFhRA2zY+XbEA7mxYbA093wdiW8Vu6gZPGWy9cmOyU9XesH1tNcEWsKFd5Vzrqx5T3D38PWx1FIIXkA== + +"@types/tough-cookie@*", "@types/tough-cookie@^4.0.5": version "4.0.5" resolved "https://registry.yarnpkg.com/@types/tough-cookie/-/tough-cookie-4.0.5.tgz#cb6e2a691b70cb177c6e3ae9c1d2e8b2ea8cd304" integrity sha512-/Ad8+nIOV7Rl++6f1BdKxFSMgmoqEoYbHRpPcx3JEfv8VRsQe9Z4mCXeJBzxs7mbHY/XOZZuXlRNfhpVPbs6ZA== -"@types/url-join@4.0.1": - version "4.0.1" - resolved "https://registry.yarnpkg.com/@types/url-join/-/url-join-4.0.1.tgz#4989c97f969464647a8586c7252d97b449cdc045" - integrity sha512-wDXw9LEEUHyV+7UWy7U315nrJGJ7p1BzaCxDpEoLr789Dk1WDVMMlf3iBfbG2F8NdWnYyFbtTxUn2ZNbm1Q4LQ== - "@types/yargs-parser@*": version "21.0.3" resolved "https://registry.yarnpkg.com/@types/yargs-parser/-/yargs-parser-21.0.3.tgz#815e30b786d2e8f0dcd85fd5bcf5e1a04d008f15" @@ -1010,7 +1094,7 @@ ajv@^8.0.0, ajv@^8.9.0: json-schema-traverse "^1.0.0" require-from-string "^2.0.2" -ansi-escapes@^4.2.1: +ansi-escapes@^4.2.1, ansi-escapes@^4.3.2: version "4.3.2" resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-4.3.2.tgz#6b2291d1db7d98b6521d5f1efa42d0f3a9feb65e" integrity sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ== @@ -1208,14 +1292,6 @@ call-bind-apply-helpers@^1.0.1, call-bind-apply-helpers@^1.0.2: es-errors "^1.3.0" function-bind "^1.1.2" -call-bound@^1.0.2: - version "1.0.4" - resolved "https://registry.yarnpkg.com/call-bound/-/call-bound-1.0.4.tgz#238de935d2a2a692928c538c7ccfa91067fd062a" - integrity sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg== - dependencies: - call-bind-apply-helpers "^1.0.2" - get-intrinsic "^1.3.0" - callsites@^3.0.0: version "3.1.0" resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73" @@ -1264,6 +1340,11 @@ cjs-module-lexer@^1.0.0: resolved "https://registry.yarnpkg.com/cjs-module-lexer/-/cjs-module-lexer-1.4.3.tgz#0f79731eb8cfe1ec72acd4066efac9d61991b00d" integrity sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q== +cli-width@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/cli-width/-/cli-width-4.1.0.tgz#42daac41d3c254ef38ad8ac037672130173691c5" + integrity sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ== + cliui@^8.0.1: version "8.0.1" resolved "https://registry.yarnpkg.com/cliui/-/cliui-8.0.1.tgz#0c04b075db02cbfe60dc8e6cf2f5486b1a3608aa" @@ -1317,6 +1398,11 @@ convert-source-map@^2.0.0: resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-2.0.0.tgz#4b560f649fc4e918dd0ab75cf4961e8bc882d82a" integrity sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg== +cookie@^0.7.2: + version "0.7.2" + resolved "https://registry.yarnpkg.com/cookie/-/cookie-0.7.2.tgz#556369c472a2ba910f2979891b526b3436237ed7" + integrity sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w== + create-jest@^29.7.0: version "29.7.0" resolved "https://registry.yarnpkg.com/create-jest/-/create-jest-29.7.0.tgz#a355c5b3cb1e1af02ba177fe7afd7feee49a5320" @@ -1436,9 +1522,9 @@ ejs@^3.1.10: jake "^10.8.5" electron-to-chromium@^1.5.173: - version "1.5.184" - resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.5.184.tgz#3ef8b7e1be5482d9b04ab0e467d62379d029c4b3" - integrity sha512-zlaUk/wwnR/27FHNarzOtMgfxD1Q0/2Aby7PnURumQTal7yauqQ3c2HHcG/pjLFTvF3AWv44kMWyArVlfHeDlw== + version "1.5.187" + resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.5.187.tgz#8c58854e065962351dc87e95614dd78d50425966" + integrity sha512-cl5Jc9I0KGUoOoSbxvTywTa40uspGJt/BDBoDLoxJRSBpWh4FFXBsjNRHfQrONsV/OoEjDfHUmZQa2d6Ze4YgA== emittery@^0.13.1: version "0.13.1" @@ -1654,9 +1740,9 @@ form-data-encoder@^4.0.2: integrity sha512-G6NsmEW15s0Uw9XnCg+33H3ViYRyiM0hMrMhhqQOR8NFc5GhYrI+6I3u7OTw7b91J2g8rtvMBZJDbcGb2YUniw== form-data@^4.0.0, form-data@^4.0.1: - version "4.0.3" - resolved "https://registry.yarnpkg.com/form-data/-/form-data-4.0.3.tgz#608b1b3f3e28be0fccf5901fc85fb3641e5cf0ae" - integrity sha512-qsITQPfmvMOSAdeyZ+12I1c+CKSstAFAwu+97zrnWAbIr5u8wfsExUzCesVLC8NgHuRUqNN4Zy6UPWUTRGslcA== + version "4.0.4" + resolved "https://registry.yarnpkg.com/form-data/-/form-data-4.0.4.tgz#784cdcce0669a9d68e94d11ac4eea98088edd2c4" + integrity sha512-KrGhL9Q4zjj0kiUt5OO4Mr/A/jlI2jDYs5eHBpYHPcBEVSiipAvn2Ko2HnPe20rmcuuvMHNdZFp+4IlGTMF0Ow== dependencies: asynckit "^0.4.0" combined-stream "^1.0.8" @@ -1694,7 +1780,7 @@ get-caller-file@^2.0.5: resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e" integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg== -get-intrinsic@^1.2.5, get-intrinsic@^1.2.6, get-intrinsic@^1.3.0: +get-intrinsic@^1.2.6: version "1.3.0" resolved "https://registry.yarnpkg.com/get-intrinsic/-/get-intrinsic-1.3.0.tgz#743f0e3b6964a93a5491ed1bffaae054d7f98d01" integrity sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ== @@ -1755,6 +1841,11 @@ graceful-fs@^4.1.2, graceful-fs@^4.2.11, graceful-fs@^4.2.4, graceful-fs@^4.2.9: resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.11.tgz#4183e4e8bf08bb6e05bbb2f7d2e0c8f712ca40e3" integrity sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ== +graphql@^16.8.1: + version "16.11.0" + resolved "https://registry.yarnpkg.com/graphql/-/graphql-16.11.0.tgz#96d17f66370678027fdf59b2d4c20b4efaa8a633" + integrity sha512-mS1lbMsxgQj6hge1XZ6p7GPhbrtFwUFYi3wRzXAC/FmYnyXMTvvI3td3rjmQ2u8ewXueaSvRPWaEcgVVOT9Jnw== + has-flag@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b" @@ -1779,6 +1870,11 @@ hasown@^2.0.2: dependencies: function-bind "^1.1.2" +headers-polyfill@^4.0.2: + version "4.0.3" + resolved "https://registry.yarnpkg.com/headers-polyfill/-/headers-polyfill-4.0.3.tgz#922a0155de30ecc1f785bcf04be77844ca95ad07" + integrity sha512-IScLbePpkvO846sIwOtOTDjutRMWdXdJmXdMvk6gCBHxFO8d+QKOQedyZSxFTTFYRSmlgSTDtXqqq4pcenBXLQ== + html-encoding-sniffer@^3.0.0: version "3.0.0" resolved "https://registry.yarnpkg.com/html-encoding-sniffer/-/html-encoding-sniffer-3.0.0.tgz#2cb1a8cf0db52414776e5b2a7a04d5dd98158de9" @@ -1873,6 +1969,11 @@ is-generator-fn@^2.0.0: resolved "https://registry.yarnpkg.com/is-generator-fn/-/is-generator-fn-2.1.0.tgz#7d140adc389aaf3011a8f2a2a4cfa6faadffb118" integrity sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ== +is-node-process@^1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/is-node-process/-/is-node-process-1.2.0.tgz#ea02a1b90ddb3934a19aea414e88edef7e11d134" + integrity sha512-Vg4o6/fqPxIjtxgUH5QLJhwZ7gW5diGCVlXpuUfELC62CuxM1iHcRe51f2W1FDy04Ai4KJkagKjx3XaqyfRKXw== + is-number@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" @@ -2337,11 +2438,6 @@ jest@^29.7.0: import-local "^3.0.2" jest-cli "^29.7.0" -js-base64@3.7.7: - version "3.7.7" - resolved "https://registry.yarnpkg.com/js-base64/-/js-base64-3.7.7.tgz#e51b84bf78fbf5702b9541e2cb7bfcb893b43e79" - integrity sha512-7rCnleh0z2CkXhH67J8K1Ytz0b2Y+yxTPL+/KOJoa20hfnVQ/3/T6W/KflYI4bRHRagNeXeU2bkNGI3v1oS/lw== - js-tokens@^4.0.0: version "4.0.0" resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" @@ -2529,6 +2625,35 @@ ms@^2.1.3: resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== +msw@^2.8.4: + version "2.10.4" + resolved "https://registry.yarnpkg.com/msw/-/msw-2.10.4.tgz#a39dad96468aecfd752e5b7df4bbc86f1d73dec4" + integrity sha512-6R1or/qyele7q3RyPwNuvc0IxO8L8/Aim6Sz5ncXEgcWUNxSKE+udriTOWHtpMwmfkLYlacA2y7TIx4cL5lgHA== + dependencies: + "@bundled-es-modules/cookie" "^2.0.1" + "@bundled-es-modules/statuses" "^1.0.1" + "@bundled-es-modules/tough-cookie" "^0.1.6" + "@inquirer/confirm" "^5.0.0" + "@mswjs/interceptors" "^0.39.1" + "@open-draft/deferred-promise" "^2.2.0" + "@open-draft/until" "^2.1.0" + "@types/cookie" "^0.6.0" + "@types/statuses" "^2.0.4" + graphql "^16.8.1" + headers-polyfill "^4.0.2" + is-node-process "^1.2.0" + outvariant "^1.4.3" + path-to-regexp "^6.3.0" + picocolors "^1.1.1" + strict-event-emitter "^0.5.1" + type-fest "^4.26.1" + yargs "^17.7.2" + +mute-stream@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/mute-stream/-/mute-stream-2.0.0.tgz#a5446fc0c512b71c83c44d908d5c7b7b4c493b2b" + integrity sha512-WWdIxpyjEn+FhQJQQv9aQAYlHoNVdzIzUySNV1gHUPDSdZJ3yZn7pAAbQcV7B56Mvu881q9FZV+0Vx2xC44VWA== + natural-compare@^1.4.0: version "1.4.0" resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" @@ -2573,11 +2698,6 @@ nwsapi@^2.2.2: resolved "https://registry.yarnpkg.com/nwsapi/-/nwsapi-2.2.20.tgz#22e53253c61e7b0e7e93cef42c891154bcca11ef" integrity sha512-/ieB+mDe4MrrKMT8z+mQL8klXydZWGR5Dowt4RAGKbJ3kIGEx3X4ljUo+6V73IXtUPWgfOlU5B9MlGxFO5T+cA== -object-inspect@^1.13.3: - version "1.13.4" - resolved "https://registry.yarnpkg.com/object-inspect/-/object-inspect-1.13.4.tgz#8375265e21bc20d0fa582c22e1b13485d6e00213" - integrity sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew== - once@^1.3.0: version "1.4.0" resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" @@ -2592,6 +2712,11 @@ onetime@^5.1.2: dependencies: mimic-fn "^2.1.0" +outvariant@^1.4.0, outvariant@^1.4.3: + version "1.4.3" + resolved "https://registry.yarnpkg.com/outvariant/-/outvariant-1.4.3.tgz#221c1bfc093e8fec7075497e7799fdbf43d14873" + integrity sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA== + p-limit@^2.2.0: version "2.3.0" resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.3.0.tgz#3dd33c647a214fdfffd835933eb086da0dc21db1" @@ -2655,6 +2780,11 @@ path-parse@^1.0.7: resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735" integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw== +path-to-regexp@^6.3.0: + version "6.3.0" + resolved "https://registry.yarnpkg.com/path-to-regexp/-/path-to-regexp-6.3.0.tgz#2b6a26a337737a8e1416f9272ed0766b1c0389f4" + integrity sha512-Yhpw4T9C6hPpgPeA28us07OJeqZ5EzQTkbfwuhsUg0c237RomFoETJgmp2sa3F/41gfLE6G5cqcYwznmeEeOlQ== + picocolors@^1.1.1: version "1.1.1" resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.1.1.tgz#3d321af3eab939b083c8f929a1d12cda81c26b6b" @@ -2726,13 +2856,6 @@ pure-rand@^6.0.0: resolved "https://registry.yarnpkg.com/pure-rand/-/pure-rand-6.1.0.tgz#d173cf23258231976ccbdb05247c9787957604f2" integrity sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA== -qs@^6.13.1: - version "6.14.0" - resolved "https://registry.yarnpkg.com/qs/-/qs-6.14.0.tgz#c63fa40680d2c5c941412a0e899c89af60c0a930" - integrity sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w== - dependencies: - side-channel "^1.1.0" - querystringify@^2.1.1: version "2.2.0" resolved "https://registry.yarnpkg.com/querystringify/-/querystringify-2.2.0.tgz#3345941b4153cb9d082d8eee4cda2016a9aef7f6" @@ -2858,51 +2981,16 @@ shebang-regex@^3.0.0: resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== -side-channel-list@^1.0.0: - version "1.0.0" - resolved "https://registry.yarnpkg.com/side-channel-list/-/side-channel-list-1.0.0.tgz#10cb5984263115d3b7a0e336591e290a830af8ad" - integrity sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA== - dependencies: - es-errors "^1.3.0" - object-inspect "^1.13.3" - -side-channel-map@^1.0.1: - version "1.0.1" - resolved "https://registry.yarnpkg.com/side-channel-map/-/side-channel-map-1.0.1.tgz#d6bb6b37902c6fef5174e5f533fab4c732a26f42" - integrity sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA== - dependencies: - call-bound "^1.0.2" - es-errors "^1.3.0" - get-intrinsic "^1.2.5" - object-inspect "^1.13.3" - -side-channel-weakmap@^1.0.2: - version "1.0.2" - resolved "https://registry.yarnpkg.com/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz#11dda19d5368e40ce9ec2bdc1fb0ecbc0790ecea" - integrity sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A== - dependencies: - call-bound "^1.0.2" - es-errors "^1.3.0" - get-intrinsic "^1.2.5" - object-inspect "^1.13.3" - side-channel-map "^1.0.1" - -side-channel@^1.1.0: - version "1.1.0" - resolved "https://registry.yarnpkg.com/side-channel/-/side-channel-1.1.0.tgz#c3fcff9c4da932784873335ec9765fa94ff66bc9" - integrity sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw== - dependencies: - es-errors "^1.3.0" - object-inspect "^1.13.3" - side-channel-list "^1.0.0" - side-channel-map "^1.0.1" - side-channel-weakmap "^1.0.2" - signal-exit@^3.0.3, signal-exit@^3.0.7: version "3.0.7" resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.7.tgz#a9a1767f8af84155114eaabd73f99273c8f59ad9" integrity sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ== +signal-exit@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-4.1.0.tgz#952188c1cbd546070e2dd20d0f41c0ae0530cb04" + integrity sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw== + sisteransi@^1.0.5: version "1.0.5" resolved "https://registry.yarnpkg.com/sisteransi/-/sisteransi-1.0.5.tgz#134d681297756437cc05ca01370d3a7a571075ed" @@ -2963,6 +3051,16 @@ stack-utils@^2.0.3: dependencies: escape-string-regexp "^2.0.0" +statuses@^2.0.1: + version "2.0.2" + resolved "https://registry.yarnpkg.com/statuses/-/statuses-2.0.2.tgz#8f75eecef765b5e1cfcdc080da59409ed424e382" + integrity sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw== + +strict-event-emitter@^0.5.1: + version "0.5.1" + resolved "https://registry.yarnpkg.com/strict-event-emitter/-/strict-event-emitter-0.5.1.tgz#1602ece81c51574ca39c6815e09f1a3e8550bd93" + integrity sha512-vMgjE/GGEPEFnhFub6pa4FmJBRBVOLpIII2hvCZ8Kzb7K0hlHo7mQv6xYrBvCL2LtAIBwFUK8wvuJgTVSQ5MFQ== + string-length@^4.0.1: version "4.0.2" resolved "https://registry.yarnpkg.com/string-length/-/string-length-4.0.2.tgz#a8a8dc7bd5c1a82b9b3c8b87e125f66871b6e57a" @@ -3085,7 +3183,7 @@ to-regex-range@^5.0.1: dependencies: is-number "^7.0.0" -tough-cookie@^4.1.2: +tough-cookie@^4.1.2, tough-cookie@^4.1.4: version "4.1.4" resolved "https://registry.yarnpkg.com/tough-cookie/-/tough-cookie-4.1.4.tgz#945f1461b45b5a8c76821c33ea49c3ac192c1b36" integrity sha512-Loo5UUvLD9ScZ6jh8beX1T6sO1w2/MpCRpEP7V280GKMVUQ0Jzar2U3UJPsrdbziLEMMhu3Ujnq//rhiFuIeag== @@ -3107,7 +3205,7 @@ tr46@~0.0.3: resolved "https://registry.yarnpkg.com/tr46/-/tr46-0.0.3.tgz#8184fd347dac9cdc185992f3a6622e14b9d9ab6a" integrity sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw== -ts-jest@^29.1.1: +ts-jest@^29.3.4: version "29.4.0" resolved "https://registry.yarnpkg.com/ts-jest/-/ts-jest-29.4.0.tgz#bef0ee98d94c83670af7462a1617bf2367a83740" integrity sha512-d423TJMnJGu80/eSgfQ5w/R+0zFJvdtTxwtF9KzFFunOpSeD+79lHJQIiAhluJoyGRbvj9NZJsl9WjCUo0ND7Q== @@ -3148,7 +3246,7 @@ type-fest@^0.21.3: resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.21.3.tgz#d260a24b0198436e133fa26a524a6d65fa3b2e37" integrity sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w== -type-fest@^4.41.0: +type-fest@^4.26.1, type-fest@^4.41.0: version "4.41.0" resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-4.41.0.tgz#6ae1c8e5731273c2bf1f58ad39cbae2c91a46c58" integrity sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA== @@ -3181,11 +3279,6 @@ update-browserslist-db@^1.1.3: escalade "^3.2.0" picocolors "^1.1.1" -url-join@4.0.1: - version "4.0.1" - resolved "https://registry.yarnpkg.com/url-join/-/url-join-4.0.1.tgz#b642e21a2646808ffa178c4c5fda39844e12cde7" - integrity sha512-jk1+QP6ZJqyOiuEI9AEWQfju/nB2Pw466kbA0LEZljHwKeMgd9WrAEgEGxjPDD2+TNbbb37rTyhEfrCXfuKXnA== - url-parse@^1.5.3: version "1.5.10" resolved "https://registry.yarnpkg.com/url-parse/-/url-parse-1.5.10.tgz#9d3c2f736c1d75dd3bd2be507dcc111f1e2ea9c1" @@ -3306,6 +3399,15 @@ which@^2.0.1: dependencies: isexe "^2.0.0" +wrap-ansi@^6.2.0: + version "6.2.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-6.2.0.tgz#e9393ba07102e6c91a3b221478f0257cd2856e53" + integrity sha512-r6lPcBGxZXlIcymEu7InxDMhdW0KDxpLgoFLcguasxCaJ/SOIZwINatK9KY/tf+ZrlywOKU0UDj3ATXUBfxJXA== + dependencies: + ansi-styles "^4.0.0" + string-width "^4.1.0" + strip-ansi "^6.0.0" + wrap-ansi@^7.0.0: version "7.0.0" resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" @@ -3358,7 +3460,7 @@ yargs-parser@^21.1.1: resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-21.1.1.tgz#9096bceebf990d21bb31fa9516e0ede294a77d35" integrity sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw== -yargs@^17.3.1: +yargs@^17.3.1, yargs@^17.7.2: version "17.7.2" resolved "https://registry.yarnpkg.com/yargs/-/yargs-17.7.2.tgz#991df39aca675a192b816e1e0363f9d75d2aa269" integrity sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w== @@ -3375,3 +3477,8 @@ yocto-queue@^0.1.0: version "0.1.0" resolved "https://registry.yarnpkg.com/yocto-queue/-/yocto-queue-0.1.0.tgz#0294eb3dee05028d31ee1a5fa2c556a6aaf10a1b" integrity sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q== + +yoctocolors-cjs@^2.1.2: + version "2.1.2" + resolved "https://registry.yarnpkg.com/yoctocolors-cjs/-/yoctocolors-cjs-2.1.2.tgz#f4b905a840a37506813a7acaa28febe97767a242" + integrity sha512-cYVsTjKl8b+FrnidjibDWskAv7UKOfcwaVZdp/it9n1s9fU3IkgDbhdIRKCW4JDsAlECJY0ytoVPT3sK6kideA==