@astrada.co/ts-astrada-sdk 1.0.1 → 1.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ * @FidelLimited/iplat @FidelLimited/a-team
@@ -0,0 +1,31 @@
1
+ ### Description
2
+
3
+ Add a description here.
4
+
5
+ ### Ticket
6
+
7
+ [Link to Jira ticket](https://astrada.atlassian.net/browse/)
8
+
9
+ ### Checklist
10
+
11
+ <details>
12
+ <ul>
13
+ <li>- [ ] I have used a meaningful title for the pull request, including a conventional commit type (e.g., `feat`, `chore`, `fix`).</li>
14
+ <li>- [ ] I have added the Jira ticket link and ID on the description.</li>
15
+ <li>- [ ] I have tested the change in my local environment (compile and run).</li>
16
+ <li>- [ ] I have ensured strong encryption methods (e.g., MD5 isn’t acceptable).</li>
17
+ <li>- [ ] I have validated pending dependabot Medium/High alerts.</li>
18
+ <li>- [ ] I have performed a self-review of my own code.</li>
19
+ <li>- [ ] I have commented on my code, particularly in hard-to-understand areas.</li>
20
+ <li>- [ ] I have made corresponding changes to the documentation.</li>
21
+ <li>- [ ] I have added or updated an existing test to reflect the change (run `npm test`).</li>
22
+ <li>- [ ] I have checked and fixed any linting errors (e.g. run `npm run lint` or `terraform fmt && terraform validate`).</li>
23
+ </ul>
24
+ </details>
25
+
26
+ ### Notes
27
+
28
+ When discussing the contents of the pull request:
29
+
30
+ 1. Keep the discussion inside the PR as much as possible.
31
+ 2. If any discussion is done outside of the PR, write down the final conclusions/decisions in the PR conversation at the end.
@@ -0,0 +1,222 @@
1
+ name: "Release API SDKs"
2
+
3
+ on:
4
+ workflow_dispatch:
5
+ inputs:
6
+ api_spec_ref:
7
+ description: "The git ref (branch, tag, sha) of the api-spec repo to use"
8
+ type: string
9
+ required: false
10
+ default: "main"
11
+
12
+ jobs:
13
+ build:
14
+ runs-on: ubuntu-latest
15
+ permissions:
16
+ actions: read
17
+ contents: write
18
+ pull-requests: write
19
+
20
+ env:
21
+ language: TypeScript
22
+ generator: typescript-fetch
23
+ repo_name: ts-astrada-sdk
24
+ repo_dir: .
25
+ template_dir: openapi-generator/templates
26
+ additional_properties: modelPropertyNaming=original,npmName=@astrada.co/ts-astrada-sdk,npmVersion=1.0.0,licenseName=MIT
27
+
28
+ steps:
29
+ - name: Generate a token
30
+ id: generate-token
31
+ uses: actions/create-github-app-token@67018539274d69449ef7c02e8e71183d1719ab42 # v2.1.4
32
+ with:
33
+ app-id: ${{ vars.API_SDK_GENERATOR_APP_ID }}
34
+ private-key: ${{ secrets.API_SDK_GENERATOR_APP_PRIVATE_KEY }}
35
+ owner: ${{ github.repository_owner }}
36
+ repositories: |
37
+ api-spec
38
+ ${{ github.event.repository.name }}
39
+
40
+ - name: Checkout api-spec repo
41
+ uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
42
+ with:
43
+ repository: ${{ github.repository_owner }}/api-spec
44
+ path: "./api-spec"
45
+ token: ${{ steps.generate-token.outputs.token }}
46
+ ref: ${{ inputs.api_spec_ref }}
47
+ fetch-depth: 0
48
+
49
+ - name: Set up Node.js
50
+ uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0
51
+ with:
52
+ node-version-file: ./api-spec/package.json
53
+
54
+ - name: Render api-spec configuration
55
+ run: |
56
+ cd ./api-spec
57
+
58
+ npm ci
59
+ npm run bundle:public-api
60
+
61
+ cp -r ./out-public-api.yaml $HOME
62
+
63
+ - name: Determine commit type from conventional commits
64
+ id: commit_type
65
+ run: |
66
+ cd ./api-spec
67
+
68
+ # Get the latest release tag
69
+ LATEST_TAG=$(git describe --tags --abbrev=0 2>/dev/null || echo "")
70
+
71
+ if [ -z "$LATEST_TAG" ]; then
72
+ echo "No previous release found, using initial commit"
73
+ COMMIT_RANGE="HEAD"
74
+ else
75
+ echo "Latest release: $LATEST_TAG"
76
+ COMMIT_RANGE="${LATEST_TAG}..HEAD"
77
+ fi
78
+
79
+ # Get all commit messages since last release
80
+ COMMITS=$(git log --pretty=format:"%s" $COMMIT_RANGE)
81
+
82
+ # Determine the highest priority conventional commit type
83
+ # Priority: feat! > fix! > feat > fix > chore
84
+ COMMIT_TYPE="chore"
85
+
86
+ if echo "$COMMITS" | grep -qE "^feat!(\(.+\))?:|^[^:]+!:.*feat"; then
87
+ COMMIT_TYPE="feat!"
88
+ elif echo "$COMMITS" | grep -qE "^fix!(\(.+\))?:|^[^:]+!:.*fix"; then
89
+ COMMIT_TYPE="fix!"
90
+ elif echo "$COMMITS" | grep -qE "^feat(\(.+\))?:"; then
91
+ COMMIT_TYPE="feat"
92
+ elif echo "$COMMITS" | grep -qE "^fix(\(.+\))?:"; then
93
+ COMMIT_TYPE="fix"
94
+ elif echo "$COMMITS" | grep -qE "^perf(\(.+\))?:"; then
95
+ COMMIT_TYPE="perf"
96
+ elif echo "$COMMITS" | grep -qE "^refactor(\(.+\))?:"; then
97
+ COMMIT_TYPE="refactor"
98
+ fi
99
+
100
+ echo "Determined commit type: $COMMIT_TYPE"
101
+ echo "commit_type=$COMMIT_TYPE" >> $GITHUB_OUTPUT
102
+
103
+ - name: Checkout ${{ github.event.repository.name }} repo
104
+ uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
105
+
106
+ - name: Set up Node.js
107
+ uses: actions/setup-node@2028fbc5c25fe9cf00d9f06a71cc4710d4507903 # v6.0.0
108
+ with:
109
+ node-version-file: package.json
110
+
111
+ - name: Install OpenAPI Generator
112
+ run: |
113
+ npm install -g @openapitools/openapi-generator-cli
114
+
115
+ - name: Generate SDK for ${{ env.language }}
116
+ run: |
117
+ if [ -n "${{ env.template_dir }}" ]; then
118
+ TEMPLATE_FLAG="-t ${{ env.template_dir }}"
119
+ else
120
+ TEMPLATE_FLAG=""
121
+ fi
122
+
123
+ openapi-generator-cli generate \
124
+ -i $HOME/out-public-api.yaml \
125
+ -g ${{ env.generator }} \
126
+ -o ${{ env.repo_dir }} \
127
+ --git-user-id "FidelLimited" \
128
+ --git-repo-id "${{ env.repo_name }}" \
129
+ $TEMPLATE_FLAG \
130
+ --additional-properties=${{ env.additional_properties }} \
131
+ --minimal-update
132
+
133
+ rm -rf ${{ env.repo_dir }}/.openapi-generator*
134
+
135
+ # Show what changed
136
+ git status
137
+
138
+ - name: Create branch and commit changes
139
+ env:
140
+ GH_TOKEN: ${{ steps.generate-token.outputs.token }}
141
+ run: |
142
+ USER_NAME="api-sdk-generator[bot]"
143
+ USER_ID=$(gh api "users/${USER_NAME}" --jq .id)
144
+
145
+ # Configure git
146
+ git config user.name "${USER_NAME}"
147
+ git config user.email "${USER_ID}+${USER_NAME}@users.noreply.github.com"
148
+
149
+ # Get version from release or use timestamp
150
+ # Check if api_spec_ref is a semantic version (e.g., v1.2.3 or 1.2.3)
151
+ if [[ "${{ inputs.api_spec_ref }}" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+ ]]; then
152
+ VERSION="${{ inputs.api_spec_ref }}"
153
+ else
154
+ VERSION="$(date +%Y%m%d-%H%M%S)"
155
+ fi
156
+
157
+ BRANCH_NAME="sdk-update/${VERSION}"
158
+
159
+ # Create and checkout new branch
160
+ git checkout -b ${BRANCH_NAME}
161
+
162
+ # Add all changes
163
+ git add .
164
+
165
+ # Commit if there are changes
166
+ if git diff --staged --quiet; then
167
+ echo "No changes to commit"
168
+ echo "has_changes=false" >> $GITHUB_ENV
169
+ else
170
+ # Use the determined commit type from previous step
171
+ COMMIT_TYPE="${{ steps.commit_type.outputs.commit_type }}"
172
+
173
+ # Create conventional commit message
174
+ if [[ "$COMMIT_TYPE" == *"!"* ]]; then
175
+ # Breaking change - multi-line commit message
176
+ COMMIT_MESSAGE="${COMMIT_TYPE}: update SDK from api-spec ${VERSION}\n\nBREAKING CHANGE: SDK updated with breaking changes from api-spec"
177
+ else
178
+ COMMIT_MESSAGE="${COMMIT_TYPE}: update SDK from api-spec ${VERSION}"
179
+ fi
180
+
181
+ git push origin ${BRANCH_NAME}
182
+ echo "has_changes=true" >> $GITHUB_ENV
183
+ echo "branch_name=${BRANCH_NAME}" >> $GITHUB_ENV
184
+ echo "version=${VERSION}" >> $GITHUB_ENV
185
+ echo "commit_message=${COMMIT_MESSAGE}" >> $GITHUB_ENV
186
+ fi
187
+
188
+ - uses: planetscale/ghcommit-action@343f41817a6a0f882f18bbc59fdd37f49452736f # v0.2.19
189
+ if: env.has_changes == 'true'
190
+ with:
191
+ commit_message: "${{ env.commit_message }}"
192
+ repo: ${{ github.repository }}
193
+ branch: ${{ env.branch_name }}
194
+ env:
195
+ GITHUB_TOKEN: ${{ steps.generate-token.outputs.token }}
196
+
197
+ - name: Create Pull Request
198
+ if: env.has_changes == 'true'
199
+ env:
200
+ GH_TOKEN: ${{ steps.generate-token.outputs.token }}
201
+ run: |
202
+ # Determine if this includes breaking changes
203
+ if [[ "${{ steps.commit_type.outputs.commit_type }}" == *"!"* ]]; then
204
+ BREAKING_NOTICE="⚠️ **This update includes BREAKING CHANGES**"
205
+ else
206
+ BREAKING_NOTICE=""
207
+ fi
208
+
209
+ gh pr create \
210
+ --title "${{ steps.commit_type.outputs.commit_type }}: update SDK from api-spec ${{ env.version }}" \
211
+ --body "This PR contains SDK updates generated from api-spec repository.
212
+
213
+ ${BREAKING_NOTICE}
214
+
215
+ **Commit Type:** \`${{ steps.commit_type.outputs.commit_type }}\`
216
+ **Source:** ${{ github.repository }}@${{ github.sha }}
217
+ **Generator:** openapi-generator (${{ env.generator }})
218
+ **Triggered by:** ${{ github.event_name }}
219
+
220
+ Please review the changes and merge if everything looks good." \
221
+ --base main \
222
+ --head ${{ env.branch_name }}
package/CHANGELOG.md CHANGED
@@ -1,6 +1,6 @@
1
- ## [1.0.1](https://github.com/FidelLimited/ts-astrada-sdk/compare/v1.0.0...v1.0.1) (2025-10-09)
1
+ # [1.2.0](https://github.com/FidelLimited/ts-astrada-sdk/compare/v1.1.0...v1.2.0) (2025-11-21)
2
2
 
3
3
 
4
- ### Bug Fixes
4
+ ### Features
5
5
 
6
- * correct assumptions ([677fc93](https://github.com/FidelLimited/ts-astrada-sdk/commit/677fc938892e11496467b1fd17db80e0a2095e18))
6
+ * **api-sdk:** improve release workflow and add generator templates ([#12](https://github.com/FidelLimited/ts-astrada-sdk/issues/12)) ([5ef13b9](https://github.com/FidelLimited/ts-astrada-sdk/commit/5ef13b943dd11117c0e2ecc383a5afa65d1e4505))
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 Fidel Limited DBA Astrada
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,274 @@
1
+ # Astrada TypeScript SDK
2
+
3
+ <div align="center">
4
+
5
+ [![npm version](https://img.shields.io/npm/v/@astrada.co/ts-astrada-sdk.svg)](https://www.npmjs.com/package/@astrada.co/ts-astrada-sdk)
6
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
7
+ [![TypeScript](https://img.shields.io/badge/TypeScript-5.9+-blue.svg)](https://www.typescriptlang.org/)
8
+
9
+ **The official TypeScript/JavaScript SDK for the Astrada API**
10
+
11
+ Build powerful spend management experiences with real-time transaction data from any Visa or Mastercard.
12
+
13
+ [Documentation](https://docs.astrada.co) • [API Reference](https://docs.astrada.co/reference) • [Get API Keys](https://astrada.co)
14
+
15
+ </div>
16
+
17
+ ---
18
+
19
+ ## What is Astrada?
20
+
21
+ Astrada provides a unified API for transaction data that enables software companies to build bring-your-own-card (BYOC) functionality. Access clean, normalized, and enriched transaction data in real-time from existing Visa and Mastercard cards.
22
+
23
+ ### Key Features
24
+
25
+ - **🚀 Real-time Transaction Feeds** - Get instant access to transaction data as it happens
26
+ - **💳 Universal Card Support** - Works with any Visa or Mastercard
27
+ - **🔒 Enterprise-Grade Security** - PCI-DSS compliant with Security by Design principles
28
+ - **📊 Enriched Data** - Clean, normalized transaction data with enhanced merchant information
29
+ - **🎯 Type-Safe** - Full TypeScript support with auto-generated types
30
+ - **⚡ Modern Stack** - Built for Node.js 18+ with native Fetch API support
31
+
32
+ ---
33
+
34
+ ## Installation
35
+
36
+ ```bash
37
+ npm install @astrada.co/ts-astrada-sdk
38
+ ```
39
+
40
+ ```bash
41
+ yarn add @astrada.co/ts-astrada-sdk
42
+ ```
43
+
44
+ ```bash
45
+ pnpm add @astrada.co/ts-astrada-sdk
46
+ ```
47
+
48
+ ---
49
+
50
+ ## Quick Start
51
+
52
+ ### Authentication
53
+
54
+ First, configure the SDK with your Astrada credentials:
55
+
56
+ ```typescript
57
+ import { Configuration, CardApi, TransactionsApi } from '@astrada.co/ts-astrada-sdk';
58
+
59
+ const config = new Configuration({
60
+ accountId: 'your-account-id',
61
+ clientId: 'your-client-id',
62
+ clientSecret: 'your-client-secret',
63
+ });
64
+ ```
65
+
66
+ > **Note:** The SDK automatically handles OAuth2 token management, including token refresh and caching.
67
+
68
+ ### List Cards
69
+
70
+ ```typescript
71
+ const cardApi = new CardApi(config);
72
+
73
+ const cards = await cardApi.listCards({
74
+ subaccountId: 'sub_123',
75
+ limit: 10,
76
+ });
77
+
78
+ console.log(cards.embedded?.cards);
79
+ ```
80
+
81
+ ### Get Transaction Data
82
+
83
+ ```typescript
84
+ const transactionsApi = new TransactionsApi(config);
85
+
86
+ const transactions = await transactionsApi.getTransactions({
87
+ cardId: 'card_abc123',
88
+ limit: 50,
89
+ startDate: '2024-01-01',
90
+ endDate: '2024-12-31',
91
+ });
92
+
93
+ for (const transaction of transactions.embedded?.transactions || []) {
94
+ console.log(`${transaction.amount} ${transaction.currency} at ${transaction.acceptor?.name}`);
95
+ }
96
+ ```
97
+
98
+ ### Card Subscriptions
99
+
100
+ ```typescript
101
+ const subscriptionApi = new CardSubscriptionApi(config);
102
+
103
+ // Create a card subscription
104
+ const subscription = await subscriptionApi.createCardSubscription({
105
+ subaccountId: 'sub_123',
106
+ inlineObject: {
107
+ cardNumber: '4111111111111111',
108
+ expiryMonth: '12',
109
+ expiryYear: '2025',
110
+ },
111
+ });
112
+
113
+ console.log(`Subscription created: ${subscription.id}`);
114
+ ```
115
+
116
+ ### Webhooks
117
+
118
+ ```typescript
119
+ const webhooksApi = new WebhooksApi(config);
120
+
121
+ // Create a webhook for transaction events
122
+ const webhook = await webhooksApi.createWebhook({
123
+ subaccountId: 'sub_123',
124
+ createWebhookRequest: {
125
+ url: 'https://your-app.com/webhooks/astrada',
126
+ events: ['transaction.created', 'transaction.updated'],
127
+ },
128
+ });
129
+
130
+ console.log(`Webhook created with ID: ${webhook.id}`);
131
+ ```
132
+
133
+ ---
134
+
135
+ ## API Coverage
136
+
137
+ The SDK provides full coverage of the Astrada API:
138
+
139
+ | API | Description |
140
+ |-----|-------------|
141
+ | **CardApi** | Manage and retrieve card information |
142
+ | **CardSubscriptionApi** | Subscribe to card transactions and manage subscriptions |
143
+ | **CardholderApi** | Access cardholder information |
144
+ | **TransactionsApi** | Query and retrieve transaction data |
145
+ | **TransactionMessagesApi** | Access raw transaction messages |
146
+ | **SubaccountsApi** | Manage subaccounts for multi-tenant applications |
147
+ | **WebhooksApi** | Configure webhooks for real-time event notifications |
148
+ | **EnrollmentMethodsApi** | Manage card enrollment methods |
149
+ | **NetworkBulkFeedsApi** | Access bulk transaction feeds |
150
+
151
+ ---
152
+
153
+ ## Advanced Usage
154
+
155
+ ### Custom Fetch Implementation
156
+
157
+ Provide your own fetch implementation for advanced use cases:
158
+
159
+ ```typescript
160
+ import fetch from 'node-fetch';
161
+
162
+ const config = new Configuration({
163
+ accountId: 'your-account-id',
164
+ clientId: 'your-client-id',
165
+ clientSecret: 'your-client-secret',
166
+ fetchApi: fetch as any,
167
+ });
168
+ ```
169
+
170
+ ### Middleware
171
+
172
+ Add custom middleware for logging, retry logic, or request/response transformation:
173
+
174
+ ```typescript
175
+ const api = new TransactionsApi(config).withPreMiddleware(async (context) => {
176
+ console.log(`Making request to: ${context.url}`);
177
+ return context;
178
+ });
179
+ ```
180
+
181
+ ### Error Handling
182
+
183
+ ```typescript
184
+ import { ResponseError } from '@astrada.co/ts-astrada-sdk';
185
+
186
+ try {
187
+ const cards = await cardApi.listCards({ subaccountId: 'sub_123' });
188
+ } catch (error) {
189
+ if (error instanceof ResponseError) {
190
+ console.error(`API Error: ${error.response.status}`);
191
+ const body = await error.response.json();
192
+ console.error(body);
193
+ }
194
+ }
195
+ ```
196
+
197
+ ---
198
+
199
+ ## TypeScript Support
200
+
201
+ The SDK is written in TypeScript and includes comprehensive type definitions:
202
+
203
+ ```typescript
204
+ import type {
205
+ Card,
206
+ Transaction,
207
+ Webhook,
208
+ CardSubscription
209
+ } from '@astrada.co/ts-astrada-sdk';
210
+
211
+ const handleTransaction = (transaction: Transaction) => {
212
+ // Full type safety and IntelliSense support
213
+ console.log(transaction.amount);
214
+ console.log(transaction.acceptor?.name);
215
+ };
216
+ ```
217
+
218
+ ---
219
+
220
+ ## Requirements
221
+
222
+ - **Node.js**: 18.0.0 or higher
223
+ - **TypeScript**: 5.0.0 or higher (for TypeScript users)
224
+
225
+ The SDK uses the native Fetch API available in Node.js 18+.
226
+
227
+ ---
228
+
229
+ ## Development
230
+
231
+ ### Build
232
+
233
+ ```bash
234
+ npm run build
235
+ ```
236
+
237
+ ### Generate from OpenAPI Spec
238
+
239
+ This SDK is auto-generated from the Astrada OpenAPI specification. To regenerate:
240
+
241
+ ```bash
242
+ # From the api-spec repository
243
+ openapi-generator generate -i openapi.yaml -g typescript-fetch -o ../ts-astrada-sdk
244
+ ```
245
+
246
+ ---
247
+
248
+ ## Support
249
+
250
+ - **Documentation**: [docs.astrada.co](https://docs.astrada.co)
251
+ - **Issues**: [GitHub Issues](https://github.com/FidelLimited/ts-astrada-sdk/issues)
252
+ - **Contact**: <support@astrada.co>
253
+
254
+ ---
255
+
256
+ ## License
257
+
258
+ This project is licensed under the MIT License - see the LICENSE file for details.
259
+
260
+ ---
261
+
262
+ ## About Astrada
263
+
264
+ Astrada provides a unified API for transaction data, helping software companies build richer experiences with real-time transaction data from any Visa or Mastercard.
265
+
266
+ ---
267
+
268
+ <div align="center">
269
+
270
+ Made with ❤️ by the Astrada Team
271
+
272
+ [Website](https://astrada.co) • [LinkedIn](https://linkedin.com/company/astrada)
273
+
274
+ </div>
@@ -0,0 +1,2 @@
1
+ README.md
2
+ openapi-generator/
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "{{npmName}}",
3
+ "version": "{{npmVersion}}",
4
+ "description": "Astrada's API client SDK for JavaScript/TypeScript",
5
+ "author": "Astrada",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "https://{{gitHost}}/{{gitUserId}}/{{gitRepoId}}.git"
9
+ },
10
+ {{#licenseName}}
11
+ "license": "{{licenseName}}",
12
+ {{/licenseName}}
13
+ {{#packageAsSourceOnlyLibrary}}
14
+ "main": "./index.ts",
15
+ {{/packageAsSourceOnlyLibrary}}
16
+ {{^packageAsSourceOnlyLibrary}}
17
+ "main": "./dist/index.js",
18
+ "types": "./dist/index.d.ts",
19
+ {{#supportsES6}}
20
+ "module": "./dist/esm/index.js",
21
+ "sideEffects": false,
22
+ {{/supportsES6}}
23
+ "scripts": {
24
+ "prebuild": "rm -rf dist",
25
+ "build": "tsc{{#supportsES6}} && tsc -p tsconfig.esm.json{{/supportsES6}}"{{^sagasAndRecords}},
26
+ "prepare": "npm run build"{{/sagasAndRecords}}
27
+ },
28
+ {{/packageAsSourceOnlyLibrary}}
29
+ "devDependencies": {
30
+ {{#sagasAndRecords}}
31
+ "immutable": "^4.0.0-rc.12",
32
+ "normalizr": "^3.6.1",
33
+ "redux-saga": "^1.1.3",
34
+ "redux-ts-simple": "^3.2.0",
35
+ "reselect": "^4.0.0",
36
+ {{/sagasAndRecords}}
37
+ "typescript": "^4.0 || ^5.0"
38
+ }{{#npmRepository}},{{/npmRepository}}
39
+ {{#npmRepository}}
40
+ "publishConfig": {
41
+ "registry": "{{npmRepository}}"
42
+ }
43
+ {{/npmRepository}}
44
+ }
@@ -0,0 +1,515 @@
1
+ /* tslint:disable */
2
+ /* eslint-disable */
3
+ {{> licenseInfo }}
4
+
5
+
6
+ export const BASE_PATH = "{{{basePath}}}".replace(/\/+$/, "");
7
+
8
+ export interface ConfigurationParameters {
9
+ accountId: string; // parameter for authentication
10
+ clientId: string; // parameter for authentication
11
+ clientSecret: string; // parameter for authentication
12
+ // optional parameters
13
+ basePath?: string; // override base path
14
+ fetchApi?: FetchAPI; // override for fetch implementation
15
+ middleware?: Middleware[]; // middleware to apply before/after fetch requests
16
+ queryParamsStringify?: (params: HTTPQuery) => string; // stringify function for query strings
17
+ headers?: HTTPHeaders; //header params we want to use on every request
18
+ credentials?: RequestCredentials; //value for the credentials param we want to use on each request
19
+ }
20
+
21
+ export interface AccessToken {
22
+ access_token: string;
23
+ token_type: string;
24
+ expires_in: number;
25
+ scope?: string;
26
+ }
27
+
28
+ export interface AuthenticationParameter {
29
+ accountId: string;
30
+ clientId: string;
31
+ clientSecret: string;
32
+ fetchApi: FetchAPI;
33
+ basePath: string;
34
+ }
35
+
36
+ export interface AuthenticationError {
37
+ error: string;
38
+ error_description?: string;
39
+ status?: number;
40
+ }
41
+
42
+ export class Configuration {
43
+ private authClient: AuthenticationClient
44
+ constructor(private configuration: ConfigurationParameters) {
45
+ this.authClient = new AuthenticationClient({
46
+ basePath: this.basePath,
47
+ clientId: this.clientId,
48
+ clientSecret: this.clientSecret,
49
+ accountId: this.accountId,
50
+ fetchApi: this.fetchApi
51
+ });
52
+ }
53
+
54
+ set config(configuration: Configuration) {
55
+ this.configuration = configuration;
56
+ }
57
+
58
+ get accessToken(): (name?: string, scopes?: string[]) => Promise<string> {
59
+ return this.authClient.getAccessToken.bind(this.authClient);
60
+ }
61
+
62
+ get accountId(): string {
63
+ return this.configuration.accountId;
64
+ }
65
+
66
+ get clientId(): string {
67
+ return this.configuration.clientId;
68
+ }
69
+
70
+ get clientSecret(): string {
71
+ return this.configuration.clientSecret;
72
+ }
73
+
74
+ get basePath(): string {
75
+ return this.configuration.basePath != null ? this.configuration.basePath : BASE_PATH;
76
+ }
77
+
78
+ get fetchApi(): FetchAPI | undefined {
79
+ return this.configuration.fetchApi;
80
+ }
81
+
82
+ get middleware(): Middleware[] {
83
+ return this.configuration.middleware || [];
84
+ }
85
+
86
+ get queryParamsStringify(): (params: HTTPQuery) => string {
87
+ return this.configuration.queryParamsStringify || querystring;
88
+ }
89
+
90
+ get headers(): HTTPHeaders | undefined {
91
+ return this.configuration.headers;
92
+ }
93
+
94
+ get credentials(): RequestCredentials | undefined {
95
+ return this.configuration.credentials;
96
+ }
97
+ }
98
+
99
+ export class AuthenticationClient {
100
+ private cachedToken: AccessToken | null = null;
101
+ private tokenExpiry: number = 0;
102
+
103
+ constructor(private authConfig: AuthenticationParameter) { }
104
+
105
+ async getAccessToken(name?: string, scopes?: string[]): Promise<string> {
106
+ if (this.isTokenValid()) {
107
+ return 'Bearer ' + this.cachedToken!.access_token;
108
+ }
109
+
110
+ const tokenResponse = await this.requestNewToken();
111
+ this.cacheToken(tokenResponse);
112
+ return 'Bearer ' + tokenResponse.access_token;
113
+ }
114
+
115
+ private async requestNewToken(): Promise<AccessToken> {
116
+ const params = new URLSearchParams({
117
+ client_id: this.authConfig.clientId,
118
+ client_secret: this.authConfig.clientSecret,
119
+ grant_type: "client_credentials",
120
+ });
121
+ const url = `${this.authConfig.basePath}/auth/realms/${this.authConfig.accountId}/protocol/openid-connect/token`;
122
+
123
+ const response = await (this.authConfig.fetchApi || fetch)(url, {
124
+ method: 'POST',
125
+ headers: {
126
+ 'Content-Type': 'application/x-www-form-urlencoded',
127
+ },
128
+ body: params
129
+ });
130
+ const data = await response.json() as any;
131
+
132
+ if (response && (response.status >= 200 && response.status < 300)) {
133
+ return data as AccessToken;
134
+ }
135
+
136
+ if (data) {
137
+ const astradaError: AuthenticationError = {
138
+ error: data.error || "authentication_failed",
139
+ error_description:
140
+ data.error_description ||
141
+ "Failed to authenticate with Astrada API",
142
+ status: response.status,
143
+ };
144
+ throw new ResponseError(response, `Authentication failed: ${astradaError.error_description}`);
145
+ }
146
+
147
+ throw new ResponseError(response, 'Response returned an error code');
148
+ }
149
+
150
+ private cacheToken(token: AccessToken): void {
151
+ this.cachedToken = token;
152
+ this.tokenExpiry = Date.now() + token.expires_in * 1000 - 30000; // 30s buffer
153
+ }
154
+
155
+ private isTokenValid(): boolean {
156
+ return this.cachedToken !== null && Date.now() < this.tokenExpiry;
157
+ }
158
+
159
+ clearCache(): void {
160
+ this.cachedToken = null;
161
+ this.tokenExpiry = 0;
162
+ }
163
+ }
164
+
165
+
166
+ /**
167
+ * This is the base class for all generated API classes.
168
+ */
169
+ export class BaseAPI {
170
+
171
+ private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i');
172
+ private middleware: Middleware[];
173
+ private cachedToken: AccessToken | null = null;
174
+ private tokenExpiry: number = 0;
175
+
176
+ constructor(protected configuration: Configuration) {
177
+ this.middleware = configuration.middleware;
178
+ }
179
+
180
+ withMiddleware<T extends BaseAPI>(this: T, ...middlewares: Middleware[]) {
181
+ const next = this.clone<T>();
182
+ next.middleware = next.middleware.concat(...middlewares);
183
+ return next;
184
+ }
185
+
186
+ withPreMiddleware<T extends BaseAPI>(this: T, ...preMiddlewares: Array<Middleware['pre']>) {
187
+ const middlewares = preMiddlewares.map((pre) => ({ pre }));
188
+ return this.withMiddleware<T>(...middlewares);
189
+ }
190
+
191
+ withPostMiddleware<T extends BaseAPI>(this: T, ...postMiddlewares: Array<Middleware['post']>) {
192
+ const middlewares = postMiddlewares.map((post) => ({ post }));
193
+ return this.withMiddleware<T>(...middlewares);
194
+ }
195
+
196
+ /**
197
+ * Check if the given MIME is a JSON MIME.
198
+ * JSON MIME examples:
199
+ * application/json
200
+ * application/json; charset=UTF8
201
+ * APPLICATION/JSON
202
+ * application/vnd.company+json
203
+ * @param mime - MIME (Multipurpose Internet Mail Extensions)
204
+ * @return True if the given MIME is JSON, false otherwise.
205
+ */
206
+ protected isJsonMime(mime: string | null | undefined): boolean {
207
+ if (!mime) {
208
+ return false;
209
+ }
210
+ return BaseAPI.jsonRegex.test(mime);
211
+ }
212
+
213
+ protected async request(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction): Promise<Response> {
214
+ const { url, init } = await this.createFetchParams(context, initOverrides);
215
+
216
+ const response = await this.fetchApi(url, init);
217
+ if (response && (response.status >= 200 && response.status < 300)) {
218
+ return response;
219
+ }
220
+ throw new ResponseError(response, 'Response returned an error code');
221
+ }
222
+
223
+ private async createFetchParams(context: RequestOpts, initOverrides?: RequestInit | InitOverrideFunction) {
224
+ let url = this.configuration.basePath + context.path;
225
+ if (context.query !== undefined && Object.keys(context.query).length !== 0) {
226
+ // only add the querystring to the URL if there are query parameters.
227
+ // this is done to avoid urls ending with a "?" character which buggy webservers
228
+ // do not handle correctly sometimes.
229
+ url += '?' + this.configuration.queryParamsStringify(context.query);
230
+ }
231
+
232
+ const headers = Object.assign({}, this.configuration.headers, context.headers);
233
+ Object.keys(headers).forEach(key => headers[key] === undefined ? delete headers[key] : {});
234
+
235
+ const initOverrideFn =
236
+ typeof initOverrides === "function"
237
+ ? initOverrides
238
+ : async () => initOverrides;
239
+
240
+ const initParams = {
241
+ method: context.method,
242
+ headers,
243
+ body: context.body,
244
+ credentials: this.configuration.credentials,
245
+ };
246
+
247
+ const overriddenInit: RequestInit = {
248
+ ...initParams,
249
+ ...(await initOverrideFn({
250
+ init: initParams,
251
+ context,
252
+ }))
253
+ };
254
+
255
+ let body: any;
256
+ if (isFormData(overriddenInit.body)
257
+ || (overriddenInit.body instanceof URLSearchParams)
258
+ || isBlob(overriddenInit.body)) {
259
+ body = overriddenInit.body;
260
+ } else if (this.isJsonMime(headers['Content-Type'])) {
261
+ body = JSON.stringify(overriddenInit.body);
262
+ } else {
263
+ body = overriddenInit.body;
264
+ }
265
+
266
+ const init: RequestInit = {
267
+ ...overriddenInit,
268
+ body
269
+ };
270
+
271
+ return { url, init };
272
+ }
273
+
274
+ private fetchApi = async (url: string, init: RequestInit) => {
275
+ let fetchParams = { url, init };
276
+ for (const middleware of this.middleware) {
277
+ if (middleware.pre) {
278
+ fetchParams = await middleware.pre({
279
+ fetch: this.fetchApi,
280
+ ...fetchParams,
281
+ }) || fetchParams;
282
+ }
283
+ }
284
+ let response: Response | undefined = undefined;
285
+ try {
286
+ response = await (this.configuration.fetchApi || fetch)(fetchParams.url, fetchParams.init);
287
+ } catch (e) {
288
+ for (const middleware of this.middleware) {
289
+ if (middleware.onError) {
290
+ response = await middleware.onError({
291
+ fetch: this.fetchApi,
292
+ url: fetchParams.url,
293
+ init: fetchParams.init,
294
+ error: e,
295
+ response: response ? response.clone() : undefined,
296
+ }) || response;
297
+ }
298
+ }
299
+ if (response === undefined) {
300
+ if (e instanceof Error) {
301
+ throw new FetchError(e, 'The request failed and the interceptors did not return an alternative response');
302
+ } else {
303
+ throw e;
304
+ }
305
+ }
306
+ }
307
+ for (const middleware of this.middleware) {
308
+ if (middleware.post) {
309
+ response = await middleware.post({
310
+ fetch: this.fetchApi,
311
+ url: fetchParams.url,
312
+ init: fetchParams.init,
313
+ response: response.clone(),
314
+ }) || response;
315
+ }
316
+ }
317
+ return response;
318
+ }
319
+
320
+ /**
321
+ * Create a shallow clone of `this` by constructing a new instance
322
+ * and then shallow cloning data members.
323
+ */
324
+ private clone<T extends BaseAPI>(this: T): T {
325
+ const constructor = this.constructor as any;
326
+ const next = new constructor(this.configuration);
327
+ next.middleware = this.middleware.slice();
328
+ return next;
329
+ }
330
+ };
331
+
332
+ function isBlob(value: any): value is Blob {
333
+ return typeof Blob !== 'undefined' && value instanceof Blob;
334
+ }
335
+
336
+ function isFormData(value: any): value is FormData {
337
+ return typeof FormData !== "undefined" && value instanceof FormData;
338
+ }
339
+
340
+ export class ResponseError extends Error {
341
+ override name: "ResponseError" = "ResponseError";
342
+ constructor(public response: Response, msg?: string) {
343
+ super(msg);
344
+ }
345
+ }
346
+
347
+ export class FetchError extends Error {
348
+ override name: "FetchError" = "FetchError";
349
+ constructor(public cause: Error, msg?: string) {
350
+ super(msg);
351
+ }
352
+ }
353
+
354
+ export class RequiredError extends Error {
355
+ override name: "RequiredError" = "RequiredError";
356
+ constructor(public field: string, msg?: string) {
357
+ super(msg);
358
+ }
359
+ }
360
+
361
+ export const COLLECTION_FORMATS = {
362
+ csv: ",",
363
+ ssv: " ",
364
+ tsv: "\t",
365
+ pipes: "|",
366
+ };
367
+
368
+ export type FetchAPI = typeof fetch;
369
+ export type RequestCredentials = 'omit' | 'same-origin' | 'include';
370
+
371
+ export type Json = any;
372
+ export type HTTPMethod = 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS' | 'HEAD';
373
+ export type HTTPHeaders = { [key: string]: string };
374
+ export type HTTPQuery = { [key: string]: string | number | null | boolean | Array<string | number | null | boolean> | Set<string | number | null | boolean> | HTTPQuery };
375
+ export type HTTPBody = Json | FormData | URLSearchParams;
376
+ export type HTTPRequestInit = { headers?: HTTPHeaders; method: HTTPMethod; credentials?: RequestCredentials; body?: HTTPBody };
377
+ export type ModelPropertyNaming = 'camelCase' | 'snake_case' | 'PascalCase' | 'original';
378
+
379
+ export type InitOverrideFunction = (requestContext: { init: HTTPRequestInit, context: RequestOpts }) => Promise<RequestInit>
380
+
381
+ export interface FetchParams {
382
+ url: string;
383
+ init: RequestInit;
384
+ }
385
+
386
+ export interface RequestOpts {
387
+ path: string;
388
+ method: HTTPMethod;
389
+ headers: HTTPHeaders;
390
+ query?: HTTPQuery;
391
+ body?: HTTPBody;
392
+ }
393
+
394
+ export function querystring(params: HTTPQuery, prefix: string = ''): string {
395
+ return Object.keys(params)
396
+ .map(key => querystringSingleKey(key, params[key], prefix))
397
+ .filter(part => part.length > 0)
398
+ .join('&');
399
+ }
400
+
401
+ function querystringSingleKey(key: string, value: string | number | null | undefined | boolean | Array<string | number | null | boolean> | Set<string | number | null | boolean> | HTTPQuery, keyPrefix: string = ''): string {
402
+ const fullKey = keyPrefix + (keyPrefix.length ? `[${key}]` : key);
403
+ if (value instanceof Array) {
404
+ const multiValue = value.map(singleValue => encodeURIComponent(String(singleValue)))
405
+ .join(`&${encodeURIComponent(fullKey)}=`);
406
+ return `${encodeURIComponent(fullKey)}=${multiValue}`;
407
+ }
408
+ if (value instanceof Set) {
409
+ const valueAsArray = Array.from(value);
410
+ return querystringSingleKey(key, valueAsArray, keyPrefix);
411
+ }
412
+ if (value instanceof Date) {
413
+ return `${encodeURIComponent(fullKey)}=${encodeURIComponent(value.toISOString())}`;
414
+ }
415
+ if (value instanceof Object) {
416
+ return querystring(value as HTTPQuery, fullKey);
417
+ }
418
+ return `${encodeURIComponent(fullKey)}=${encodeURIComponent(String(value))}`;
419
+ }
420
+
421
+ export function exists(json: any, key: string) {
422
+ const value = json[key];
423
+ return value !== null && value !== undefined;
424
+ }
425
+
426
+ {{^ withoutRuntimeChecks }}
427
+ export function mapValues(data: any, fn: (item: any) => any) {
428
+ const result: { [key: string]: any } = {};
429
+ for (const key of Object.keys(data)) {
430
+ result[key] = fn(data[key]);
431
+ }
432
+ return result;
433
+ }
434
+ {{/withoutRuntimeChecks }}
435
+
436
+ export function canConsumeForm(consumes: Consume[]): boolean {
437
+ for (const consume of consumes) {
438
+ if ('multipart/form-data' === consume.contentType) {
439
+ return true;
440
+ }
441
+ }
442
+ return false;
443
+ }
444
+
445
+ export interface Consume {
446
+ contentType: string;
447
+ }
448
+
449
+ export interface RequestContext {
450
+ fetch: FetchAPI;
451
+ url: string;
452
+ init: RequestInit;
453
+ }
454
+
455
+ export interface ResponseContext {
456
+ fetch: FetchAPI;
457
+ url: string;
458
+ init: RequestInit;
459
+ response: Response;
460
+ }
461
+
462
+ export interface ErrorContext {
463
+ fetch: FetchAPI;
464
+ url: string;
465
+ init: RequestInit;
466
+ error: unknown;
467
+ response?: Response;
468
+ }
469
+
470
+ export interface Middleware {
471
+ pre?(context: RequestContext): Promise<FetchParams | void>;
472
+ post?(context: ResponseContext): Promise<Response | void>;
473
+ onError?(context: ErrorContext): Promise<Response | void>;
474
+ }
475
+
476
+ export interface ApiResponse<T> {
477
+ raw: Response;
478
+ value(): Promise<T>;
479
+ }
480
+
481
+ export interface ResponseTransformer<T> {
482
+ (json: any): T;
483
+ }
484
+
485
+ export class JSONApiResponse<T> {
486
+ constructor(public raw: Response, private transformer: ResponseTransformer<T> = (jsonValue: any) => jsonValue) { }
487
+
488
+ async value(): Promise<T> {
489
+ return this.transformer(await this.raw.json());
490
+ }
491
+ }
492
+
493
+ export class VoidApiResponse {
494
+ constructor(public raw: Response) { }
495
+
496
+ async value(): Promise<void> {
497
+ return undefined;
498
+ }
499
+ }
500
+
501
+ export class BlobApiResponse {
502
+ constructor(public raw: Response) { }
503
+
504
+ async value(): Promise<Blob> {
505
+ return await this.raw.blob();
506
+ };
507
+ }
508
+
509
+ export class TextApiResponse {
510
+ constructor(public raw: Response) { }
511
+
512
+ async value(): Promise<string> {
513
+ return await this.raw.text();
514
+ };
515
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrada.co/ts-astrada-sdk",
3
- "version": "1.0.1",
3
+ "version": "1.2.0",
4
4
  "description": "",
5
5
  "author": "FidelLimited",
6
6
  "license": "MIT",
@@ -11,7 +11,7 @@
11
11
  "homepage": "https://github.com/FidelLimited/ts-astrada-sdk#readme",
12
12
  "main": "lib/index.js",
13
13
  "scripts": {
14
- "prebuild": "rm -rf lib",
14
+ "prebuild": "rm -rf dist",
15
15
  "build": "tsc"
16
16
  },
17
17
  "devDependencies": {