@bcis/sdk 0.1.0 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +0 -2
- package/dist/index.d.mts +51 -14
- package/dist/index.d.ts +51 -14
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,7 +1,5 @@
|
|
|
1
1
|
# @bcis/sdk
|
|
2
2
|
|
|
3
|
-
> **Auto-generated** — re-run `npm run generate` in the `sdk-generator` project to update this file.
|
|
4
|
-
|
|
5
3
|
Type-safe TypeScript SDK for the [BCIS (Building Cost Information Service)](https://bcis.co.uk) APIs.
|
|
6
4
|
Supports both **ESM** and **CommonJS** environments with full TypeScript declarations.
|
|
7
5
|
|
package/dist/index.d.mts
CHANGED
|
@@ -6,23 +6,43 @@ interface ClientCredentialsConfig {
|
|
|
6
6
|
clientId: string;
|
|
7
7
|
/** OAuth2 client secret */
|
|
8
8
|
clientSecret: string;
|
|
9
|
-
/**
|
|
10
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Token endpoint URL.
|
|
11
|
+
* If omitted, it is resolved from `discoveryUrl` (defaults to the BCIS identity provider).
|
|
12
|
+
*/
|
|
13
|
+
tokenUrl?: string;
|
|
11
14
|
/** Space-separated or array of OAuth2 scopes to request */
|
|
12
15
|
scopes?: string[];
|
|
16
|
+
/**
|
|
17
|
+
* OpenID Connect discovery URL used to resolve endpoints when `tokenUrl` is not set.
|
|
18
|
+
* Defaults to `https://id.bcis.co.uk/.well-known/openid-configuration`.
|
|
19
|
+
*/
|
|
20
|
+
discoveryUrl?: string;
|
|
13
21
|
}
|
|
14
22
|
interface AuthorizationCodeConfig {
|
|
15
23
|
flow: 'authorization-code';
|
|
16
24
|
/** OAuth2 client ID */
|
|
17
25
|
clientId: string;
|
|
18
|
-
/**
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
26
|
+
/**
|
|
27
|
+
* Token endpoint URL.
|
|
28
|
+
* If omitted, it is resolved from `discoveryUrl` (defaults to the BCIS identity provider).
|
|
29
|
+
*/
|
|
30
|
+
tokenUrl?: string;
|
|
31
|
+
/**
|
|
32
|
+
* Authorization endpoint URL (where users are redirected to log in).
|
|
33
|
+
* If omitted, it is resolved from `discoveryUrl` (defaults to the BCIS identity provider).
|
|
34
|
+
*/
|
|
35
|
+
authorizationUrl?: string;
|
|
22
36
|
/** Redirect URI registered with the OAuth2 provider */
|
|
23
37
|
redirectUri: string;
|
|
24
38
|
/** Scopes to request */
|
|
25
39
|
scopes?: string[];
|
|
40
|
+
/**
|
|
41
|
+
* OpenID Connect discovery URL used to resolve endpoints when `tokenUrl` or
|
|
42
|
+
* `authorizationUrl` are not set.
|
|
43
|
+
* Defaults to `https://id.bcis.co.uk/.well-known/openid-configuration`.
|
|
44
|
+
*/
|
|
45
|
+
discoveryUrl?: string;
|
|
26
46
|
}
|
|
27
47
|
/** Standard OAuth2 token response */
|
|
28
48
|
interface TokenResponse {
|
|
@@ -40,24 +60,25 @@ interface TokenResponse {
|
|
|
40
60
|
* - Client Credentials flow (server-to-server, fully automatic)
|
|
41
61
|
* - Authorization Code + PKCE flow (user-facing applications)
|
|
42
62
|
*
|
|
43
|
-
*
|
|
63
|
+
* Endpoint URLs (`tokenUrl`, `authorizationUrl`) are optional — when omitted they are
|
|
64
|
+
* resolved automatically from the BCIS OpenID Connect discovery document at
|
|
65
|
+
* `https://id.bcis.co.uk/.well-known/openid-configuration`.
|
|
66
|
+
*
|
|
67
|
+
* @example Client Credentials (auto-discovered endpoints)
|
|
44
68
|
* ```ts
|
|
45
69
|
* const auth = new AuthManager({
|
|
46
70
|
* flow: 'client-credentials',
|
|
47
71
|
* clientId: 'my-id',
|
|
48
72
|
* clientSecret: 'my-secret',
|
|
49
|
-
* tokenUrl: 'https://auth.bcis.co.uk/oauth/token',
|
|
50
73
|
* });
|
|
51
74
|
* const token = await auth.getAccessToken();
|
|
52
75
|
* ```
|
|
53
76
|
*
|
|
54
|
-
* @example Authorization Code
|
|
77
|
+
* @example Authorization Code (auto-discovered endpoints)
|
|
55
78
|
* ```ts
|
|
56
79
|
* const auth = new AuthManager({
|
|
57
80
|
* flow: 'authorization-code',
|
|
58
81
|
* clientId: 'my-id',
|
|
59
|
-
* tokenUrl: 'https://auth.bcis.co.uk/oauth/token',
|
|
60
|
-
* authorizationUrl: 'https://auth.bcis.co.uk/authorize',
|
|
61
82
|
* redirectUri: 'https://myapp.com/callback',
|
|
62
83
|
* scopes: ['openid', 'profile'],
|
|
63
84
|
* });
|
|
@@ -78,6 +99,8 @@ declare class AuthManager {
|
|
|
78
99
|
private readonly store;
|
|
79
100
|
/** Pending token fetch promise to prevent concurrent requests */
|
|
80
101
|
private inflight;
|
|
102
|
+
/** Cached resolved endpoints (populated lazily from OIDC discovery) */
|
|
103
|
+
private endpoints;
|
|
81
104
|
constructor(config: AuthConfig);
|
|
82
105
|
/**
|
|
83
106
|
* Returns a valid access token, fetching or refreshing as needed.
|
|
@@ -103,6 +126,11 @@ declare class AuthManager {
|
|
|
103
126
|
handleCallback(code: string, codeVerifier: string): Promise<void>;
|
|
104
127
|
/** Clears all stored tokens. */
|
|
105
128
|
clearTokens(): void;
|
|
129
|
+
/**
|
|
130
|
+
* Resolves `tokenUrl` and `authorizationUrl`, fetching the OIDC discovery document
|
|
131
|
+
* if either URL is absent from the config. Result is cached after the first call.
|
|
132
|
+
*/
|
|
133
|
+
private resolveEndpoints;
|
|
106
134
|
private refresh;
|
|
107
135
|
}
|
|
108
136
|
|
|
@@ -288,7 +316,10 @@ interface CodesUpdateParams {
|
|
|
288
316
|
}
|
|
289
317
|
declare class CoreApiClient {
|
|
290
318
|
private readonly client;
|
|
291
|
-
|
|
319
|
+
private readonly baseUrl;
|
|
320
|
+
constructor(auth: AuthManager, options?: {
|
|
321
|
+
baseUrl?: string;
|
|
322
|
+
});
|
|
292
323
|
/** abp-retrieve */
|
|
293
324
|
abpRetrieve(params: AbpRetrieveParams): Promise<AbpResponseDto>;
|
|
294
325
|
/** indices-retrieve */
|
|
@@ -362,7 +393,10 @@ interface ReportUsageParams {
|
|
|
362
393
|
}
|
|
363
394
|
declare class ResidentialRebuildClient {
|
|
364
395
|
private readonly client;
|
|
365
|
-
|
|
396
|
+
private readonly baseUrl;
|
|
397
|
+
constructor(auth: AuthManager, options?: {
|
|
398
|
+
baseUrl?: string;
|
|
399
|
+
});
|
|
366
400
|
/** rbls-calculate */
|
|
367
401
|
calculate(params: CalculateParams): Promise<CalculationResponse>;
|
|
368
402
|
/** rbls-report-use */
|
|
@@ -590,7 +624,10 @@ interface GetBuildUpParams {
|
|
|
590
624
|
}
|
|
591
625
|
declare class ScheduleOfRatesClient {
|
|
592
626
|
private readonly client;
|
|
593
|
-
|
|
627
|
+
private readonly baseUrl;
|
|
628
|
+
constructor(auth: AuthManager, options?: {
|
|
629
|
+
baseUrl?: string;
|
|
630
|
+
});
|
|
594
631
|
/** Lists books and editions available to user */
|
|
595
632
|
getBooksEdition(): Promise<EditionsDto>;
|
|
596
633
|
/** Lists matching rates */
|
package/dist/index.d.ts
CHANGED
|
@@ -6,23 +6,43 @@ interface ClientCredentialsConfig {
|
|
|
6
6
|
clientId: string;
|
|
7
7
|
/** OAuth2 client secret */
|
|
8
8
|
clientSecret: string;
|
|
9
|
-
/**
|
|
10
|
-
|
|
9
|
+
/**
|
|
10
|
+
* Token endpoint URL.
|
|
11
|
+
* If omitted, it is resolved from `discoveryUrl` (defaults to the BCIS identity provider).
|
|
12
|
+
*/
|
|
13
|
+
tokenUrl?: string;
|
|
11
14
|
/** Space-separated or array of OAuth2 scopes to request */
|
|
12
15
|
scopes?: string[];
|
|
16
|
+
/**
|
|
17
|
+
* OpenID Connect discovery URL used to resolve endpoints when `tokenUrl` is not set.
|
|
18
|
+
* Defaults to `https://id.bcis.co.uk/.well-known/openid-configuration`.
|
|
19
|
+
*/
|
|
20
|
+
discoveryUrl?: string;
|
|
13
21
|
}
|
|
14
22
|
interface AuthorizationCodeConfig {
|
|
15
23
|
flow: 'authorization-code';
|
|
16
24
|
/** OAuth2 client ID */
|
|
17
25
|
clientId: string;
|
|
18
|
-
/**
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
26
|
+
/**
|
|
27
|
+
* Token endpoint URL.
|
|
28
|
+
* If omitted, it is resolved from `discoveryUrl` (defaults to the BCIS identity provider).
|
|
29
|
+
*/
|
|
30
|
+
tokenUrl?: string;
|
|
31
|
+
/**
|
|
32
|
+
* Authorization endpoint URL (where users are redirected to log in).
|
|
33
|
+
* If omitted, it is resolved from `discoveryUrl` (defaults to the BCIS identity provider).
|
|
34
|
+
*/
|
|
35
|
+
authorizationUrl?: string;
|
|
22
36
|
/** Redirect URI registered with the OAuth2 provider */
|
|
23
37
|
redirectUri: string;
|
|
24
38
|
/** Scopes to request */
|
|
25
39
|
scopes?: string[];
|
|
40
|
+
/**
|
|
41
|
+
* OpenID Connect discovery URL used to resolve endpoints when `tokenUrl` or
|
|
42
|
+
* `authorizationUrl` are not set.
|
|
43
|
+
* Defaults to `https://id.bcis.co.uk/.well-known/openid-configuration`.
|
|
44
|
+
*/
|
|
45
|
+
discoveryUrl?: string;
|
|
26
46
|
}
|
|
27
47
|
/** Standard OAuth2 token response */
|
|
28
48
|
interface TokenResponse {
|
|
@@ -40,24 +60,25 @@ interface TokenResponse {
|
|
|
40
60
|
* - Client Credentials flow (server-to-server, fully automatic)
|
|
41
61
|
* - Authorization Code + PKCE flow (user-facing applications)
|
|
42
62
|
*
|
|
43
|
-
*
|
|
63
|
+
* Endpoint URLs (`tokenUrl`, `authorizationUrl`) are optional — when omitted they are
|
|
64
|
+
* resolved automatically from the BCIS OpenID Connect discovery document at
|
|
65
|
+
* `https://id.bcis.co.uk/.well-known/openid-configuration`.
|
|
66
|
+
*
|
|
67
|
+
* @example Client Credentials (auto-discovered endpoints)
|
|
44
68
|
* ```ts
|
|
45
69
|
* const auth = new AuthManager({
|
|
46
70
|
* flow: 'client-credentials',
|
|
47
71
|
* clientId: 'my-id',
|
|
48
72
|
* clientSecret: 'my-secret',
|
|
49
|
-
* tokenUrl: 'https://auth.bcis.co.uk/oauth/token',
|
|
50
73
|
* });
|
|
51
74
|
* const token = await auth.getAccessToken();
|
|
52
75
|
* ```
|
|
53
76
|
*
|
|
54
|
-
* @example Authorization Code
|
|
77
|
+
* @example Authorization Code (auto-discovered endpoints)
|
|
55
78
|
* ```ts
|
|
56
79
|
* const auth = new AuthManager({
|
|
57
80
|
* flow: 'authorization-code',
|
|
58
81
|
* clientId: 'my-id',
|
|
59
|
-
* tokenUrl: 'https://auth.bcis.co.uk/oauth/token',
|
|
60
|
-
* authorizationUrl: 'https://auth.bcis.co.uk/authorize',
|
|
61
82
|
* redirectUri: 'https://myapp.com/callback',
|
|
62
83
|
* scopes: ['openid', 'profile'],
|
|
63
84
|
* });
|
|
@@ -78,6 +99,8 @@ declare class AuthManager {
|
|
|
78
99
|
private readonly store;
|
|
79
100
|
/** Pending token fetch promise to prevent concurrent requests */
|
|
80
101
|
private inflight;
|
|
102
|
+
/** Cached resolved endpoints (populated lazily from OIDC discovery) */
|
|
103
|
+
private endpoints;
|
|
81
104
|
constructor(config: AuthConfig);
|
|
82
105
|
/**
|
|
83
106
|
* Returns a valid access token, fetching or refreshing as needed.
|
|
@@ -103,6 +126,11 @@ declare class AuthManager {
|
|
|
103
126
|
handleCallback(code: string, codeVerifier: string): Promise<void>;
|
|
104
127
|
/** Clears all stored tokens. */
|
|
105
128
|
clearTokens(): void;
|
|
129
|
+
/**
|
|
130
|
+
* Resolves `tokenUrl` and `authorizationUrl`, fetching the OIDC discovery document
|
|
131
|
+
* if either URL is absent from the config. Result is cached after the first call.
|
|
132
|
+
*/
|
|
133
|
+
private resolveEndpoints;
|
|
106
134
|
private refresh;
|
|
107
135
|
}
|
|
108
136
|
|
|
@@ -288,7 +316,10 @@ interface CodesUpdateParams {
|
|
|
288
316
|
}
|
|
289
317
|
declare class CoreApiClient {
|
|
290
318
|
private readonly client;
|
|
291
|
-
|
|
319
|
+
private readonly baseUrl;
|
|
320
|
+
constructor(auth: AuthManager, options?: {
|
|
321
|
+
baseUrl?: string;
|
|
322
|
+
});
|
|
292
323
|
/** abp-retrieve */
|
|
293
324
|
abpRetrieve(params: AbpRetrieveParams): Promise<AbpResponseDto>;
|
|
294
325
|
/** indices-retrieve */
|
|
@@ -362,7 +393,10 @@ interface ReportUsageParams {
|
|
|
362
393
|
}
|
|
363
394
|
declare class ResidentialRebuildClient {
|
|
364
395
|
private readonly client;
|
|
365
|
-
|
|
396
|
+
private readonly baseUrl;
|
|
397
|
+
constructor(auth: AuthManager, options?: {
|
|
398
|
+
baseUrl?: string;
|
|
399
|
+
});
|
|
366
400
|
/** rbls-calculate */
|
|
367
401
|
calculate(params: CalculateParams): Promise<CalculationResponse>;
|
|
368
402
|
/** rbls-report-use */
|
|
@@ -590,7 +624,10 @@ interface GetBuildUpParams {
|
|
|
590
624
|
}
|
|
591
625
|
declare class ScheduleOfRatesClient {
|
|
592
626
|
private readonly client;
|
|
593
|
-
|
|
627
|
+
private readonly baseUrl;
|
|
628
|
+
constructor(auth: AuthManager, options?: {
|
|
629
|
+
baseUrl?: string;
|
|
630
|
+
});
|
|
594
631
|
/** Lists books and editions available to user */
|
|
595
632
|
getBooksEdition(): Promise<EditionsDto>;
|
|
596
633
|
/** Lists matching rates */
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var
|
|
1
|
+
'use strict';var u=class{constructor(){this.token=null;}store(e){let n=e.expires_in!=null?Date.now()+e.expires_in*1e3:null;this.token={accessToken:e.access_token,expiresAt:n,refreshToken:e.refresh_token??null};}getAccessToken(){return this.token?.accessToken??null}getRefreshToken(){return this.token?.refreshToken??null}isExpired(e=30){return this.token?this.token.expiresAt===null?false:Date.now()>=this.token.expiresAt-e*1e3:true}clear(){this.token=null;}};async function m(t){let e=new URLSearchParams({grant_type:"client_credentials",client_id:t.clientId,client_secret:t.clientSecret});t.scopes&&t.scopes.length>0&&e.set("scope",t.scopes.join(" "));let n=t.tokenUrl;if(!n)throw new Error("tokenUrl is required for client credentials flow");let r=await fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e.toString()});if(!r.ok){let o=await r.text().catch(()=>"");throw new Error(`Token request failed: ${r.status} ${r.statusText}${o?` \u2014 ${o}`:""}`)}return r.json()}function A(){let t=new Uint8Array(32);return crypto.getRandomValues(t),k(t)}async function x(t){let n=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",n);return k(new Uint8Array(r))}function k(t){let e=String.fromCharCode(...t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function y(t,e){let n=A(),r=await x(n),o=new URLSearchParams({response_type:"code",client_id:t.clientId,redirect_uri:t.redirectUri,code_challenge:r,code_challenge_method:"S256"});t.scopes&&t.scopes.length>0&&o.set("scope",t.scopes.join(" ")),e&&o.set("state",e);let i=t.authorizationUrl;if(!i)throw new Error("authorizationUrl is required for authorization-code flow");return {url:`${i}?${o.toString()}`,codeVerifier:n}}async function w(t,e,n){let r=new URLSearchParams({grant_type:"authorization_code",client_id:t.clientId,redirect_uri:t.redirectUri,code:e,code_verifier:n}),o=t.tokenUrl;if(!o)throw new Error("tokenUrl is required for authorization-code flow");return U(o,r)}async function R(t,e){let n=new URLSearchParams({grant_type:"refresh_token",client_id:t.clientId,refresh_token:e}),r=t.tokenUrl;if(!r)throw new Error("tokenUrl is required for authorization-code flow");return U(r,n)}async function U(t,e){let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e.toString()});if(!n.ok){let r=await n.text().catch(()=>"");throw new Error(`Token request failed: ${n.status} ${n.statusText}${r?` \u2014 ${r}`:""}`)}return n.json()}var T="https://id.bcis.co.uk/.well-known/openid-configuration",C=new Map;async function b(t=T){let e=C.get(t);if(e)return e;let n=await fetch(t);if(!n.ok)throw new Error(`OIDC discovery failed: ${n.status} ${n.statusText} (${t})`);let r=await n.json();if(!r.token_endpoint||!r.authorization_endpoint)throw new Error(`OIDC discovery document at ${t} is missing required endpoints`);return C.set(t,r),r}var d=class{constructor(e){this.config=e;this.store=new u;this.inflight=null;this.endpoints=null;}async getAccessToken(){if(!this.store.isExpired())return this.store.getAccessToken();if(this.inflight)return await this.inflight,this.store.getAccessToken();this.inflight=this.refresh();try{await this.inflight;}finally{this.inflight=null;}let e=this.store.getAccessToken();if(!e)throw new Error("Failed to obtain access token");return e}async getAuthorizationUrl(e){if(this.config.flow!=="authorization-code")throw new Error("getAuthorizationUrl is only available for authorization-code flow");let n=await this.resolveEndpoints();return y({...this.config,...n},e)}async handleCallback(e,n){if(this.config.flow!=="authorization-code")throw new Error("handleCallback is only available for authorization-code flow");let r=await this.resolveEndpoints(),o=await w({...this.config,...r},e,n);this.store.store(o);}clearTokens(){this.store.clear();}async resolveEndpoints(){if(this.endpoints)return this.endpoints;let e=this.config;if(!e.tokenUrl||this.config.flow==="authorization-code"&&!e.authorizationUrl){let r=await b(e.discoveryUrl);this.endpoints={tokenUrl:e.tokenUrl??r.token_endpoint,authorizationUrl:e.authorizationUrl??r.authorization_endpoint};}else this.endpoints={tokenUrl:e.tokenUrl,authorizationUrl:e.authorizationUrl??""};return this.endpoints}async refresh(){let e=await this.resolveEndpoints();if(this.config.flow==="client-credentials"){let r=await m({...this.config,tokenUrl:e.tokenUrl});this.store.store(r);return}let n=this.store.getRefreshToken();if(n){let r=await R({...this.config,...e},n);this.store.store(r);return}throw new Error("No valid token available. Call getAuthorizationUrl() and handleCallback() first.")}};var p=class extends Error{constructor(n,r,o){super(`BCIS API error ${n} ${r}`);this.status=n;this.statusText=r;this.body=o;this.name="BcisApiError";}},s=class{constructor(e){this.auth=e;}async get(e,n,r={}){let o=await this.auth.getAccessToken(),i=new URL(e+n);for(let[c,l]of Object.entries(r))if(l!=null)if(Array.isArray(l))for(let P of l)i.searchParams.append(c,String(P));else i.searchParams.set(c,String(l));let a=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"}});if(!a.ok){let c;try{c=await a.json();}catch{c=await a.text();}throw new p(a.status,a.statusText,c)}return a.json()}};var h=class{constructor(e,n){this.client=new s(e),this.baseUrl=n?.baseUrl??"https://api.bcis.co.uk/core-apis";}async abpRetrieve(e){return this.client.get(this.baseUrl,"/abp-retrieve",e)}async indicesRetrieve(e){return this.client.get(this.baseUrl,"/indices-retrieve",e)}async tpsRetrieve(e){return this.client.get(this.baseUrl,"/tps-retrieve",e)}async codesUpdate(e){return this.client.get(this.baseUrl,"/codes-update",e)}};var g=class{constructor(e,n){this.client=new s(e),this.baseUrl=n?.baseUrl??"https://api.bcis.co.uk/residential-rebuild-calculator";}async calculate(e){return this.client.get(this.baseUrl,"/rbls-calculate",e)}async reportUsage(e){return this.client.get(this.baseUrl,"/rbls-report-use",e)}};var f=class{constructor(e,n){this.client=new s(e),this.baseUrl=n?.baseUrl??"https://api.bcis.co.uk/schedule-of-rates";}async getBooksEdition(){return this.client.get(this.baseUrl,"/get-books-edition",{})}async getRates(e){return this.client.get(this.baseUrl,"/get-rates",e)}async getResources(e){return this.client.get(this.baseUrl,"/get-resources",e)}async getBuildUp(e){return this.client.get(this.baseUrl,"/get-build-up",e)}};
|
|
2
2
|
exports.AuthManager=d;exports.BcisApiError=p;exports.CoreApiClient=h;exports.ResidentialRebuildClient=g;exports.ScheduleOfRatesClient=f;//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/auth/token-store.ts","../src/auth/client-credentials.ts","../src/auth/authorization-code.ts","../src/auth/auth-manager.ts","../src/http/fetch-client.ts","../src/clients/core-api.ts","../src/clients/residential-rebuild.ts","../src/clients/schedule-of-rates.ts"],"names":["TokenStore","response","expiresAt","bufferSeconds","fetchClientCredentialsToken","config","body","text","generateCodeVerifier","array","base64UrlEncode","generateCodeChallenge","verifier","data","digest","bytes","str","getAuthorizationUrl","state","codeVerifier","codeChallenge","params","exchangeCode","code","tokenRequest","refreshAccessToken","refreshToken","tokenUrl","AuthManager","token","tokenResponse","BcisApiError","status","statusText","FetchClient","auth","baseUrl","path","url","key","value","item","CoreApiClient","ResidentialRebuildClient","ScheduleOfRatesClient"],"mappings":"aAGO,IAAMA,CAAAA,CAAN,KAAiB,CAAjB,WAAA,EAAA,CACL,IAAA,CAAQ,MAA4B,KAAA,CAEpC,KAAA,CAAMC,CAAAA,CAA+B,CACnC,IAAMC,CAAAA,CACJD,EAAS,UAAA,EAAc,IAAA,CACnB,IAAA,CAAK,GAAA,EAAI,CAAIA,CAAAA,CAAS,UAAA,CAAa,GAAA,CACnC,IAAA,CAEN,IAAA,CAAK,KAAA,CAAQ,CACX,WAAA,CAAaA,CAAAA,CAAS,aACtB,SAAA,CAAAC,CAAAA,CACA,YAAA,CAAcD,CAAAA,CAAS,aAAA,EAAiB,IAC1C,EACF,CAEA,cAAA,EAAgC,CAC9B,OAAO,IAAA,CAAK,KAAA,EAAO,WAAA,EAAe,IACpC,CAEA,eAAA,EAAiC,CAC/B,OAAO,IAAA,CAAK,KAAA,EAAO,YAAA,EAAgB,IACrC,CAMA,SAAA,CAAUE,CAAAA,CAAgB,EAAA,CAAa,CACrC,OAAK,KAAK,KAAA,CACN,IAAA,CAAK,KAAA,CAAM,SAAA,GAAc,IAAA,CAAa,KAAA,CACnC,KAAK,GAAA,EAAI,EAAK,IAAA,CAAK,KAAA,CAAM,SAAA,CAAYA,CAAAA,CAAgB,IAFpC,IAG1B,CAEA,KAAA,EAAc,CACZ,IAAA,CAAK,KAAA,CAAQ,KACf,CACF,CAAA,CCnCA,eAAsBC,CAAAA,CACpBC,CAAAA,CACwB,CACxB,IAAMC,EAAO,IAAI,eAAA,CAAgB,CAC/B,UAAA,CAAY,oBAAA,CACZ,SAAA,CAAWD,CAAAA,CA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A,CAAsB,kCAAA,CAAoC,eAAA,CAAiBA,CAA4C,CAC5I,CACF,EC5BO,IAAMsB,CAAAA,CAAN,KAA+B,CAGpC,WAAA,CAAYR,CAAAA,CAAmB,CAC7B,IAAA,CAAK,MAAA,CAAS,IAAID,CAAAA,CAAYC,CAAI,EACpC,CAGA,MAAM,SAAA,CAAUd,CAAAA,CAAuD,CACrE,OAAO,IAAA,CAAK,MAAA,CAAO,GAAA,CAAyB,uDAAA,CAAyD,iBAAA,CAAmBA,CAA4C,CACtK,CAGA,MAAM,WAAA,CAAYA,CAAAA,CAAmD,CACnE,OAAO,IAAA,CAAK,OAAO,GAAA,CAAmB,uDAAA,CAAyD,kBAAA,CAAoBA,CAA4C,CACjK,CACF,EC/BO,IAAMuB,CAAAA,CAAN,KAA4B,CAGjC,WAAA,CAAYT,CAAAA,CAAmB,CAC7B,KAAK,MAAA,CAAS,IAAID,CAAAA,CAAYC,CAAI,EACpC,CAGA,MAAM,eAAA,EAAwC,CAC5C,OAAO,IAAA,CAAK,MAAA,CAAO,GAAA,CAAiB,0CAAA,CAA4C,qBAAsB,EAAE,CAC1G,CAGA,MAAM,QAAA,CAASd,CAAAA,CAAqD,CAClE,OAAO,IAAA,CAAK,MAAA,CAAO,GAAA,CAAwB,0CAAA,CAA4C,YAAA,CAAcA,CAA4C,CACnJ,CAGA,MAAM,YAAA,CAAaA,CAAAA,CAA6D,CAC9E,OAAO,IAAA,CAAK,MAAA,CAAO,GAAA,CAA4B,0CAAA,CAA4C,gBAAA,CAAkBA,CAA4C,CAC3J,CAGA,MAAM,UAAA,CAAWA,CAAAA,CAA0D,CACzE,OAAO,IAAA,CAAK,MAAA,CAAO,GAAA,CAA2B,0CAAA,CAA4C,eAAA,CAAiBA,CAA4C,CACzJ,CACF","file":"index.js","sourcesContent":["import type { StoredToken, TokenResponse } from './types';\n\n/** In-memory token storage with expiry awareness. */\nexport class TokenStore {\n private token: StoredToken | null = null;\n\n store(response: TokenResponse): void {\n const expiresAt =\n response.expires_in != null\n ? Date.now() + response.expires_in * 1000\n : null;\n\n this.token = {\n accessToken: response.access_token,\n expiresAt,\n refreshToken: response.refresh_token ?? null,\n };\n }\n\n getAccessToken(): string | null {\n return this.token?.accessToken ?? null;\n }\n\n getRefreshToken(): string | null {\n return this.token?.refreshToken ?? null;\n }\n\n /**\n * Returns true if there is no token or the token is within `bufferSeconds`\n * of expiry. Defaults to a 30-second buffer to allow for clock skew.\n */\n isExpired(bufferSeconds = 30): boolean {\n if (!this.token) return true;\n if (this.token.expiresAt === null) return false;\n return Date.now() >= this.token.expiresAt - bufferSeconds * 1000;\n }\n\n clear(): void {\n this.token = null;\n }\n}\n","import type { ClientCredentialsConfig, TokenResponse } from './types';\n\n/**\n * Fetches a new access token using the OAuth2 Client Credentials flow.\n */\nexport async function fetchClientCredentialsToken(\n config: ClientCredentialsConfig\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: config.clientId,\n client_secret: config.clientSecret,\n });\n\n if (config.scopes && config.scopes.length > 0) {\n body.set('scope', config.scopes.join(' '));\n }\n\n const response = await fetch(config.tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","import type { AuthorizationCodeConfig, TokenResponse } from './types';\n\n// ---------------------------------------------------------------------------\n// PKCE helpers\n// ---------------------------------------------------------------------------\n\n/** Generates a cryptographically random PKCE code verifier (43-128 chars). */\nexport function generateCodeVerifier(): string {\n const array = new Uint8Array(32);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\n/** Derives a PKCE code challenge (S256) from a code verifier. */\nexport async function generateCodeChallenge(verifier: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const digest = await crypto.subtle.digest('SHA-256', data);\n return base64UrlEncode(new Uint8Array(digest));\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n const str = String.fromCharCode(...bytes);\n return btoa(str).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n// ---------------------------------------------------------------------------\n// Authorization Code flows\n// ---------------------------------------------------------------------------\n\n/**\n * Builds the authorization URL to redirect the user to.\n * Returns the URL and the code verifier (must be stored and passed to exchangeCode).\n */\nexport async function getAuthorizationUrl(\n config: AuthorizationCodeConfig,\n state?: string\n): Promise<{ url: string; codeVerifier: string }> {\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = await generateCodeChallenge(codeVerifier);\n\n const params = new URLSearchParams({\n response_type: 'code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code_challenge: codeChallenge,\n code_challenge_method: 'S256',\n });\n\n if (config.scopes && config.scopes.length > 0) {\n params.set('scope', config.scopes.join(' '));\n }\n\n if (state) {\n params.set('state', state);\n }\n\n return {\n url: `${config.authorizationUrl}?${params.toString()}`,\n codeVerifier,\n };\n}\n\n/**\n * Exchanges an authorization code for tokens.\n */\nexport async function exchangeCode(\n config: AuthorizationCodeConfig,\n code: string,\n codeVerifier: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code,\n code_verifier: codeVerifier,\n });\n\n return tokenRequest(config.tokenUrl, body);\n}\n\n/**\n * Refreshes an access token using a refresh token.\n */\nexport async function refreshAccessToken(\n config: AuthorizationCodeConfig,\n refreshToken: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: config.clientId,\n refresh_token: refreshToken,\n });\n\n return tokenRequest(config.tokenUrl, body);\n}\n\nasync function tokenRequest(\n tokenUrl: string,\n body: URLSearchParams\n): Promise<TokenResponse> {\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","import type { AuthConfig, AuthorizationCodeConfig } from './types';\nimport { TokenStore } from './token-store';\nimport { fetchClientCredentialsToken } from './client-credentials';\nimport {\n getAuthorizationUrl as buildAuthorizationUrl,\n exchangeCode,\n refreshAccessToken,\n} from './authorization-code';\n\n/**\n * Centralized OAuth2 authentication manager.\n *\n * Supports:\n * - Client Credentials flow (server-to-server, fully automatic)\n * - Authorization Code + PKCE flow (user-facing applications)\n *\n * @example Client Credentials\n * ```ts\n * const auth = new AuthManager({\n * flow: 'client-credentials',\n * clientId: 'my-id',\n * clientSecret: 'my-secret',\n * tokenUrl: 'https://auth.bcis.co.uk/oauth/token',\n * });\n * const token = await auth.getAccessToken();\n * ```\n *\n * @example Authorization Code\n * ```ts\n * const auth = new AuthManager({\n * flow: 'authorization-code',\n * clientId: 'my-id',\n * tokenUrl: 'https://auth.bcis.co.uk/oauth/token',\n * authorizationUrl: 'https://auth.bcis.co.uk/authorize',\n * redirectUri: 'https://myapp.com/callback',\n * scopes: ['openid', 'profile'],\n * });\n *\n * // Step 1: redirect user\n * const { url, codeVerifier } = await auth.getAuthorizationUrl();\n * // store codeVerifier in session, redirect user to url\n *\n * // Step 2: on callback\n * await auth.handleCallback(code, codeVerifier);\n *\n * // Step 3: use the SDK\n * const token = await auth.getAccessToken();\n * ```\n */\nexport class AuthManager {\n private readonly store = new TokenStore();\n /** Pending token fetch promise to prevent concurrent requests */\n private inflight: Promise<void> | null = null;\n\n constructor(private readonly config: AuthConfig) {}\n\n /**\n * Returns a valid access token, fetching or refreshing as needed.\n * For Client Credentials flow this is fully automatic.\n * For Authorization Code flow, `handleCallback` must have been called first.\n */\n async getAccessToken(): Promise<string> {\n if (!this.store.isExpired()) {\n return this.store.getAccessToken()!;\n }\n\n if (this.inflight) {\n await this.inflight;\n return this.store.getAccessToken()!;\n }\n\n this.inflight = this.refresh();\n try {\n await this.inflight;\n } finally {\n this.inflight = null;\n }\n\n const token = this.store.getAccessToken();\n if (!token) throw new Error('Failed to obtain access token');\n return token;\n }\n\n /**\n * Authorization Code flow only.\n * Builds and returns the authorization URL to redirect the user to.\n * The returned `codeVerifier` must be persisted (e.g. in session storage)\n * and passed to `handleCallback`.\n */\n async getAuthorizationUrl(state?: string): Promise<{ url: string; codeVerifier: string }> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('getAuthorizationUrl is only available for authorization-code flow');\n }\n return buildAuthorizationUrl(this.config, state);\n }\n\n /**\n * Authorization Code flow only.\n * Exchanges the authorization code (from the redirect callback) for tokens\n * and stores them internally.\n */\n async handleCallback(code: string, codeVerifier: string): Promise<void> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('handleCallback is only available for authorization-code flow');\n }\n const tokenResponse = await exchangeCode(this.config, code, codeVerifier);\n this.store.store(tokenResponse);\n }\n\n /** Clears all stored tokens. */\n clearTokens(): void {\n this.store.clear();\n }\n\n private async refresh(): Promise<void> {\n if (this.config.flow === 'client-credentials') {\n const tokenResponse = await fetchClientCredentialsToken(this.config);\n this.store.store(tokenResponse);\n return;\n }\n\n // Authorization Code flow: try refresh token first, else throw\n const refreshToken = this.store.getRefreshToken();\n if (refreshToken) {\n const tokenResponse = await refreshAccessToken(\n this.config as AuthorizationCodeConfig,\n refreshToken\n );\n this.store.store(tokenResponse);\n return;\n }\n\n throw new Error(\n 'No valid token available. Call getAuthorizationUrl() and handleCallback() first.'\n );\n }\n}\n","import type { AuthManager } from '../auth/auth-manager';\n\n/** Thrown when an API response is not 2xx. */\nexport class BcisApiError extends Error {\n constructor(\n public readonly status: number,\n public readonly statusText: string,\n public readonly body: unknown\n ) {\n super(`BCIS API error ${status} ${statusText}`);\n this.name = 'BcisApiError';\n }\n}\n\n/**\n * Thin fetch wrapper that:\n * - Injects the Authorization: Bearer header from AuthManager\n * - Serialises query parameters (including arrays as repeated params)\n * - Throws BcisApiError on non-2xx responses\n */\nexport class FetchClient {\n constructor(private readonly auth: AuthManager) {}\n\n async get<T>(\n baseUrl: string,\n path: string,\n params: Record<string, unknown> = {}\n ): Promise<T> {\n const token = await this.auth.getAccessToken();\n const url = new URL(baseUrl + path);\n\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) {\n url.searchParams.append(key, String(item));\n }\n } else {\n url.searchParams.set(key, String(value));\n }\n }\n\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n body = await response.text();\n }\n throw new BcisApiError(response.status, response.statusText, body);\n }\n\n return response.json() as Promise<T>;\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { AbpResponseDto, IndicesResponseDto, TpsResponseDto, CodesResponseDto } from '../types/core-api.types';\n\n// --- Parameter interfaces ---\n\nexport interface AbpRetrieveParams {\n /** When true, returns additional data for graph plotting. Default false. */\n 'include-data-for-graph'?: boolean;\n /** When true, includes sub-divided categories (e.g., size bands) in results. Default false. */\n 'include-subclasses'?: boolean;\n /** A comma-separated list of building function codes used to filter study results. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'building-function': string[];\n /** A list of type of work codes to filter the results by, the example contains all valid codes. */\n 'type-of-work': string[];\n /** A six-character code identifying the BCIS study */\n 'abp-study': 'ABPBUI' | 'ABPFUN' | 'ABPGRP' | 'ABPEM2' | 'ABPEUR' | 'ABPEXT';\n}\n\nexport interface IndicesRetrieveParams {\n /** Restricts the index series by year e.g. `1985` or description `1985 mean = 100`. Ignored if a series number is provided. Descriptions must match text exactly, case-insensitive but including spaces. */\n 'base-of-series'?: string;\n /** Restricts index series by `regularity` (`monthly`, `quarterly`, `annual`). Ignored if a series number is used. Defaults to `quarterly`, then `monthly`, then `annual`. */\n regularity?: string[];\n /** Restricts index figures up to a specific month `yyyy-mm`, or leave blank for latest available. */\n 'end-date'?: string;\n /** Restricts index figures to a specific month `yyyy-mm`, or leave blank for earliest available. */\n 'start-date'?: string;\n /** Comma-delimited list of short names (e.g. `BCISTPI:AllIn`) or series numbers. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'series-identification': string[];\n}\n\nexport interface TpsRetrieveParams {\n /** Supports suffixes to filter or refine the study data: - Level Filters: - `:region`, `:county`, `:district` - Example: `location2000:region` (regional indices), `location2000:county,district` (county and district indices) - Postcode Filter: - `:postcode:<POSTCODE>` (no spaces) - Example: `location2000:postcode:SW1P3AD` - Cannot be combined with level filters. - Effective Date Filter: - `:EffectiveDate:<YYYYQn>` - Example: `location2000:EffectiveDate:2015Q2` - Can be combined with postcode or level filters. - Outcode List: - `:outcode` - Example: `location2000:outcode` - Not supported for 1980 boundaries or with EffectiveDate. `short-tps-name` is not case sensitive. For available studies, use the `codesUpdate` web service with `codeType=shortTPSName`. */\n 'short-tps-name': string;\n}\n\nexport interface CodesUpdateParams {\n /** A date in `yyyy-mm-dd` format. Returns only codes added or modified since this date. Not supported for all code types. Leave blank to return all codes. */\n 'if-changed-since'?: string;\n /** A version string to select relevant code tables. */\n version?: string;\n /** A string to select the code list required. The supported values are: - `seriesIdentification`: All regularity names (for `/indices-retrieve`) - `shortTPSName`: Tender Price Studies - short names (for `/tps-retrieve`) - `ABPStudy`: Average building prices study codes (for `/abp-retrieve`) - `BuildingFunction`: List of building function codes (for `/abp-retrieve`, and `/analyses-search`) - `BuildingFunction:Categories`: List of building function categories - `BuildingFunction:[1-9]`: List of building function codes for the category specified after the colon - `BuildingFunction:Duration`: List of building function codes for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:Categories`: List of building function categories for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:[1-9]`: List of building function codes for duration calculator for category specified after the colon (for `Duration Model Calculate Api`) - `BuildingFunction:ABP`: List of building function codes for average building prices study where results are available to the user (for `/abp-retrieve`) - `SimplifiedTypeOfWork`: List of shorter type of work codes (for `/abp-retrieve`) The list of supported code types may be extended in the future. */\n 'code-type': 'shortTPSName' | 'ABPStudy' | 'BuildingFunction' | 'BuildingFunction:Categories' | 'BuildingFunction:[1-9]' | 'BuildingFunction:Duration' | 'BuildingFunction:Duration:Categories' | 'BuildingFunction:Duration:[1-9]' | 'BuildingFunction:ABP' | 'SimplifiedTypeOfWork';\n}\n\n// --- Client ---\n\nexport class CoreApiClient {\n private readonly client: FetchClient;\n\n constructor(auth: AuthManager) {\n this.client = new FetchClient(auth);\n }\n\n /** abp-retrieve */\n async abpRetrieve(params: AbpRetrieveParams): Promise<AbpResponseDto> {\n return this.client.get<AbpResponseDto>('https://api.bcis.co.uk/core-apis', '/abp-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** indices-retrieve */\n async indicesRetrieve(params: IndicesRetrieveParams): Promise<IndicesResponseDto> {\n return this.client.get<IndicesResponseDto>('https://api.bcis.co.uk/core-apis', '/indices-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** tps-retrieve */\n async tpsRetrieve(params: TpsRetrieveParams): Promise<TpsResponseDto> {\n return this.client.get<TpsResponseDto>('https://api.bcis.co.uk/core-apis', '/tps-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** codes-update */\n async codesUpdate(params: CodesUpdateParams): Promise<CodesResponseDto> {\n return this.client.get<CodesResponseDto>('https://api.bcis.co.uk/core-apis', '/codes-update', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { CalculationResponse, UsageResponse } from '../types/residential-rebuild.types';\n\n// --- Parameter interfaces ---\n\nexport interface CalculateParams {\n /** Postcode of the property */\n postCode: string;\n /** Type of the property */\n type: string;\n /** Number of storeys in the property */\n storeys: string;\n /** Style of the property: detached, terraced, etc */\n style: string;\n /** Type of the walls of the property */\n wallType: string;\n /** Type of the roof of the property */\n roofType?: string;\n /** Year the property was built */\n yearBuilt: number;\n /** Number of flats */\n noOfFlats?: number;\n /** Area of the property in sq.m. */\n area?: number;\n /** Number of rooms in the property */\n noOfRooms?: number;\n /** Number of bedrooms in the property */\n noOfBedrooms?: number;\n /** Number of garage spaces in the property */\n noOfGarageSpaces?: number;\n /** Number of bathrooms in the property */\n noOfBathrooms?: number;\n /** Special features of the property, Must be blank, or a comma delimited list containing one or more of 'cellar' or 'noexternals' */\n specialFeatures?: string;\n}\n\nexport interface ReportUsageParams {\n /** First month of the usage report */\n startMonth?: string;\n /** Last month of the usage report */\n endMonth?: string;\n}\n\n// --- Client ---\n\nexport class ResidentialRebuildClient {\n private readonly client: FetchClient;\n\n constructor(auth: AuthManager) {\n this.client = new FetchClient(auth);\n }\n\n /** rbls-calculate */\n async calculate(params: CalculateParams): Promise<CalculationResponse> {\n return this.client.get<CalculationResponse>('https://api.bcis.co.uk/residential-rebuild-calculator', '/rbls-calculate', params as unknown as Record<string, unknown>);\n }\n\n /** rbls-report-use */\n async reportUsage(params: ReportUsageParams): Promise<UsageResponse> {\n return this.client.get<UsageResponse>('https://api.bcis.co.uk/residential-rebuild-calculator', '/rbls-report-use', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { EditionsDto, GetRateResponseDto, GetResourceResponseDto, GetBuildUpResponseDto } from '../types/schedule-of-rates.types';\n\n// --- Parameter interfaces ---\n\nexport interface GetRatesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetResourcesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetBuildUpParams {\n /** Id as returned from GetRates or GetResources */\n 'entity-id': string;\n}\n\n// --- Client ---\n\nexport class ScheduleOfRatesClient {\n private readonly client: FetchClient;\n\n constructor(auth: AuthManager) {\n this.client = new FetchClient(auth);\n }\n\n /** Lists books and editions available to user */\n async getBooksEdition(): Promise<EditionsDto> {\n return this.client.get<EditionsDto>('https://api.bcis.co.uk/schedule-of-rates', '/get-books-edition', {});\n }\n\n /** Lists matching rates */\n async getRates(params: GetRatesParams): Promise<GetRateResponseDto> {\n return this.client.get<GetRateResponseDto>('https://api.bcis.co.uk/schedule-of-rates', '/get-rates', params as unknown as Record<string, unknown>);\n }\n\n /** Lists matching resources */\n async getResources(params: GetResourcesParams): Promise<GetResourceResponseDto> {\n return this.client.get<GetResourceResponseDto>('https://api.bcis.co.uk/schedule-of-rates', '/get-resources', params as unknown as Record<string, unknown>);\n }\n\n /** Lists components of a rate or buildUp */\n async getBuildUp(params: GetBuildUpParams): Promise<GetBuildUpResponseDto> {\n return this.client.get<GetBuildUpResponseDto>('https://api.bcis.co.uk/schedule-of-rates', '/get-build-up', params as unknown as Record<string, unknown>);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/auth/token-store.ts","../src/auth/client-credentials.ts","../src/auth/authorization-code.ts","../src/auth/oidc-discovery.ts","../src/auth/auth-manager.ts","../src/http/fetch-client.ts","../src/clients/core-api.ts","../src/clients/residential-rebuild.ts","../src/clients/schedule-of-rates.ts"],"names":["TokenStore","response","expiresAt","bufferSeconds","fetchClientCredentialsToken","config","body","tokenUrl","text","generateCodeVerifier","array","base64UrlEncode","generateCodeChallenge","verifier","data","digest","bytes","str","getAuthorizationUrl","state","codeVerifier","codeChallenge","params","authUrl","exchangeCode","code","tokenRequest","refreshAccessToken","refreshToken","BCIS_DISCOVERY_URL","cache","fetchOidcConfig","discoveryUrl","cached","AuthManager","token","endpoints","tokenResponse","cfg","oidc","BcisApiError","status","statusText","FetchClient","auth","baseUrl","path","url","key","value","item","CoreApiClient","options","ResidentialRebuildClient","ScheduleOfRatesClient"],"mappings":"aAGO,IAAMA,CAAAA,CAAN,KAAiB,CAAjB,WAAA,EAAA,CACL,KAAQ,KAAA,CAA4B,KAAA,CAEpC,KAAA,CAAMC,CAAAA,CAA+B,CACnC,IAAMC,CAAAA,CACJD,CAAAA,CAAS,YAAc,IAAA,CACnB,IAAA,CAAK,GAAA,EAAI,CAAIA,CAAAA,CAAS,UAAA,CAAa,GAAA,CACnC,IAAA,CAEN,KAAK,KAAA,CAAQ,CACX,WAAA,CAAaA,CAAAA,CAAS,aACtB,SAAA,CAAAC,CAAAA,CACA,YAAA,CAAcD,CAAAA,CAAS,eAAiB,IAC1C,EACF,CAEA,cAAA,EAAgC,CAC9B,OAAO,IAAA,CAAK,KAAA,EAAO,aAAe,IACpC,CAEA,eAAA,EAAiC,CAC/B,OAAO,IAAA,CAAK,KAAA,EAAO,YAAA,EAAgB,IACrC,CAMA,SAAA,CAAUE,CAAAA,CAAgB,EAAA,CAAa,CACrC,OAAK,IAAA,CAAK,KAAA,CACN,KAAK,KAAA,CAAM,SAAA,GAAc,IAAA,CAAa,KAAA,CACnC,KAAK,GAAA,EAAI,EAAK,IAAA,CAAK,KAAA,CAAM,UAAYA,CAAAA,CAAgB,GAAA,CAFpC,IAG1B,CAEA,KAAA,EAAc,CACZ,IAAA,CAAK,KAAA,CAAQ,KACf,CACF,CAAA,CCnCA,eAAsBC,CAAAA,CACpBC,CAAAA,CACwB,CACxB,IAAMC,CAAAA,CAAO,IAAI,eAAA,CAAgB,CAC/B,UAAA,CAAY,oBAAA,CACZ,SAAA,CAAWD,CAAAA,CAAO,QAAA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,CAAK,MAAA,CAAO,GAAA,CAAyB,IAAA,CAAK,QAAS,iBAAA,CAAmBA,CAA4C,CAC3H,CAGA,MAAM,WAAA,CAAYA,CAAAA,CAAmD,CACnE,OAAO,IAAA,CAAK,MAAA,CAAO,GAAA,CAAmB,IAAA,CAAK,QAAS,kBAAA,CAAoBA,CAA4C,CACtH,CACF,ECjCO,IAAMgC,CAAAA,CAAN,KAA4B,CAIjC,WAAA,CAAYV,CAAAA,CAAmBQ,CAAAA,CAAgC,CAC7D,KAAK,MAAA,CAAS,IAAIT,CAAAA,CAAYC,CAAI,CAAA,CAClC,IAAA,CAAK,OAAA,CAAUQ,CAAAA,EAAS,SAAW,2CACrC,CAGA,MAAM,eAAA,EAAwC,CAC5C,OAAO,IAAA,CAAK,MAAA,CAAO,IAAiB,IAAA,CAAK,OAAA,CAAS,oBAAA,CAAsB,EAAE,CAC5E,CAGA,MAAM,QAAA,CAAS9B,EAAqD,CAClE,OAAO,IAAA,CAAK,MAAA,CAAO,GAAA,CAAwB,IAAA,CAAK,OAAA,CAAS,YAAA,CAAcA,CAA4C,CACrH,CAGA,MAAM,YAAA,CAAaA,EAA6D,CAC9E,OAAO,IAAA,CAAK,MAAA,CAAO,IAA4B,IAAA,CAAK,OAAA,CAAS,gBAAA,CAAkBA,CAA4C,CAC7H,CAGA,MAAM,UAAA,CAAWA,EAA0D,CACzE,OAAO,IAAA,CAAK,MAAA,CAAO,IAA2B,IAAA,CAAK,OAAA,CAAS,eAAA,CAAiBA,CAA4C,CAC3H,CACF","file":"index.js","sourcesContent":["import type { StoredToken, TokenResponse } from './types';\n\n/** In-memory token storage with expiry awareness. */\nexport class TokenStore {\n private token: StoredToken | null = null;\n\n store(response: TokenResponse): void {\n const expiresAt =\n response.expires_in != null\n ? Date.now() + response.expires_in * 1000\n : null;\n\n this.token = {\n accessToken: response.access_token,\n expiresAt,\n refreshToken: response.refresh_token ?? null,\n };\n }\n\n getAccessToken(): string | null {\n return this.token?.accessToken ?? null;\n }\n\n getRefreshToken(): string | null {\n return this.token?.refreshToken ?? null;\n }\n\n /**\n * Returns true if there is no token or the token is within `bufferSeconds`\n * of expiry. Defaults to a 30-second buffer to allow for clock skew.\n */\n isExpired(bufferSeconds = 30): boolean {\n if (!this.token) return true;\n if (this.token.expiresAt === null) return false;\n return Date.now() >= this.token.expiresAt - bufferSeconds * 1000;\n }\n\n clear(): void {\n this.token = null;\n }\n}\n","import type { ClientCredentialsConfig, TokenResponse } from './types';\n\n/**\n * Fetches a new access token using the OAuth2 Client Credentials flow.\n */\nexport async function fetchClientCredentialsToken(\n config: ClientCredentialsConfig\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: config.clientId,\n client_secret: config.clientSecret,\n });\n\n if (config.scopes && config.scopes.length > 0) {\n body.set('scope', config.scopes.join(' '));\n }\n\n const tokenUrl = config.tokenUrl;\n if (!tokenUrl) throw new Error('tokenUrl is required for client credentials flow');\n\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","import type { AuthorizationCodeConfig, TokenResponse } from './types';\n\n// ---------------------------------------------------------------------------\n// PKCE helpers\n// ---------------------------------------------------------------------------\n\n/** Generates a cryptographically random PKCE code verifier (43-128 chars). */\nexport function generateCodeVerifier(): string {\n const array = new Uint8Array(32);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\n/** Derives a PKCE code challenge (S256) from a code verifier. */\nexport async function generateCodeChallenge(verifier: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const digest = await crypto.subtle.digest('SHA-256', data);\n return base64UrlEncode(new Uint8Array(digest));\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n const str = String.fromCharCode(...bytes);\n return btoa(str).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n// ---------------------------------------------------------------------------\n// Authorization Code flows\n// ---------------------------------------------------------------------------\n\n/**\n * Builds the authorization URL to redirect the user to.\n * Returns the URL and the code verifier (must be stored and passed to exchangeCode).\n */\nexport async function getAuthorizationUrl(\n config: AuthorizationCodeConfig,\n state?: string\n): Promise<{ url: string; codeVerifier: string }> {\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = await generateCodeChallenge(codeVerifier);\n\n const params = new URLSearchParams({\n response_type: 'code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code_challenge: codeChallenge,\n code_challenge_method: 'S256',\n });\n\n if (config.scopes && config.scopes.length > 0) {\n params.set('scope', config.scopes.join(' '));\n }\n\n if (state) {\n params.set('state', state);\n }\n\n const authUrl = config.authorizationUrl;\n if (!authUrl) throw new Error('authorizationUrl is required for authorization-code flow');\n\n return {\n url: `${authUrl}?${params.toString()}`,\n codeVerifier,\n };\n}\n\n/**\n * Exchanges an authorization code for tokens.\n */\nexport async function exchangeCode(\n config: AuthorizationCodeConfig,\n code: string,\n codeVerifier: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code,\n code_verifier: codeVerifier,\n });\n\n const tokenUrl = config.tokenUrl;\n if (!tokenUrl) throw new Error('tokenUrl is required for authorization-code flow');\n return tokenRequest(tokenUrl, body);\n}\n\n/**\n * Refreshes an access token using a refresh token.\n */\nexport async function refreshAccessToken(\n config: AuthorizationCodeConfig,\n refreshToken: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: config.clientId,\n refresh_token: refreshToken,\n });\n\n const tokenUrl = config.tokenUrl;\n if (!tokenUrl) throw new Error('tokenUrl is required for authorization-code flow');\n return tokenRequest(tokenUrl, body);\n}\n\nasync function tokenRequest(\n tokenUrl: string,\n body: URLSearchParams\n): Promise<TokenResponse> {\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","const BCIS_DISCOVERY_URL = 'https://id.bcis.co.uk/.well-known/openid-configuration';\n\nexport interface OidcConfig {\n token_endpoint: string;\n authorization_endpoint: string;\n [key: string]: unknown;\n}\n\n/** Module-level cache keyed by discovery URL */\nconst cache = new Map<string, OidcConfig>();\n\n/**\n * Fetches and caches the OpenID Connect discovery document.\n * Defaults to the BCIS identity provider.\n */\nexport async function fetchOidcConfig(discoveryUrl = BCIS_DISCOVERY_URL): Promise<OidcConfig> {\n const cached = cache.get(discoveryUrl);\n if (cached) return cached;\n\n const response = await fetch(discoveryUrl);\n if (!response.ok) {\n throw new Error(\n `OIDC discovery failed: ${response.status} ${response.statusText} (${discoveryUrl})`\n );\n }\n\n const config = (await response.json()) as OidcConfig;\n\n if (!config.token_endpoint || !config.authorization_endpoint) {\n throw new Error(`OIDC discovery document at ${discoveryUrl} is missing required endpoints`);\n }\n\n cache.set(discoveryUrl, config);\n return config;\n}\n","import type { AuthConfig, AuthorizationCodeConfig, ClientCredentialsConfig } from './types';\nimport { TokenStore } from './token-store';\nimport { fetchClientCredentialsToken } from './client-credentials';\nimport {\n getAuthorizationUrl as buildAuthorizationUrl,\n exchangeCode,\n refreshAccessToken,\n} from './authorization-code';\nimport { fetchOidcConfig } from './oidc-discovery';\n\n/**\n * Centralized OAuth2 authentication manager.\n *\n * Supports:\n * - Client Credentials flow (server-to-server, fully automatic)\n * - Authorization Code + PKCE flow (user-facing applications)\n *\n * Endpoint URLs (`tokenUrl`, `authorizationUrl`) are optional — when omitted they are\n * resolved automatically from the BCIS OpenID Connect discovery document at\n * `https://id.bcis.co.uk/.well-known/openid-configuration`.\n *\n * @example Client Credentials (auto-discovered endpoints)\n * ```ts\n * const auth = new AuthManager({\n * flow: 'client-credentials',\n * clientId: 'my-id',\n * clientSecret: 'my-secret',\n * });\n * const token = await auth.getAccessToken();\n * ```\n *\n * @example Authorization Code (auto-discovered endpoints)\n * ```ts\n * const auth = new AuthManager({\n * flow: 'authorization-code',\n * clientId: 'my-id',\n * redirectUri: 'https://myapp.com/callback',\n * scopes: ['openid', 'profile'],\n * });\n *\n * // Step 1: redirect user\n * const { url, codeVerifier } = await auth.getAuthorizationUrl();\n * // store codeVerifier in session, redirect user to url\n *\n * // Step 2: on callback\n * await auth.handleCallback(code, codeVerifier);\n *\n * // Step 3: use the SDK\n * const token = await auth.getAccessToken();\n * ```\n */\nexport class AuthManager {\n private readonly store = new TokenStore();\n /** Pending token fetch promise to prevent concurrent requests */\n private inflight: Promise<void> | null = null;\n /** Cached resolved endpoints (populated lazily from OIDC discovery) */\n private endpoints: { tokenUrl: string; authorizationUrl: string } | null = null;\n\n constructor(private readonly config: AuthConfig) {}\n\n /**\n * Returns a valid access token, fetching or refreshing as needed.\n * For Client Credentials flow this is fully automatic.\n * For Authorization Code flow, `handleCallback` must have been called first.\n */\n async getAccessToken(): Promise<string> {\n if (!this.store.isExpired()) {\n return this.store.getAccessToken()!;\n }\n\n if (this.inflight) {\n await this.inflight;\n return this.store.getAccessToken()!;\n }\n\n this.inflight = this.refresh();\n try {\n await this.inflight;\n } finally {\n this.inflight = null;\n }\n\n const token = this.store.getAccessToken();\n if (!token) throw new Error('Failed to obtain access token');\n return token;\n }\n\n /**\n * Authorization Code flow only.\n * Builds and returns the authorization URL to redirect the user to.\n * The returned `codeVerifier` must be persisted (e.g. in session storage)\n * and passed to `handleCallback`.\n */\n async getAuthorizationUrl(state?: string): Promise<{ url: string; codeVerifier: string }> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('getAuthorizationUrl is only available for authorization-code flow');\n }\n const endpoints = await this.resolveEndpoints();\n return buildAuthorizationUrl(\n { ...(this.config as AuthorizationCodeConfig), ...endpoints },\n state\n );\n }\n\n /**\n * Authorization Code flow only.\n * Exchanges the authorization code (from the redirect callback) for tokens\n * and stores them internally.\n */\n async handleCallback(code: string, codeVerifier: string): Promise<void> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('handleCallback is only available for authorization-code flow');\n }\n const endpoints = await this.resolveEndpoints();\n const tokenResponse = await exchangeCode(\n { ...(this.config as AuthorizationCodeConfig), ...endpoints },\n code,\n codeVerifier\n );\n this.store.store(tokenResponse);\n }\n\n /** Clears all stored tokens. */\n clearTokens(): void {\n this.store.clear();\n }\n\n /**\n * Resolves `tokenUrl` and `authorizationUrl`, fetching the OIDC discovery document\n * if either URL is absent from the config. Result is cached after the first call.\n */\n private async resolveEndpoints(): Promise<{ tokenUrl: string; authorizationUrl: string }> {\n if (this.endpoints) return this.endpoints;\n\n const cfg = this.config as {\n tokenUrl?: string;\n authorizationUrl?: string;\n discoveryUrl?: string;\n };\n\n const needsDiscovery =\n !cfg.tokenUrl ||\n (this.config.flow === 'authorization-code' && !cfg.authorizationUrl);\n\n if (needsDiscovery) {\n const oidc = await fetchOidcConfig(cfg.discoveryUrl);\n this.endpoints = {\n tokenUrl: cfg.tokenUrl ?? oidc.token_endpoint,\n authorizationUrl: cfg.authorizationUrl ?? oidc.authorization_endpoint,\n };\n } else {\n this.endpoints = {\n tokenUrl: cfg.tokenUrl!,\n authorizationUrl: cfg.authorizationUrl ?? '',\n };\n }\n\n return this.endpoints;\n }\n\n private async refresh(): Promise<void> {\n const endpoints = await this.resolveEndpoints();\n\n if (this.config.flow === 'client-credentials') {\n const tokenResponse = await fetchClientCredentialsToken({\n ...(this.config as ClientCredentialsConfig),\n tokenUrl: endpoints.tokenUrl,\n });\n this.store.store(tokenResponse);\n return;\n }\n\n // Authorization Code flow: try refresh token first, else throw\n const refreshToken = this.store.getRefreshToken();\n if (refreshToken) {\n const tokenResponse = await refreshAccessToken(\n { ...(this.config as AuthorizationCodeConfig), ...endpoints },\n refreshToken\n );\n this.store.store(tokenResponse);\n return;\n }\n\n throw new Error(\n 'No valid token available. Call getAuthorizationUrl() and handleCallback() first.'\n );\n }\n}\n","import type { AuthManager } from '../auth/auth-manager';\n\n/** Thrown when an API response is not 2xx. */\nexport class BcisApiError extends Error {\n constructor(\n public readonly status: number,\n public readonly statusText: string,\n public readonly body: unknown\n ) {\n super(`BCIS API error ${status} ${statusText}`);\n this.name = 'BcisApiError';\n }\n}\n\n/**\n * Thin fetch wrapper that:\n * - Injects the Authorization: Bearer header from AuthManager\n * - Serialises query parameters (including arrays as repeated params)\n * - Throws BcisApiError on non-2xx responses\n */\nexport class FetchClient {\n constructor(private readonly auth: AuthManager) {}\n\n async get<T>(\n baseUrl: string,\n path: string,\n params: Record<string, unknown> = {}\n ): Promise<T> {\n const token = await this.auth.getAccessToken();\n const url = new URL(baseUrl + path);\n\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) {\n url.searchParams.append(key, String(item));\n }\n } else {\n url.searchParams.set(key, String(value));\n }\n }\n\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n body = await response.text();\n }\n throw new BcisApiError(response.status, response.statusText, body);\n }\n\n return response.json() as Promise<T>;\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { AbpResponseDto, IndicesResponseDto, TpsResponseDto, CodesResponseDto } from '../types/core-api.types';\n\n// --- Parameter interfaces ---\n\nexport interface AbpRetrieveParams {\n /** When true, returns additional data for graph plotting. Default false. */\n 'include-data-for-graph'?: boolean;\n /** When true, includes sub-divided categories (e.g., size bands) in results. Default false. */\n 'include-subclasses'?: boolean;\n /** A comma-separated list of building function codes used to filter study results. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'building-function': string[];\n /** A list of type of work codes to filter the results by, the example contains all valid codes. */\n 'type-of-work': string[];\n /** A six-character code identifying the BCIS study */\n 'abp-study': 'ABPBUI' | 'ABPFUN' | 'ABPGRP' | 'ABPEM2' | 'ABPEUR' | 'ABPEXT';\n}\n\nexport interface IndicesRetrieveParams {\n /** Restricts the index series by year e.g. `1985` or description `1985 mean = 100`. Ignored if a series number is provided. Descriptions must match text exactly, case-insensitive but including spaces. */\n 'base-of-series'?: string;\n /** Restricts index series by `regularity` (`monthly`, `quarterly`, `annual`). Ignored if a series number is used. Defaults to `quarterly`, then `monthly`, then `annual`. */\n regularity?: string[];\n /** Restricts index figures up to a specific month `yyyy-mm`, or leave blank for latest available. */\n 'end-date'?: string;\n /** Restricts index figures to a specific month `yyyy-mm`, or leave blank for earliest available. */\n 'start-date'?: string;\n /** Comma-delimited list of short names (e.g. `BCISTPI:AllIn`) or series numbers. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'series-identification': string[];\n}\n\nexport interface TpsRetrieveParams {\n /** Supports suffixes to filter or refine the study data: - Level Filters: - `:region`, `:county`, `:district` - Example: `location2000:region` (regional indices), `location2000:county,district` (county and district indices) - Postcode Filter: - `:postcode:<POSTCODE>` (no spaces) - Example: `location2000:postcode:SW1P3AD` - Cannot be combined with level filters. - Effective Date Filter: - `:EffectiveDate:<YYYYQn>` - Example: `location2000:EffectiveDate:2015Q2` - Can be combined with postcode or level filters. - Outcode List: - `:outcode` - Example: `location2000:outcode` - Not supported for 1980 boundaries or with EffectiveDate. `short-tps-name` is not case sensitive. For available studies, use the `codesUpdate` web service with `codeType=shortTPSName`. */\n 'short-tps-name': string;\n}\n\nexport interface CodesUpdateParams {\n /** A date in `yyyy-mm-dd` format. Returns only codes added or modified since this date. Not supported for all code types. Leave blank to return all codes. */\n 'if-changed-since'?: string;\n /** A version string to select relevant code tables. */\n version?: string;\n /** A string to select the code list required. The supported values are: - `seriesIdentification`: All regularity names (for `/indices-retrieve`) - `shortTPSName`: Tender Price Studies - short names (for `/tps-retrieve`) - `ABPStudy`: Average building prices study codes (for `/abp-retrieve`) - `BuildingFunction`: List of building function codes (for `/abp-retrieve`, and `/analyses-search`) - `BuildingFunction:Categories`: List of building function categories - `BuildingFunction:[1-9]`: List of building function codes for the category specified after the colon - `BuildingFunction:Duration`: List of building function codes for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:Categories`: List of building function categories for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:[1-9]`: List of building function codes for duration calculator for category specified after the colon (for `Duration Model Calculate Api`) - `BuildingFunction:ABP`: List of building function codes for average building prices study where results are available to the user (for `/abp-retrieve`) - `SimplifiedTypeOfWork`: List of shorter type of work codes (for `/abp-retrieve`) The list of supported code types may be extended in the future. */\n 'code-type': 'shortTPSName' | 'ABPStudy' | 'BuildingFunction' | 'BuildingFunction:Categories' | 'BuildingFunction:[1-9]' | 'BuildingFunction:Duration' | 'BuildingFunction:Duration:Categories' | 'BuildingFunction:Duration:[1-9]' | 'BuildingFunction:ABP' | 'SimplifiedTypeOfWork';\n}\n\n// --- Client ---\n\nexport class CoreApiClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/core-apis';\n }\n\n /** abp-retrieve */\n async abpRetrieve(params: AbpRetrieveParams): Promise<AbpResponseDto> {\n return this.client.get<AbpResponseDto>(this.baseUrl, '/abp-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** indices-retrieve */\n async indicesRetrieve(params: IndicesRetrieveParams): Promise<IndicesResponseDto> {\n return this.client.get<IndicesResponseDto>(this.baseUrl, '/indices-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** tps-retrieve */\n async tpsRetrieve(params: TpsRetrieveParams): Promise<TpsResponseDto> {\n return this.client.get<TpsResponseDto>(this.baseUrl, '/tps-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** codes-update */\n async codesUpdate(params: CodesUpdateParams): Promise<CodesResponseDto> {\n return this.client.get<CodesResponseDto>(this.baseUrl, '/codes-update', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { CalculationResponse, UsageResponse } from '../types/residential-rebuild.types';\n\n// --- Parameter interfaces ---\n\nexport interface CalculateParams {\n /** Postcode of the property */\n postCode: string;\n /** Type of the property */\n type: string;\n /** Number of storeys in the property */\n storeys: string;\n /** Style of the property: detached, terraced, etc */\n style: string;\n /** Type of the walls of the property */\n wallType: string;\n /** Type of the roof of the property */\n roofType?: string;\n /** Year the property was built */\n yearBuilt: number;\n /** Number of flats */\n noOfFlats?: number;\n /** Area of the property in sq.m. */\n area?: number;\n /** Number of rooms in the property */\n noOfRooms?: number;\n /** Number of bedrooms in the property */\n noOfBedrooms?: number;\n /** Number of garage spaces in the property */\n noOfGarageSpaces?: number;\n /** Number of bathrooms in the property */\n noOfBathrooms?: number;\n /** Special features of the property, Must be blank, or a comma delimited list containing one or more of 'cellar' or 'noexternals' */\n specialFeatures?: string;\n}\n\nexport interface ReportUsageParams {\n /** First month of the usage report */\n startMonth?: string;\n /** Last month of the usage report */\n endMonth?: string;\n}\n\n// --- Client ---\n\nexport class ResidentialRebuildClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/residential-rebuild-calculator';\n }\n\n /** rbls-calculate */\n async calculate(params: CalculateParams): Promise<CalculationResponse> {\n return this.client.get<CalculationResponse>(this.baseUrl, '/rbls-calculate', params as unknown as Record<string, unknown>);\n }\n\n /** rbls-report-use */\n async reportUsage(params: ReportUsageParams): Promise<UsageResponse> {\n return this.client.get<UsageResponse>(this.baseUrl, '/rbls-report-use', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { EditionsDto, GetRateResponseDto, GetResourceResponseDto, GetBuildUpResponseDto } from '../types/schedule-of-rates.types';\n\n// --- Parameter interfaces ---\n\nexport interface GetRatesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetResourcesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetBuildUpParams {\n /** Id as returned from GetRates or GetResources */\n 'entity-id': string;\n}\n\n// --- Client ---\n\nexport class ScheduleOfRatesClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/schedule-of-rates';\n }\n\n /** Lists books and editions available to user */\n async getBooksEdition(): Promise<EditionsDto> {\n return this.client.get<EditionsDto>(this.baseUrl, '/get-books-edition', {});\n }\n\n /** Lists matching rates */\n async getRates(params: GetRatesParams): Promise<GetRateResponseDto> {\n return this.client.get<GetRateResponseDto>(this.baseUrl, '/get-rates', params as unknown as Record<string, unknown>);\n }\n\n /** Lists matching resources */\n async getResources(params: GetResourcesParams): Promise<GetResourceResponseDto> {\n return this.client.get<GetResourceResponseDto>(this.baseUrl, '/get-resources', params as unknown as Record<string, unknown>);\n }\n\n /** Lists components of a rate or buildUp */\n async getBuildUp(params: GetBuildUpParams): Promise<GetBuildUpResponseDto> {\n return this.client.get<GetBuildUpResponseDto>(this.baseUrl, '/get-build-up', params as unknown as Record<string, unknown>);\n }\n}\n"]}
|
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
1
|
+
var u=class{constructor(){this.token=null;}store(e){let n=e.expires_in!=null?Date.now()+e.expires_in*1e3:null;this.token={accessToken:e.access_token,expiresAt:n,refreshToken:e.refresh_token??null};}getAccessToken(){return this.token?.accessToken??null}getRefreshToken(){return this.token?.refreshToken??null}isExpired(e=30){return this.token?this.token.expiresAt===null?false:Date.now()>=this.token.expiresAt-e*1e3:true}clear(){this.token=null;}};async function m(t){let e=new URLSearchParams({grant_type:"client_credentials",client_id:t.clientId,client_secret:t.clientSecret});t.scopes&&t.scopes.length>0&&e.set("scope",t.scopes.join(" "));let n=t.tokenUrl;if(!n)throw new Error("tokenUrl is required for client credentials flow");let r=await fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e.toString()});if(!r.ok){let o=await r.text().catch(()=>"");throw new Error(`Token request failed: ${r.status} ${r.statusText}${o?` \u2014 ${o}`:""}`)}return r.json()}function A(){let t=new Uint8Array(32);return crypto.getRandomValues(t),k(t)}async function x(t){let n=new TextEncoder().encode(t),r=await crypto.subtle.digest("SHA-256",n);return k(new Uint8Array(r))}function k(t){let e=String.fromCharCode(...t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function y(t,e){let n=A(),r=await x(n),o=new URLSearchParams({response_type:"code",client_id:t.clientId,redirect_uri:t.redirectUri,code_challenge:r,code_challenge_method:"S256"});t.scopes&&t.scopes.length>0&&o.set("scope",t.scopes.join(" ")),e&&o.set("state",e);let i=t.authorizationUrl;if(!i)throw new Error("authorizationUrl is required for authorization-code flow");return {url:`${i}?${o.toString()}`,codeVerifier:n}}async function w(t,e,n){let r=new URLSearchParams({grant_type:"authorization_code",client_id:t.clientId,redirect_uri:t.redirectUri,code:e,code_verifier:n}),o=t.tokenUrl;if(!o)throw new Error("tokenUrl is required for authorization-code flow");return U(o,r)}async function R(t,e){let n=new URLSearchParams({grant_type:"refresh_token",client_id:t.clientId,refresh_token:e}),r=t.tokenUrl;if(!r)throw new Error("tokenUrl is required for authorization-code flow");return U(r,n)}async function U(t,e){let n=await fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e.toString()});if(!n.ok){let r=await n.text().catch(()=>"");throw new Error(`Token request failed: ${n.status} ${n.statusText}${r?` \u2014 ${r}`:""}`)}return n.json()}var T="https://id.bcis.co.uk/.well-known/openid-configuration",C=new Map;async function b(t=T){let e=C.get(t);if(e)return e;let n=await fetch(t);if(!n.ok)throw new Error(`OIDC discovery failed: ${n.status} ${n.statusText} (${t})`);let r=await n.json();if(!r.token_endpoint||!r.authorization_endpoint)throw new Error(`OIDC discovery document at ${t} is missing required endpoints`);return C.set(t,r),r}var d=class{constructor(e){this.config=e;this.store=new u;this.inflight=null;this.endpoints=null;}async getAccessToken(){if(!this.store.isExpired())return this.store.getAccessToken();if(this.inflight)return await this.inflight,this.store.getAccessToken();this.inflight=this.refresh();try{await this.inflight;}finally{this.inflight=null;}let e=this.store.getAccessToken();if(!e)throw new Error("Failed to obtain access token");return e}async getAuthorizationUrl(e){if(this.config.flow!=="authorization-code")throw new Error("getAuthorizationUrl is only available for authorization-code flow");let n=await this.resolveEndpoints();return y({...this.config,...n},e)}async handleCallback(e,n){if(this.config.flow!=="authorization-code")throw new Error("handleCallback is only available for authorization-code flow");let r=await this.resolveEndpoints(),o=await w({...this.config,...r},e,n);this.store.store(o);}clearTokens(){this.store.clear();}async resolveEndpoints(){if(this.endpoints)return this.endpoints;let e=this.config;if(!e.tokenUrl||this.config.flow==="authorization-code"&&!e.authorizationUrl){let r=await b(e.discoveryUrl);this.endpoints={tokenUrl:e.tokenUrl??r.token_endpoint,authorizationUrl:e.authorizationUrl??r.authorization_endpoint};}else this.endpoints={tokenUrl:e.tokenUrl,authorizationUrl:e.authorizationUrl??""};return this.endpoints}async refresh(){let e=await this.resolveEndpoints();if(this.config.flow==="client-credentials"){let r=await m({...this.config,tokenUrl:e.tokenUrl});this.store.store(r);return}let n=this.store.getRefreshToken();if(n){let r=await R({...this.config,...e},n);this.store.store(r);return}throw new Error("No valid token available. Call getAuthorizationUrl() and handleCallback() first.")}};var p=class extends Error{constructor(n,r,o){super(`BCIS API error ${n} ${r}`);this.status=n;this.statusText=r;this.body=o;this.name="BcisApiError";}},s=class{constructor(e){this.auth=e;}async get(e,n,r={}){let o=await this.auth.getAccessToken(),i=new URL(e+n);for(let[c,l]of Object.entries(r))if(l!=null)if(Array.isArray(l))for(let P of l)i.searchParams.append(c,String(P));else i.searchParams.set(c,String(l));let a=await fetch(i.toString(),{method:"GET",headers:{Authorization:`Bearer ${o}`,Accept:"application/json"}});if(!a.ok){let c;try{c=await a.json();}catch{c=await a.text();}throw new p(a.status,a.statusText,c)}return a.json()}};var h=class{constructor(e,n){this.client=new s(e),this.baseUrl=n?.baseUrl??"https://api.bcis.co.uk/core-apis";}async abpRetrieve(e){return this.client.get(this.baseUrl,"/abp-retrieve",e)}async indicesRetrieve(e){return this.client.get(this.baseUrl,"/indices-retrieve",e)}async tpsRetrieve(e){return this.client.get(this.baseUrl,"/tps-retrieve",e)}async codesUpdate(e){return this.client.get(this.baseUrl,"/codes-update",e)}};var g=class{constructor(e,n){this.client=new s(e),this.baseUrl=n?.baseUrl??"https://api.bcis.co.uk/residential-rebuild-calculator";}async calculate(e){return this.client.get(this.baseUrl,"/rbls-calculate",e)}async reportUsage(e){return this.client.get(this.baseUrl,"/rbls-report-use",e)}};var f=class{constructor(e,n){this.client=new s(e),this.baseUrl=n?.baseUrl??"https://api.bcis.co.uk/schedule-of-rates";}async getBooksEdition(){return this.client.get(this.baseUrl,"/get-books-edition",{})}async getRates(e){return this.client.get(this.baseUrl,"/get-rates",e)}async getResources(e){return this.client.get(this.baseUrl,"/get-resources",e)}async getBuildUp(e){return this.client.get(this.baseUrl,"/get-build-up",e)}};
|
|
2
2
|
export{d as AuthManager,p as BcisApiError,h as CoreApiClient,g as ResidentialRebuildClient,f as ScheduleOfRatesClient};//# sourceMappingURL=index.mjs.map
|
|
3
3
|
//# sourceMappingURL=index.mjs.map
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/auth/token-store.ts","../src/auth/client-credentials.ts","../src/auth/authorization-code.ts","../src/auth/auth-manager.ts","../src/http/fetch-client.ts","../src/clients/core-api.ts","../src/clients/residential-rebuild.ts","../src/clients/schedule-of-rates.ts"],"names":["TokenStore","response","expiresAt","bufferSeconds","fetchClientCredentialsToken","config","body","text","generateCodeVerifier","array","base64UrlEncode","generateCodeChallenge","verifier","data","digest","bytes","str","getAuthorizationUrl","state","codeVerifier","codeChallenge","params","exchangeCode","code","tokenRequest","refreshAccessToken","refreshToken","tokenUrl","AuthManager","token","tokenResponse","BcisApiError","status","statusText","FetchClient","auth","baseUrl","path","url","key","value","item","CoreApiClient","ResidentialRebuildClient","ScheduleOfRatesClient"],"mappings":"AAGO,IAAMA,CAAAA,CAAN,KAAiB,CAAjB,WAAA,EAAA,CACL,IAAA,CAAQ,MAA4B,KAAA,CAEpC,KAAA,CAAMC,CAAAA,CAA+B,CACnC,IAAMC,CAAAA,CACJD,EAAS,UAAA,EAAc,IAAA,CACnB,IAAA,CAAK,GAAA,EAAI,CAAIA,CAAAA,CAAS,UAAA,CAAa,GAAA,CACnC,IAAA,CAEN,IAAA,CAAK,KAAA,CAAQ,CACX,WAAA,CAAaA,CAAAA,CAAS,aACtB,SAAA,CAAAC,CAAAA,CACA,YAAA,CAAcD,CAAAA,CAAS,aAAA,EAAiB,IAC1C,EACF,CAEA,cAAA,EAAgC,CAC9B,OAAO,IAAA,CAAK,KAAA,EAAO,WAAA,EAAe,IACpC,CAEA,eAAA,EAAi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,IAAA,CAAK,MAAA,CAAO,GAAA,CAAwB,0CAAA,CAA4C,YAAA,CAAcA,CAA4C,CACnJ,CAGA,MAAM,YAAA,CAAaA,CAAAA,CAA6D,CAC9E,OAAO,IAAA,CAAK,MAAA,CAAO,GAAA,CAA4B,0CAAA,CAA4C,gBAAA,CAAkBA,CAA4C,CAC3J,CAGA,MAAM,UAAA,CAAWA,CAAAA,CAA0D,CACzE,OAAO,IAAA,CAAK,MAAA,CAAO,GAAA,CAA2B,0CAAA,CAA4C,eAAA,CAAiBA,CAA4C,CACzJ,CACF","file":"index.mjs","sourcesContent":["import type { StoredToken, TokenResponse } from './types';\n\n/** In-memory token storage with expiry awareness. */\nexport class TokenStore {\n private token: StoredToken | null = null;\n\n store(response: TokenResponse): void {\n const expiresAt =\n response.expires_in != null\n ? Date.now() + response.expires_in * 1000\n : null;\n\n this.token = {\n accessToken: response.access_token,\n expiresAt,\n refreshToken: response.refresh_token ?? null,\n };\n }\n\n getAccessToken(): string | null {\n return this.token?.accessToken ?? null;\n }\n\n getRefreshToken(): string | null {\n return this.token?.refreshToken ?? null;\n }\n\n /**\n * Returns true if there is no token or the token is within `bufferSeconds`\n * of expiry. Defaults to a 30-second buffer to allow for clock skew.\n */\n isExpired(bufferSeconds = 30): boolean {\n if (!this.token) return true;\n if (this.token.expiresAt === null) return false;\n return Date.now() >= this.token.expiresAt - bufferSeconds * 1000;\n }\n\n clear(): void {\n this.token = null;\n }\n}\n","import type { ClientCredentialsConfig, TokenResponse } from './types';\n\n/**\n * Fetches a new access token using the OAuth2 Client Credentials flow.\n */\nexport async function fetchClientCredentialsToken(\n config: ClientCredentialsConfig\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: config.clientId,\n client_secret: config.clientSecret,\n });\n\n if (config.scopes && config.scopes.length > 0) {\n body.set('scope', config.scopes.join(' '));\n }\n\n const response = await fetch(config.tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","import type { AuthorizationCodeConfig, TokenResponse } from './types';\n\n// ---------------------------------------------------------------------------\n// PKCE helpers\n// ---------------------------------------------------------------------------\n\n/** Generates a cryptographically random PKCE code verifier (43-128 chars). */\nexport function generateCodeVerifier(): string {\n const array = new Uint8Array(32);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\n/** Derives a PKCE code challenge (S256) from a code verifier. */\nexport async function generateCodeChallenge(verifier: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const digest = await crypto.subtle.digest('SHA-256', data);\n return base64UrlEncode(new Uint8Array(digest));\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n const str = String.fromCharCode(...bytes);\n return btoa(str).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n// ---------------------------------------------------------------------------\n// Authorization Code flows\n// ---------------------------------------------------------------------------\n\n/**\n * Builds the authorization URL to redirect the user to.\n * Returns the URL and the code verifier (must be stored and passed to exchangeCode).\n */\nexport async function getAuthorizationUrl(\n config: AuthorizationCodeConfig,\n state?: string\n): Promise<{ url: string; codeVerifier: string }> {\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = await generateCodeChallenge(codeVerifier);\n\n const params = new URLSearchParams({\n response_type: 'code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code_challenge: codeChallenge,\n code_challenge_method: 'S256',\n });\n\n if (config.scopes && config.scopes.length > 0) {\n params.set('scope', config.scopes.join(' '));\n }\n\n if (state) {\n params.set('state', state);\n }\n\n return {\n url: `${config.authorizationUrl}?${params.toString()}`,\n codeVerifier,\n };\n}\n\n/**\n * Exchanges an authorization code for tokens.\n */\nexport async function exchangeCode(\n config: AuthorizationCodeConfig,\n code: string,\n codeVerifier: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code,\n code_verifier: codeVerifier,\n });\n\n return tokenRequest(config.tokenUrl, body);\n}\n\n/**\n * Refreshes an access token using a refresh token.\n */\nexport async function refreshAccessToken(\n config: AuthorizationCodeConfig,\n refreshToken: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: config.clientId,\n refresh_token: refreshToken,\n });\n\n return tokenRequest(config.tokenUrl, body);\n}\n\nasync function tokenRequest(\n tokenUrl: string,\n body: URLSearchParams\n): Promise<TokenResponse> {\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","import type { AuthConfig, AuthorizationCodeConfig } from './types';\nimport { TokenStore } from './token-store';\nimport { fetchClientCredentialsToken } from './client-credentials';\nimport {\n getAuthorizationUrl as buildAuthorizationUrl,\n exchangeCode,\n refreshAccessToken,\n} from './authorization-code';\n\n/**\n * Centralized OAuth2 authentication manager.\n *\n * Supports:\n * - Client Credentials flow (server-to-server, fully automatic)\n * - Authorization Code + PKCE flow (user-facing applications)\n *\n * @example Client Credentials\n * ```ts\n * const auth = new AuthManager({\n * flow: 'client-credentials',\n * clientId: 'my-id',\n * clientSecret: 'my-secret',\n * tokenUrl: 'https://auth.bcis.co.uk/oauth/token',\n * });\n * const token = await auth.getAccessToken();\n * ```\n *\n * @example Authorization Code\n * ```ts\n * const auth = new AuthManager({\n * flow: 'authorization-code',\n * clientId: 'my-id',\n * tokenUrl: 'https://auth.bcis.co.uk/oauth/token',\n * authorizationUrl: 'https://auth.bcis.co.uk/authorize',\n * redirectUri: 'https://myapp.com/callback',\n * scopes: ['openid', 'profile'],\n * });\n *\n * // Step 1: redirect user\n * const { url, codeVerifier } = await auth.getAuthorizationUrl();\n * // store codeVerifier in session, redirect user to url\n *\n * // Step 2: on callback\n * await auth.handleCallback(code, codeVerifier);\n *\n * // Step 3: use the SDK\n * const token = await auth.getAccessToken();\n * ```\n */\nexport class AuthManager {\n private readonly store = new TokenStore();\n /** Pending token fetch promise to prevent concurrent requests */\n private inflight: Promise<void> | null = null;\n\n constructor(private readonly config: AuthConfig) {}\n\n /**\n * Returns a valid access token, fetching or refreshing as needed.\n * For Client Credentials flow this is fully automatic.\n * For Authorization Code flow, `handleCallback` must have been called first.\n */\n async getAccessToken(): Promise<string> {\n if (!this.store.isExpired()) {\n return this.store.getAccessToken()!;\n }\n\n if (this.inflight) {\n await this.inflight;\n return this.store.getAccessToken()!;\n }\n\n this.inflight = this.refresh();\n try {\n await this.inflight;\n } finally {\n this.inflight = null;\n }\n\n const token = this.store.getAccessToken();\n if (!token) throw new Error('Failed to obtain access token');\n return token;\n }\n\n /**\n * Authorization Code flow only.\n * Builds and returns the authorization URL to redirect the user to.\n * The returned `codeVerifier` must be persisted (e.g. in session storage)\n * and passed to `handleCallback`.\n */\n async getAuthorizationUrl(state?: string): Promise<{ url: string; codeVerifier: string }> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('getAuthorizationUrl is only available for authorization-code flow');\n }\n return buildAuthorizationUrl(this.config, state);\n }\n\n /**\n * Authorization Code flow only.\n * Exchanges the authorization code (from the redirect callback) for tokens\n * and stores them internally.\n */\n async handleCallback(code: string, codeVerifier: string): Promise<void> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('handleCallback is only available for authorization-code flow');\n }\n const tokenResponse = await exchangeCode(this.config, code, codeVerifier);\n this.store.store(tokenResponse);\n }\n\n /** Clears all stored tokens. */\n clearTokens(): void {\n this.store.clear();\n }\n\n private async refresh(): Promise<void> {\n if (this.config.flow === 'client-credentials') {\n const tokenResponse = await fetchClientCredentialsToken(this.config);\n this.store.store(tokenResponse);\n return;\n }\n\n // Authorization Code flow: try refresh token first, else throw\n const refreshToken = this.store.getRefreshToken();\n if (refreshToken) {\n const tokenResponse = await refreshAccessToken(\n this.config as AuthorizationCodeConfig,\n refreshToken\n );\n this.store.store(tokenResponse);\n return;\n }\n\n throw new Error(\n 'No valid token available. Call getAuthorizationUrl() and handleCallback() first.'\n );\n }\n}\n","import type { AuthManager } from '../auth/auth-manager';\n\n/** Thrown when an API response is not 2xx. */\nexport class BcisApiError extends Error {\n constructor(\n public readonly status: number,\n public readonly statusText: string,\n public readonly body: unknown\n ) {\n super(`BCIS API error ${status} ${statusText}`);\n this.name = 'BcisApiError';\n }\n}\n\n/**\n * Thin fetch wrapper that:\n * - Injects the Authorization: Bearer header from AuthManager\n * - Serialises query parameters (including arrays as repeated params)\n * - Throws BcisApiError on non-2xx responses\n */\nexport class FetchClient {\n constructor(private readonly auth: AuthManager) {}\n\n async get<T>(\n baseUrl: string,\n path: string,\n params: Record<string, unknown> = {}\n ): Promise<T> {\n const token = await this.auth.getAccessToken();\n const url = new URL(baseUrl + path);\n\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) {\n url.searchParams.append(key, String(item));\n }\n } else {\n url.searchParams.set(key, String(value));\n }\n }\n\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n body = await response.text();\n }\n throw new BcisApiError(response.status, response.statusText, body);\n }\n\n return response.json() as Promise<T>;\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { AbpResponseDto, IndicesResponseDto, TpsResponseDto, CodesResponseDto } from '../types/core-api.types';\n\n// --- Parameter interfaces ---\n\nexport interface AbpRetrieveParams {\n /** When true, returns additional data for graph plotting. Default false. */\n 'include-data-for-graph'?: boolean;\n /** When true, includes sub-divided categories (e.g., size bands) in results. Default false. */\n 'include-subclasses'?: boolean;\n /** A comma-separated list of building function codes used to filter study results. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'building-function': string[];\n /** A list of type of work codes to filter the results by, the example contains all valid codes. */\n 'type-of-work': string[];\n /** A six-character code identifying the BCIS study */\n 'abp-study': 'ABPBUI' | 'ABPFUN' | 'ABPGRP' | 'ABPEM2' | 'ABPEUR' | 'ABPEXT';\n}\n\nexport interface IndicesRetrieveParams {\n /** Restricts the index series by year e.g. `1985` or description `1985 mean = 100`. Ignored if a series number is provided. Descriptions must match text exactly, case-insensitive but including spaces. */\n 'base-of-series'?: string;\n /** Restricts index series by `regularity` (`monthly`, `quarterly`, `annual`). Ignored if a series number is used. Defaults to `quarterly`, then `monthly`, then `annual`. */\n regularity?: string[];\n /** Restricts index figures up to a specific month `yyyy-mm`, or leave blank for latest available. */\n 'end-date'?: string;\n /** Restricts index figures to a specific month `yyyy-mm`, or leave blank for earliest available. */\n 'start-date'?: string;\n /** Comma-delimited list of short names (e.g. `BCISTPI:AllIn`) or series numbers. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'series-identification': string[];\n}\n\nexport interface TpsRetrieveParams {\n /** Supports suffixes to filter or refine the study data: - Level Filters: - `:region`, `:county`, `:district` - Example: `location2000:region` (regional indices), `location2000:county,district` (county and district indices) - Postcode Filter: - `:postcode:<POSTCODE>` (no spaces) - Example: `location2000:postcode:SW1P3AD` - Cannot be combined with level filters. - Effective Date Filter: - `:EffectiveDate:<YYYYQn>` - Example: `location2000:EffectiveDate:2015Q2` - Can be combined with postcode or level filters. - Outcode List: - `:outcode` - Example: `location2000:outcode` - Not supported for 1980 boundaries or with EffectiveDate. `short-tps-name` is not case sensitive. For available studies, use the `codesUpdate` web service with `codeType=shortTPSName`. */\n 'short-tps-name': string;\n}\n\nexport interface CodesUpdateParams {\n /** A date in `yyyy-mm-dd` format. Returns only codes added or modified since this date. Not supported for all code types. Leave blank to return all codes. */\n 'if-changed-since'?: string;\n /** A version string to select relevant code tables. */\n version?: string;\n /** A string to select the code list required. The supported values are: - `seriesIdentification`: All regularity names (for `/indices-retrieve`) - `shortTPSName`: Tender Price Studies - short names (for `/tps-retrieve`) - `ABPStudy`: Average building prices study codes (for `/abp-retrieve`) - `BuildingFunction`: List of building function codes (for `/abp-retrieve`, and `/analyses-search`) - `BuildingFunction:Categories`: List of building function categories - `BuildingFunction:[1-9]`: List of building function codes for the category specified after the colon - `BuildingFunction:Duration`: List of building function codes for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:Categories`: List of building function categories for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:[1-9]`: List of building function codes for duration calculator for category specified after the colon (for `Duration Model Calculate Api`) - `BuildingFunction:ABP`: List of building function codes for average building prices study where results are available to the user (for `/abp-retrieve`) - `SimplifiedTypeOfWork`: List of shorter type of work codes (for `/abp-retrieve`) The list of supported code types may be extended in the future. */\n 'code-type': 'shortTPSName' | 'ABPStudy' | 'BuildingFunction' | 'BuildingFunction:Categories' | 'BuildingFunction:[1-9]' | 'BuildingFunction:Duration' | 'BuildingFunction:Duration:Categories' | 'BuildingFunction:Duration:[1-9]' | 'BuildingFunction:ABP' | 'SimplifiedTypeOfWork';\n}\n\n// --- Client ---\n\nexport class CoreApiClient {\n private readonly client: FetchClient;\n\n constructor(auth: AuthManager) {\n this.client = new FetchClient(auth);\n }\n\n /** abp-retrieve */\n async abpRetrieve(params: AbpRetrieveParams): Promise<AbpResponseDto> {\n return this.client.get<AbpResponseDto>('https://api.bcis.co.uk/core-apis', '/abp-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** indices-retrieve */\n async indicesRetrieve(params: IndicesRetrieveParams): Promise<IndicesResponseDto> {\n return this.client.get<IndicesResponseDto>('https://api.bcis.co.uk/core-apis', '/indices-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** tps-retrieve */\n async tpsRetrieve(params: TpsRetrieveParams): Promise<TpsResponseDto> {\n return this.client.get<TpsResponseDto>('https://api.bcis.co.uk/core-apis', '/tps-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** codes-update */\n async codesUpdate(params: CodesUpdateParams): Promise<CodesResponseDto> {\n return this.client.get<CodesResponseDto>('https://api.bcis.co.uk/core-apis', '/codes-update', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { CalculationResponse, UsageResponse } from '../types/residential-rebuild.types';\n\n// --- Parameter interfaces ---\n\nexport interface CalculateParams {\n /** Postcode of the property */\n postCode: string;\n /** Type of the property */\n type: string;\n /** Number of storeys in the property */\n storeys: string;\n /** Style of the property: detached, terraced, etc */\n style: string;\n /** Type of the walls of the property */\n wallType: string;\n /** Type of the roof of the property */\n roofType?: string;\n /** Year the property was built */\n yearBuilt: number;\n /** Number of flats */\n noOfFlats?: number;\n /** Area of the property in sq.m. */\n area?: number;\n /** Number of rooms in the property */\n noOfRooms?: number;\n /** Number of bedrooms in the property */\n noOfBedrooms?: number;\n /** Number of garage spaces in the property */\n noOfGarageSpaces?: number;\n /** Number of bathrooms in the property */\n noOfBathrooms?: number;\n /** Special features of the property, Must be blank, or a comma delimited list containing one or more of 'cellar' or 'noexternals' */\n specialFeatures?: string;\n}\n\nexport interface ReportUsageParams {\n /** First month of the usage report */\n startMonth?: string;\n /** Last month of the usage report */\n endMonth?: string;\n}\n\n// --- Client ---\n\nexport class ResidentialRebuildClient {\n private readonly client: FetchClient;\n\n constructor(auth: AuthManager) {\n this.client = new FetchClient(auth);\n }\n\n /** rbls-calculate */\n async calculate(params: CalculateParams): Promise<CalculationResponse> {\n return this.client.get<CalculationResponse>('https://api.bcis.co.uk/residential-rebuild-calculator', '/rbls-calculate', params as unknown as Record<string, unknown>);\n }\n\n /** rbls-report-use */\n async reportUsage(params: ReportUsageParams): Promise<UsageResponse> {\n return this.client.get<UsageResponse>('https://api.bcis.co.uk/residential-rebuild-calculator', '/rbls-report-use', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { EditionsDto, GetRateResponseDto, GetResourceResponseDto, GetBuildUpResponseDto } from '../types/schedule-of-rates.types';\n\n// --- Parameter interfaces ---\n\nexport interface GetRatesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetResourcesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetBuildUpParams {\n /** Id as returned from GetRates or GetResources */\n 'entity-id': string;\n}\n\n// --- Client ---\n\nexport class ScheduleOfRatesClient {\n private readonly client: FetchClient;\n\n constructor(auth: AuthManager) {\n this.client = new FetchClient(auth);\n }\n\n /** Lists books and editions available to user */\n async getBooksEdition(): Promise<EditionsDto> {\n return this.client.get<EditionsDto>('https://api.bcis.co.uk/schedule-of-rates', '/get-books-edition', {});\n }\n\n /** Lists matching rates */\n async getRates(params: GetRatesParams): Promise<GetRateResponseDto> {\n return this.client.get<GetRateResponseDto>('https://api.bcis.co.uk/schedule-of-rates', '/get-rates', params as unknown as Record<string, unknown>);\n }\n\n /** Lists matching resources */\n async getResources(params: GetResourcesParams): Promise<GetResourceResponseDto> {\n return this.client.get<GetResourceResponseDto>('https://api.bcis.co.uk/schedule-of-rates', '/get-resources', params as unknown as Record<string, unknown>);\n }\n\n /** Lists components of a rate or buildUp */\n async getBuildUp(params: GetBuildUpParams): Promise<GetBuildUpResponseDto> {\n return this.client.get<GetBuildUpResponseDto>('https://api.bcis.co.uk/schedule-of-rates', '/get-build-up', params as unknown as Record<string, unknown>);\n }\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/auth/token-store.ts","../src/auth/client-credentials.ts","../src/auth/authorization-code.ts","../src/auth/oidc-discovery.ts","../src/auth/auth-manager.ts","../src/http/fetch-client.ts","../src/clients/core-api.ts","../src/clients/residential-rebuild.ts","../src/clients/schedule-of-rates.ts"],"names":["TokenStore","response","expiresAt","bufferSeconds","fetchClientCredentialsToken","config","body","tokenUrl","text","generateCodeVerifier","array","base64UrlEncode","generateCodeChallenge","verifier","data","digest","bytes","str","getAuthorizationUrl","state","codeVerifier","codeChallenge","params","authUrl","exchangeCode","code","tokenRequest","refreshAccessToken","refreshToken","BCIS_DISCOVERY_URL","cache","fetchOidcConfig","discoveryUrl","cached","AuthManager","token","endpoints","tokenResponse","cfg","oidc","BcisApiError","status","statusText","FetchClient","auth","baseUrl","path","url","key","value","item","CoreApiClient","options","ResidentialRebuildClient","ScheduleOfRatesClient"],"mappings":"AAGO,IAAMA,CAAAA,CAAN,KAAiB,CAAjB,WAAA,EAAA,CACL,KAAQ,KAAA,CAA4B,KAAA,CAEpC,KAAA,CAAMC,CAAAA,CAA+B,CACnC,IAAMC,CAAAA,CACJD,CAAAA,CAAS,YAAc,IAAA,CACnB,IAAA,CAAK,GAAA,EAAI,CAAIA,CAAAA,CAAS,UAAA,CAAa,GAAA,CACnC,IAAA,CAEN,KAAK,KAAA,CAAQ,CACX,WAAA,CAAaA,CAAAA,CAAS,aACtB,SAAA,CAAAC,CAAAA,CACA,YAAA,CAAcD,CAAAA,CAAS,eAAiB,IAC1C,EACF,CAEA,cAAA,EAAgC,CAC9B,OAAO,IAAA,CAAK,KAAA,EAAO,aAAe,IACpC,CAEA,eAAA,EAAiC,CAC/B,OAA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A,CAAO,IAA4B,IAAA,CAAK,OAAA,CAAS,gBAAA,CAAkBA,CAA4C,CAC7H,CAGA,MAAM,UAAA,CAAWA,EAA0D,CACzE,OAAO,IAAA,CAAK,MAAA,CAAO,IAA2B,IAAA,CAAK,OAAA,CAAS,eAAA,CAAiBA,CAA4C,CAC3H,CACF","file":"index.mjs","sourcesContent":["import type { StoredToken, TokenResponse } from './types';\n\n/** In-memory token storage with expiry awareness. */\nexport class TokenStore {\n private token: StoredToken | null = null;\n\n store(response: TokenResponse): void {\n const expiresAt =\n response.expires_in != null\n ? Date.now() + response.expires_in * 1000\n : null;\n\n this.token = {\n accessToken: response.access_token,\n expiresAt,\n refreshToken: response.refresh_token ?? null,\n };\n }\n\n getAccessToken(): string | null {\n return this.token?.accessToken ?? null;\n }\n\n getRefreshToken(): string | null {\n return this.token?.refreshToken ?? null;\n }\n\n /**\n * Returns true if there is no token or the token is within `bufferSeconds`\n * of expiry. Defaults to a 30-second buffer to allow for clock skew.\n */\n isExpired(bufferSeconds = 30): boolean {\n if (!this.token) return true;\n if (this.token.expiresAt === null) return false;\n return Date.now() >= this.token.expiresAt - bufferSeconds * 1000;\n }\n\n clear(): void {\n this.token = null;\n }\n}\n","import type { ClientCredentialsConfig, TokenResponse } from './types';\n\n/**\n * Fetches a new access token using the OAuth2 Client Credentials flow.\n */\nexport async function fetchClientCredentialsToken(\n config: ClientCredentialsConfig\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: config.clientId,\n client_secret: config.clientSecret,\n });\n\n if (config.scopes && config.scopes.length > 0) {\n body.set('scope', config.scopes.join(' '));\n }\n\n const tokenUrl = config.tokenUrl;\n if (!tokenUrl) throw new Error('tokenUrl is required for client credentials flow');\n\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","import type { AuthorizationCodeConfig, TokenResponse } from './types';\n\n// ---------------------------------------------------------------------------\n// PKCE helpers\n// ---------------------------------------------------------------------------\n\n/** Generates a cryptographically random PKCE code verifier (43-128 chars). */\nexport function generateCodeVerifier(): string {\n const array = new Uint8Array(32);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\n/** Derives a PKCE code challenge (S256) from a code verifier. */\nexport async function generateCodeChallenge(verifier: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const digest = await crypto.subtle.digest('SHA-256', data);\n return base64UrlEncode(new Uint8Array(digest));\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n const str = String.fromCharCode(...bytes);\n return btoa(str).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n// ---------------------------------------------------------------------------\n// Authorization Code flows\n// ---------------------------------------------------------------------------\n\n/**\n * Builds the authorization URL to redirect the user to.\n * Returns the URL and the code verifier (must be stored and passed to exchangeCode).\n */\nexport async function getAuthorizationUrl(\n config: AuthorizationCodeConfig,\n state?: string\n): Promise<{ url: string; codeVerifier: string }> {\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = await generateCodeChallenge(codeVerifier);\n\n const params = new URLSearchParams({\n response_type: 'code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code_challenge: codeChallenge,\n code_challenge_method: 'S256',\n });\n\n if (config.scopes && config.scopes.length > 0) {\n params.set('scope', config.scopes.join(' '));\n }\n\n if (state) {\n params.set('state', state);\n }\n\n const authUrl = config.authorizationUrl;\n if (!authUrl) throw new Error('authorizationUrl is required for authorization-code flow');\n\n return {\n url: `${authUrl}?${params.toString()}`,\n codeVerifier,\n };\n}\n\n/**\n * Exchanges an authorization code for tokens.\n */\nexport async function exchangeCode(\n config: AuthorizationCodeConfig,\n code: string,\n codeVerifier: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code,\n code_verifier: codeVerifier,\n });\n\n const tokenUrl = config.tokenUrl;\n if (!tokenUrl) throw new Error('tokenUrl is required for authorization-code flow');\n return tokenRequest(tokenUrl, body);\n}\n\n/**\n * Refreshes an access token using a refresh token.\n */\nexport async function refreshAccessToken(\n config: AuthorizationCodeConfig,\n refreshToken: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: config.clientId,\n refresh_token: refreshToken,\n });\n\n const tokenUrl = config.tokenUrl;\n if (!tokenUrl) throw new Error('tokenUrl is required for authorization-code flow');\n return tokenRequest(tokenUrl, body);\n}\n\nasync function tokenRequest(\n tokenUrl: string,\n body: URLSearchParams\n): Promise<TokenResponse> {\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","const BCIS_DISCOVERY_URL = 'https://id.bcis.co.uk/.well-known/openid-configuration';\n\nexport interface OidcConfig {\n token_endpoint: string;\n authorization_endpoint: string;\n [key: string]: unknown;\n}\n\n/** Module-level cache keyed by discovery URL */\nconst cache = new Map<string, OidcConfig>();\n\n/**\n * Fetches and caches the OpenID Connect discovery document.\n * Defaults to the BCIS identity provider.\n */\nexport async function fetchOidcConfig(discoveryUrl = BCIS_DISCOVERY_URL): Promise<OidcConfig> {\n const cached = cache.get(discoveryUrl);\n if (cached) return cached;\n\n const response = await fetch(discoveryUrl);\n if (!response.ok) {\n throw new Error(\n `OIDC discovery failed: ${response.status} ${response.statusText} (${discoveryUrl})`\n );\n }\n\n const config = (await response.json()) as OidcConfig;\n\n if (!config.token_endpoint || !config.authorization_endpoint) {\n throw new Error(`OIDC discovery document at ${discoveryUrl} is missing required endpoints`);\n }\n\n cache.set(discoveryUrl, config);\n return config;\n}\n","import type { AuthConfig, AuthorizationCodeConfig, ClientCredentialsConfig } from './types';\nimport { TokenStore } from './token-store';\nimport { fetchClientCredentialsToken } from './client-credentials';\nimport {\n getAuthorizationUrl as buildAuthorizationUrl,\n exchangeCode,\n refreshAccessToken,\n} from './authorization-code';\nimport { fetchOidcConfig } from './oidc-discovery';\n\n/**\n * Centralized OAuth2 authentication manager.\n *\n * Supports:\n * - Client Credentials flow (server-to-server, fully automatic)\n * - Authorization Code + PKCE flow (user-facing applications)\n *\n * Endpoint URLs (`tokenUrl`, `authorizationUrl`) are optional — when omitted they are\n * resolved automatically from the BCIS OpenID Connect discovery document at\n * `https://id.bcis.co.uk/.well-known/openid-configuration`.\n *\n * @example Client Credentials (auto-discovered endpoints)\n * ```ts\n * const auth = new AuthManager({\n * flow: 'client-credentials',\n * clientId: 'my-id',\n * clientSecret: 'my-secret',\n * });\n * const token = await auth.getAccessToken();\n * ```\n *\n * @example Authorization Code (auto-discovered endpoints)\n * ```ts\n * const auth = new AuthManager({\n * flow: 'authorization-code',\n * clientId: 'my-id',\n * redirectUri: 'https://myapp.com/callback',\n * scopes: ['openid', 'profile'],\n * });\n *\n * // Step 1: redirect user\n * const { url, codeVerifier } = await auth.getAuthorizationUrl();\n * // store codeVerifier in session, redirect user to url\n *\n * // Step 2: on callback\n * await auth.handleCallback(code, codeVerifier);\n *\n * // Step 3: use the SDK\n * const token = await auth.getAccessToken();\n * ```\n */\nexport class AuthManager {\n private readonly store = new TokenStore();\n /** Pending token fetch promise to prevent concurrent requests */\n private inflight: Promise<void> | null = null;\n /** Cached resolved endpoints (populated lazily from OIDC discovery) */\n private endpoints: { tokenUrl: string; authorizationUrl: string } | null = null;\n\n constructor(private readonly config: AuthConfig) {}\n\n /**\n * Returns a valid access token, fetching or refreshing as needed.\n * For Client Credentials flow this is fully automatic.\n * For Authorization Code flow, `handleCallback` must have been called first.\n */\n async getAccessToken(): Promise<string> {\n if (!this.store.isExpired()) {\n return this.store.getAccessToken()!;\n }\n\n if (this.inflight) {\n await this.inflight;\n return this.store.getAccessToken()!;\n }\n\n this.inflight = this.refresh();\n try {\n await this.inflight;\n } finally {\n this.inflight = null;\n }\n\n const token = this.store.getAccessToken();\n if (!token) throw new Error('Failed to obtain access token');\n return token;\n }\n\n /**\n * Authorization Code flow only.\n * Builds and returns the authorization URL to redirect the user to.\n * The returned `codeVerifier` must be persisted (e.g. in session storage)\n * and passed to `handleCallback`.\n */\n async getAuthorizationUrl(state?: string): Promise<{ url: string; codeVerifier: string }> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('getAuthorizationUrl is only available for authorization-code flow');\n }\n const endpoints = await this.resolveEndpoints();\n return buildAuthorizationUrl(\n { ...(this.config as AuthorizationCodeConfig), ...endpoints },\n state\n );\n }\n\n /**\n * Authorization Code flow only.\n * Exchanges the authorization code (from the redirect callback) for tokens\n * and stores them internally.\n */\n async handleCallback(code: string, codeVerifier: string): Promise<void> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('handleCallback is only available for authorization-code flow');\n }\n const endpoints = await this.resolveEndpoints();\n const tokenResponse = await exchangeCode(\n { ...(this.config as AuthorizationCodeConfig), ...endpoints },\n code,\n codeVerifier\n );\n this.store.store(tokenResponse);\n }\n\n /** Clears all stored tokens. */\n clearTokens(): void {\n this.store.clear();\n }\n\n /**\n * Resolves `tokenUrl` and `authorizationUrl`, fetching the OIDC discovery document\n * if either URL is absent from the config. Result is cached after the first call.\n */\n private async resolveEndpoints(): Promise<{ tokenUrl: string; authorizationUrl: string }> {\n if (this.endpoints) return this.endpoints;\n\n const cfg = this.config as {\n tokenUrl?: string;\n authorizationUrl?: string;\n discoveryUrl?: string;\n };\n\n const needsDiscovery =\n !cfg.tokenUrl ||\n (this.config.flow === 'authorization-code' && !cfg.authorizationUrl);\n\n if (needsDiscovery) {\n const oidc = await fetchOidcConfig(cfg.discoveryUrl);\n this.endpoints = {\n tokenUrl: cfg.tokenUrl ?? oidc.token_endpoint,\n authorizationUrl: cfg.authorizationUrl ?? oidc.authorization_endpoint,\n };\n } else {\n this.endpoints = {\n tokenUrl: cfg.tokenUrl!,\n authorizationUrl: cfg.authorizationUrl ?? '',\n };\n }\n\n return this.endpoints;\n }\n\n private async refresh(): Promise<void> {\n const endpoints = await this.resolveEndpoints();\n\n if (this.config.flow === 'client-credentials') {\n const tokenResponse = await fetchClientCredentialsToken({\n ...(this.config as ClientCredentialsConfig),\n tokenUrl: endpoints.tokenUrl,\n });\n this.store.store(tokenResponse);\n return;\n }\n\n // Authorization Code flow: try refresh token first, else throw\n const refreshToken = this.store.getRefreshToken();\n if (refreshToken) {\n const tokenResponse = await refreshAccessToken(\n { ...(this.config as AuthorizationCodeConfig), ...endpoints },\n refreshToken\n );\n this.store.store(tokenResponse);\n return;\n }\n\n throw new Error(\n 'No valid token available. Call getAuthorizationUrl() and handleCallback() first.'\n );\n }\n}\n","import type { AuthManager } from '../auth/auth-manager';\n\n/** Thrown when an API response is not 2xx. */\nexport class BcisApiError extends Error {\n constructor(\n public readonly status: number,\n public readonly statusText: string,\n public readonly body: unknown\n ) {\n super(`BCIS API error ${status} ${statusText}`);\n this.name = 'BcisApiError';\n }\n}\n\n/**\n * Thin fetch wrapper that:\n * - Injects the Authorization: Bearer header from AuthManager\n * - Serialises query parameters (including arrays as repeated params)\n * - Throws BcisApiError on non-2xx responses\n */\nexport class FetchClient {\n constructor(private readonly auth: AuthManager) {}\n\n async get<T>(\n baseUrl: string,\n path: string,\n params: Record<string, unknown> = {}\n ): Promise<T> {\n const token = await this.auth.getAccessToken();\n const url = new URL(baseUrl + path);\n\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) {\n url.searchParams.append(key, String(item));\n }\n } else {\n url.searchParams.set(key, String(value));\n }\n }\n\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n body = await response.text();\n }\n throw new BcisApiError(response.status, response.statusText, body);\n }\n\n return response.json() as Promise<T>;\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { AbpResponseDto, IndicesResponseDto, TpsResponseDto, CodesResponseDto } from '../types/core-api.types';\n\n// --- Parameter interfaces ---\n\nexport interface AbpRetrieveParams {\n /** When true, returns additional data for graph plotting. Default false. */\n 'include-data-for-graph'?: boolean;\n /** When true, includes sub-divided categories (e.g., size bands) in results. Default false. */\n 'include-subclasses'?: boolean;\n /** A comma-separated list of building function codes used to filter study results. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'building-function': string[];\n /** A list of type of work codes to filter the results by, the example contains all valid codes. */\n 'type-of-work': string[];\n /** A six-character code identifying the BCIS study */\n 'abp-study': 'ABPBUI' | 'ABPFUN' | 'ABPGRP' | 'ABPEM2' | 'ABPEUR' | 'ABPEXT';\n}\n\nexport interface IndicesRetrieveParams {\n /** Restricts the index series by year e.g. `1985` or description `1985 mean = 100`. Ignored if a series number is provided. Descriptions must match text exactly, case-insensitive but including spaces. */\n 'base-of-series'?: string;\n /** Restricts index series by `regularity` (`monthly`, `quarterly`, `annual`). Ignored if a series number is used. Defaults to `quarterly`, then `monthly`, then `annual`. */\n regularity?: string[];\n /** Restricts index figures up to a specific month `yyyy-mm`, or leave blank for latest available. */\n 'end-date'?: string;\n /** Restricts index figures to a specific month `yyyy-mm`, or leave blank for earliest available. */\n 'start-date'?: string;\n /** Comma-delimited list of short names (e.g. `BCISTPI:AllIn`) or series numbers. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'series-identification': string[];\n}\n\nexport interface TpsRetrieveParams {\n /** Supports suffixes to filter or refine the study data: - Level Filters: - `:region`, `:county`, `:district` - Example: `location2000:region` (regional indices), `location2000:county,district` (county and district indices) - Postcode Filter: - `:postcode:<POSTCODE>` (no spaces) - Example: `location2000:postcode:SW1P3AD` - Cannot be combined with level filters. - Effective Date Filter: - `:EffectiveDate:<YYYYQn>` - Example: `location2000:EffectiveDate:2015Q2` - Can be combined with postcode or level filters. - Outcode List: - `:outcode` - Example: `location2000:outcode` - Not supported for 1980 boundaries or with EffectiveDate. `short-tps-name` is not case sensitive. For available studies, use the `codesUpdate` web service with `codeType=shortTPSName`. */\n 'short-tps-name': string;\n}\n\nexport interface CodesUpdateParams {\n /** A date in `yyyy-mm-dd` format. Returns only codes added or modified since this date. Not supported for all code types. Leave blank to return all codes. */\n 'if-changed-since'?: string;\n /** A version string to select relevant code tables. */\n version?: string;\n /** A string to select the code list required. The supported values are: - `seriesIdentification`: All regularity names (for `/indices-retrieve`) - `shortTPSName`: Tender Price Studies - short names (for `/tps-retrieve`) - `ABPStudy`: Average building prices study codes (for `/abp-retrieve`) - `BuildingFunction`: List of building function codes (for `/abp-retrieve`, and `/analyses-search`) - `BuildingFunction:Categories`: List of building function categories - `BuildingFunction:[1-9]`: List of building function codes for the category specified after the colon - `BuildingFunction:Duration`: List of building function codes for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:Categories`: List of building function categories for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:[1-9]`: List of building function codes for duration calculator for category specified after the colon (for `Duration Model Calculate Api`) - `BuildingFunction:ABP`: List of building function codes for average building prices study where results are available to the user (for `/abp-retrieve`) - `SimplifiedTypeOfWork`: List of shorter type of work codes (for `/abp-retrieve`) The list of supported code types may be extended in the future. */\n 'code-type': 'shortTPSName' | 'ABPStudy' | 'BuildingFunction' | 'BuildingFunction:Categories' | 'BuildingFunction:[1-9]' | 'BuildingFunction:Duration' | 'BuildingFunction:Duration:Categories' | 'BuildingFunction:Duration:[1-9]' | 'BuildingFunction:ABP' | 'SimplifiedTypeOfWork';\n}\n\n// --- Client ---\n\nexport class CoreApiClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/core-apis';\n }\n\n /** abp-retrieve */\n async abpRetrieve(params: AbpRetrieveParams): Promise<AbpResponseDto> {\n return this.client.get<AbpResponseDto>(this.baseUrl, '/abp-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** indices-retrieve */\n async indicesRetrieve(params: IndicesRetrieveParams): Promise<IndicesResponseDto> {\n return this.client.get<IndicesResponseDto>(this.baseUrl, '/indices-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** tps-retrieve */\n async tpsRetrieve(params: TpsRetrieveParams): Promise<TpsResponseDto> {\n return this.client.get<TpsResponseDto>(this.baseUrl, '/tps-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** codes-update */\n async codesUpdate(params: CodesUpdateParams): Promise<CodesResponseDto> {\n return this.client.get<CodesResponseDto>(this.baseUrl, '/codes-update', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { CalculationResponse, UsageResponse } from '../types/residential-rebuild.types';\n\n// --- Parameter interfaces ---\n\nexport interface CalculateParams {\n /** Postcode of the property */\n postCode: string;\n /** Type of the property */\n type: string;\n /** Number of storeys in the property */\n storeys: string;\n /** Style of the property: detached, terraced, etc */\n style: string;\n /** Type of the walls of the property */\n wallType: string;\n /** Type of the roof of the property */\n roofType?: string;\n /** Year the property was built */\n yearBuilt: number;\n /** Number of flats */\n noOfFlats?: number;\n /** Area of the property in sq.m. */\n area?: number;\n /** Number of rooms in the property */\n noOfRooms?: number;\n /** Number of bedrooms in the property */\n noOfBedrooms?: number;\n /** Number of garage spaces in the property */\n noOfGarageSpaces?: number;\n /** Number of bathrooms in the property */\n noOfBathrooms?: number;\n /** Special features of the property, Must be blank, or a comma delimited list containing one or more of 'cellar' or 'noexternals' */\n specialFeatures?: string;\n}\n\nexport interface ReportUsageParams {\n /** First month of the usage report */\n startMonth?: string;\n /** Last month of the usage report */\n endMonth?: string;\n}\n\n// --- Client ---\n\nexport class ResidentialRebuildClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/residential-rebuild-calculator';\n }\n\n /** rbls-calculate */\n async calculate(params: CalculateParams): Promise<CalculationResponse> {\n return this.client.get<CalculationResponse>(this.baseUrl, '/rbls-calculate', params as unknown as Record<string, unknown>);\n }\n\n /** rbls-report-use */\n async reportUsage(params: ReportUsageParams): Promise<UsageResponse> {\n return this.client.get<UsageResponse>(this.baseUrl, '/rbls-report-use', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { EditionsDto, GetRateResponseDto, GetResourceResponseDto, GetBuildUpResponseDto } from '../types/schedule-of-rates.types';\n\n// --- Parameter interfaces ---\n\nexport interface GetRatesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetResourcesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetBuildUpParams {\n /** Id as returned from GetRates or GetResources */\n 'entity-id': string;\n}\n\n// --- Client ---\n\nexport class ScheduleOfRatesClient {\n private readonly client: FetchClient;\n private readonly baseUrl: string;\n\n constructor(auth: AuthManager, options?: { baseUrl?: string }) {\n this.client = new FetchClient(auth);\n this.baseUrl = options?.baseUrl ?? 'https://api.bcis.co.uk/schedule-of-rates';\n }\n\n /** Lists books and editions available to user */\n async getBooksEdition(): Promise<EditionsDto> {\n return this.client.get<EditionsDto>(this.baseUrl, '/get-books-edition', {});\n }\n\n /** Lists matching rates */\n async getRates(params: GetRatesParams): Promise<GetRateResponseDto> {\n return this.client.get<GetRateResponseDto>(this.baseUrl, '/get-rates', params as unknown as Record<string, unknown>);\n }\n\n /** Lists matching resources */\n async getResources(params: GetResourcesParams): Promise<GetResourceResponseDto> {\n return this.client.get<GetResourceResponseDto>(this.baseUrl, '/get-resources', params as unknown as Record<string, unknown>);\n }\n\n /** Lists components of a rate or buildUp */\n async getBuildUp(params: GetBuildUpParams): Promise<GetBuildUpResponseDto> {\n return this.client.get<GetBuildUpResponseDto>(this.baseUrl, '/get-build-up', params as unknown as Record<string, unknown>);\n }\n}\n"]}
|