@bcis/sdk 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -24,7 +24,7 @@ Use this flow for back-end or machine-to-machine integrations.
24
24
  Tokens are fetched and renewed automatically — no user interaction required.
25
25
 
26
26
  ```typescript
27
- import { AuthManager, CoreApiClient, ResidentialRebuildClient, ScheduleOfRatesClient } from '@bcis/sdk';
27
+ import { AuthManager, CoreApiClient, DurationCalculatorClient, ResidentialRebuildClient, ScheduleOfRatesClient } from '@bcis/sdk';
28
28
 
29
29
  const auth = new AuthManager({
30
30
  flow: 'client-credentials',
@@ -149,6 +149,63 @@ Returns codes lists or other supporting data
149
149
 
150
150
  ---
151
151
 
152
+ ### `DurationCalculatorClient`
153
+
154
+ **Base URL:** `https://api.bcis.co.uk/rebuild-core`
155
+
156
+ Duration calculator API Documentation
157
+
158
+ **Instantiation:**
159
+
160
+ ```typescript
161
+ import { AuthManager, DurationCalculatorClient } from '@bcis/sdk';
162
+
163
+ const client = new DurationCalculatorClient(auth);
164
+
165
+ // Override the base URL (e.g. for a staging environment):
166
+ // const client = new DurationCalculatorClient(auth, { baseUrl: 'https://api.bcis.co.uk/rebuild-core' });
167
+ ```
168
+
169
+ **Methods:**
170
+
171
+ #### `getModels(params: GetModelsParams): Promise<DurationModelsDto>`
172
+
173
+ This endpoint provides a list of models, quarters, and locations. Parameters from these lists will be used to perform duration calculations.
174
+
175
+ | Parameter | Type | Required | Description |
176
+ |-----------|------|:--------:|-------------|
177
+ | `publication-date` | string | | The date of the publication in YYYY-MM-DD format. Can be used to reproduce a calculation as it would have been performed |
178
+
179
+ #### `getOptions(params: GetOptionsParams): Promise<DurationModelOptionsDto>`
180
+
181
+ This endpoint provides a list of: building functions, procurements, selection of contractor, and client organisations. Parameters from these lists will be used to perform duration calculations.
182
+
183
+ | Parameter | Type | Required | Description |
184
+ |-----------|------|:--------:|-------------|
185
+ | `model-id` | number | ✓ | There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes |
186
+
187
+ #### `calculateDuration(params: CalculateDurationParams): Promise<CalculationResultDto>`
188
+
189
+ This endpoint provides the calculated construction duration based on the minimal details that might be available at the feasibility stage of a construction project.
190
+ For each estimate we provide two interval measures:
191
+ - Confidence interval: quantifies the uncertainty around the estimated mean duration. It gives a range that is likely to contain the true mean duration for projects with the same predictor values.
192
+ - Prediction interval: quantifies the likely range of outcomes for an individual project. It is wider than the confidence interval because it accounts both for uncertainty in the mean estimate and for the natural variability between individual projects.
193
+ Example: a CI of 5–13 weeks means the expected mean is likely in that range; a PI of 3–20 weeks means an individual project's duration is likely to fall somewhere in that wider range.
194
+
195
+ | Parameter | Type | Required | Description |
196
+ |-----------|------|:--------:|-------------|
197
+ | `publication-date` | string | | The date on which the project details are published. Can be used to reproduce a calculation as it would have been perfor |
198
+ | `organisation-id` | number | ✓ | The appropriate sector for the client organisation |
199
+ | `contractor-selection-id` | number | ✓ | The selection of contractor that best describes the way in which the contractor will be selected. |
200
+ | `procurement-id` | number | ✓ | The procurement process that best describes the way in which the project will be procured. |
201
+ | `function-group-id` | number | ✓ | The building function of the project. It is based on groups of building functions rather than the full list of building |
202
+ | `location-id` | number | ✓ | The location of the project. Is used to adjust the contract value to UK mean location. |
203
+ | `date-applicable` | string | ✓ | The quarter at which the contract value has been priced. Is used to adjust the contract value to the base price level us |
204
+ | `contract-value` | number | ✓ | The anticipated cost of construction expressed as at the anticipated start on site. |
205
+ | `model-id` | number | ✓ | There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes |
206
+
207
+ ---
208
+
152
209
  ### `ResidentialRebuildClient`
153
210
 
154
211
  **Base URL:** `https://api.bcis.co.uk/residential-rebuild-calculator`
@@ -288,6 +345,9 @@ import type {
288
345
  IndicesResponseDto,
289
346
  TpsResponseDto,
290
347
  CodesResponseDto,
348
+ DurationModelsDto,
349
+ DurationModelOptionsDto,
350
+ CalculationResultDto,
291
351
  CalculationResponse,
292
352
  UsageResponse,
293
353
  EditionsDto,
package/dist/index.d.mts CHANGED
@@ -330,6 +330,100 @@ declare class CoreApiClient {
330
330
  codesUpdate(params: CodesUpdateParams): Promise<CodesResponseDto>;
331
331
  }
332
332
 
333
+ interface DurationModelsDto {
334
+ models: Array<{
335
+ modelId: number;
336
+ title: string;
337
+ countryName: string;
338
+ currency: string;
339
+ currencyCode: string;
340
+ editionId: number;
341
+ defaultModel: boolean;
342
+ }>;
343
+ quarters: Array<{
344
+ dateApplicable: string;
345
+ quarter: string;
346
+ defaultQuarter: boolean;
347
+ }>;
348
+ locations: Array<{
349
+ locationId: number;
350
+ location: string;
351
+ defaultLocation: boolean;
352
+ }>;
353
+ }
354
+ interface DurationModelOptionsDto {
355
+ buildingFunctions: Array<{
356
+ id: number;
357
+ description: string;
358
+ defaultOption: boolean;
359
+ }>;
360
+ procurements: Array<{
361
+ id: number;
362
+ description: string;
363
+ defaultOption: boolean;
364
+ }>;
365
+ selectionOfContractors: Array<{
366
+ id: number;
367
+ description: string;
368
+ defaultOption: boolean;
369
+ }>;
370
+ clientOrganisations: Array<{
371
+ id: number;
372
+ description: string;
373
+ defaultOption: boolean;
374
+ }>;
375
+ }
376
+ interface CalculationResultDto {
377
+ estimatedDuration: number;
378
+ confidenceIntervalLower: number;
379
+ confidenceIntervalUpper: number;
380
+ predictionIntervalLower: number;
381
+ predictionIntervalUpper: number;
382
+ message?: string;
383
+ }
384
+
385
+ interface GetModelsParams {
386
+ /** The date of the publication in YYYY-MM-DD format. Can be used to reproduce a calculation as it would have been performed at the given date. */
387
+ 'publication-date'?: string;
388
+ }
389
+ interface GetOptionsParams {
390
+ /** There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes. */
391
+ 'model-id': number;
392
+ }
393
+ interface CalculateDurationParams {
394
+ /** The date on which the project details are published. Can be used to reproduce a calculation as it would have been performed at the given date. */
395
+ 'publication-date'?: string;
396
+ /** The appropriate sector for the client organisation */
397
+ 'organisation-id': number;
398
+ /** The selection of contractor that best describes the way in which the contractor will be selected. */
399
+ 'contractor-selection-id': number;
400
+ /** The procurement process that best describes the way in which the project will be procured. */
401
+ 'procurement-id': number;
402
+ /** The building function of the project. It is based on groups of building functions rather than the full list of building function codes used elsewhere in BCIS. */
403
+ 'function-group-id': number;
404
+ /** The location of the project. Is used to adjust the contract value to UK mean location. */
405
+ 'location-id': number;
406
+ /** The quarter at which the contract value has been priced. Is used to adjust the contract value to the base price level used by the models */
407
+ 'date-applicable': string;
408
+ /** The anticipated cost of construction expressed as at the anticipated start on site. */
409
+ 'contract-value': number;
410
+ /** There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes. */
411
+ 'model-id': number;
412
+ }
413
+ declare class DurationCalculatorClient {
414
+ private readonly client;
415
+ private readonly baseUrl;
416
+ constructor(auth: AuthManager, options?: {
417
+ baseUrl?: string;
418
+ });
419
+ /** Retrieve the list of models, quarters, and locations available for duration calculations */
420
+ getModels(params: GetModelsParams): Promise<DurationModelsDto>;
421
+ /** Retrieve a list of options for the duration-calculation parameters */
422
+ getOptions(params: GetOptionsParams): Promise<DurationModelOptionsDto>;
423
+ /** Retrieve the calculated construction duration */
424
+ calculateDuration(params: CalculateDurationParams): Promise<CalculationResultDto>;
425
+ }
426
+
333
427
  type UsageResponse = Array<{
334
428
  /** Month of calculations report */
335
429
  calculationMonth?: string;
@@ -638,4 +732,4 @@ declare class ScheduleOfRatesClient {
638
732
  getBuildUp(params: GetBuildUpParams): Promise<GetBuildUpResponseDto>;
639
733
  }
640
734
 
641
- export { type AbpResponseDto, type AuthConfig, AuthManager, type AuthorizationCodeConfig, BcisApiError, type CalculationResponse, type ClientCredentialsConfig, type CodesResponseDto, CoreApiClient, type EditionsDto, type Error$1 as Error, type GetBuildUpResponseDto, type GetRateResponseDto, type GetResourceResponseDto, type IndicesResponseDto, ResidentialRebuildClient, ScheduleOfRatesClient, type TokenResponse, type TpsResponseDto, type UsageResponse };
735
+ export { type AbpResponseDto, type AuthConfig, AuthManager, type AuthorizationCodeConfig, BcisApiError, type CalculationResponse, type CalculationResultDto, type ClientCredentialsConfig, type CodesResponseDto, CoreApiClient, DurationCalculatorClient, type DurationModelOptionsDto, type DurationModelsDto, type EditionsDto, type Error$1 as Error, type GetBuildUpResponseDto, type GetRateResponseDto, type GetResourceResponseDto, type IndicesResponseDto, ResidentialRebuildClient, ScheduleOfRatesClient, type TokenResponse, type TpsResponseDto, type UsageResponse };
package/dist/index.d.ts CHANGED
@@ -330,6 +330,100 @@ declare class CoreApiClient {
330
330
  codesUpdate(params: CodesUpdateParams): Promise<CodesResponseDto>;
331
331
  }
332
332
 
333
+ interface DurationModelsDto {
334
+ models: Array<{
335
+ modelId: number;
336
+ title: string;
337
+ countryName: string;
338
+ currency: string;
339
+ currencyCode: string;
340
+ editionId: number;
341
+ defaultModel: boolean;
342
+ }>;
343
+ quarters: Array<{
344
+ dateApplicable: string;
345
+ quarter: string;
346
+ defaultQuarter: boolean;
347
+ }>;
348
+ locations: Array<{
349
+ locationId: number;
350
+ location: string;
351
+ defaultLocation: boolean;
352
+ }>;
353
+ }
354
+ interface DurationModelOptionsDto {
355
+ buildingFunctions: Array<{
356
+ id: number;
357
+ description: string;
358
+ defaultOption: boolean;
359
+ }>;
360
+ procurements: Array<{
361
+ id: number;
362
+ description: string;
363
+ defaultOption: boolean;
364
+ }>;
365
+ selectionOfContractors: Array<{
366
+ id: number;
367
+ description: string;
368
+ defaultOption: boolean;
369
+ }>;
370
+ clientOrganisations: Array<{
371
+ id: number;
372
+ description: string;
373
+ defaultOption: boolean;
374
+ }>;
375
+ }
376
+ interface CalculationResultDto {
377
+ estimatedDuration: number;
378
+ confidenceIntervalLower: number;
379
+ confidenceIntervalUpper: number;
380
+ predictionIntervalLower: number;
381
+ predictionIntervalUpper: number;
382
+ message?: string;
383
+ }
384
+
385
+ interface GetModelsParams {
386
+ /** The date of the publication in YYYY-MM-DD format. Can be used to reproduce a calculation as it would have been performed at the given date. */
387
+ 'publication-date'?: string;
388
+ }
389
+ interface GetOptionsParams {
390
+ /** There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes. */
391
+ 'model-id': number;
392
+ }
393
+ interface CalculateDurationParams {
394
+ /** The date on which the project details are published. Can be used to reproduce a calculation as it would have been performed at the given date. */
395
+ 'publication-date'?: string;
396
+ /** The appropriate sector for the client organisation */
397
+ 'organisation-id': number;
398
+ /** The selection of contractor that best describes the way in which the contractor will be selected. */
399
+ 'contractor-selection-id': number;
400
+ /** The procurement process that best describes the way in which the project will be procured. */
401
+ 'procurement-id': number;
402
+ /** The building function of the project. It is based on groups of building functions rather than the full list of building function codes used elsewhere in BCIS. */
403
+ 'function-group-id': number;
404
+ /** The location of the project. Is used to adjust the contract value to UK mean location. */
405
+ 'location-id': number;
406
+ /** The quarter at which the contract value has been priced. Is used to adjust the contract value to the base price level used by the models */
407
+ 'date-applicable': string;
408
+ /** The anticipated cost of construction expressed as at the anticipated start on site. */
409
+ 'contract-value': number;
410
+ /** There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes. */
411
+ 'model-id': number;
412
+ }
413
+ declare class DurationCalculatorClient {
414
+ private readonly client;
415
+ private readonly baseUrl;
416
+ constructor(auth: AuthManager, options?: {
417
+ baseUrl?: string;
418
+ });
419
+ /** Retrieve the list of models, quarters, and locations available for duration calculations */
420
+ getModels(params: GetModelsParams): Promise<DurationModelsDto>;
421
+ /** Retrieve a list of options for the duration-calculation parameters */
422
+ getOptions(params: GetOptionsParams): Promise<DurationModelOptionsDto>;
423
+ /** Retrieve the calculated construction duration */
424
+ calculateDuration(params: CalculateDurationParams): Promise<CalculationResultDto>;
425
+ }
426
+
333
427
  type UsageResponse = Array<{
334
428
  /** Month of calculations report */
335
429
  calculationMonth?: string;
@@ -638,4 +732,4 @@ declare class ScheduleOfRatesClient {
638
732
  getBuildUp(params: GetBuildUpParams): Promise<GetBuildUpResponseDto>;
639
733
  }
640
734
 
641
- export { type AbpResponseDto, type AuthConfig, AuthManager, type AuthorizationCodeConfig, BcisApiError, type CalculationResponse, type ClientCredentialsConfig, type CodesResponseDto, CoreApiClient, type EditionsDto, type Error$1 as Error, type GetBuildUpResponseDto, type GetRateResponseDto, type GetResourceResponseDto, type IndicesResponseDto, ResidentialRebuildClient, ScheduleOfRatesClient, type TokenResponse, type TpsResponseDto, type UsageResponse };
735
+ export { type AbpResponseDto, type AuthConfig, AuthManager, type AuthorizationCodeConfig, BcisApiError, type CalculationResponse, type CalculationResultDto, type ClientCredentialsConfig, type CodesResponseDto, CoreApiClient, DurationCalculatorClient, type DurationModelOptionsDto, type DurationModelsDto, type EditionsDto, type Error$1 as Error, type GetBuildUpResponseDto, type GetRateResponseDto, type GetResourceResponseDto, type IndicesResponseDto, ResidentialRebuildClient, ScheduleOfRatesClient, type TokenResponse, type TpsResponseDto, type UsageResponse };
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
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
- exports.AuthManager=d;exports.BcisApiError=p;exports.CoreApiClient=h;exports.ResidentialRebuildClient=g;exports.ScheduleOfRatesClient=f;//# sourceMappingURL=index.js.map
1
+ 'use strict';var u=class{constructor(){this.token=null;}store(e){let t=e.expires_in!=null?Date.now()+e.expires_in*1e3:null;this.token={accessToken:e.access_token,expiresAt:t,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 k(n){let e=new URLSearchParams({grant_type:"client_credentials",client_id:n.clientId,client_secret:n.clientSecret});n.scopes&&n.scopes.length>0&&e.set("scope",n.scopes.join(" "));let t=n.tokenUrl;if(!t)throw new Error("tokenUrl is required for client credentials flow");let r=await fetch(t,{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 n=new Uint8Array(32);return crypto.getRandomValues(n),y(n)}async function T(n){let t=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",t);return y(new Uint8Array(r))}function y(n){let e=String.fromCharCode(...n);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function w(n,e){let t=A(),r=await T(t),o=new URLSearchParams({response_type:"code",client_id:n.clientId,redirect_uri:n.redirectUri,code_challenge:r,code_challenge_method:"S256"});n.scopes&&n.scopes.length>0&&o.set("scope",n.scopes.join(" ")),e&&o.set("state",e);let i=n.authorizationUrl;if(!i)throw new Error("authorizationUrl is required for authorization-code flow");return {url:`${i}?${o.toString()}`,codeVerifier:t}}async function b(n,e,t){let r=new URLSearchParams({grant_type:"authorization_code",client_id:n.clientId,redirect_uri:n.redirectUri,code:e,code_verifier:t}),o=n.tokenUrl;if(!o)throw new Error("tokenUrl is required for authorization-code flow");return U(o,r)}async function R(n,e){let t=new URLSearchParams({grant_type:"refresh_token",client_id:n.clientId,refresh_token:e}),r=n.tokenUrl;if(!r)throw new Error("tokenUrl is required for authorization-code flow");return U(r,t)}async function U(n,e){let t=await fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e.toString()});if(!t.ok){let r=await t.text().catch(()=>"");throw new Error(`Token request failed: ${t.status} ${t.statusText}${r?` \u2014 ${r}`:""}`)}return t.json()}var D="https://id.bcis.co.uk/.well-known/openid-configuration",C=new Map;async function P(n=D){let e=C.get(n);if(e)return e;let t=await fetch(n);if(!t.ok)throw new Error(`OIDC discovery failed: ${t.status} ${t.statusText} (${n})`);let r=await t.json();if(!r.token_endpoint||!r.authorization_endpoint)throw new Error(`OIDC discovery document at ${n} is missing required endpoints`);return C.set(n,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 t=await this.resolveEndpoints();return w({...this.config,...t},e)}async handleCallback(e,t){if(this.config.flow!=="authorization-code")throw new Error("handleCallback is only available for authorization-code flow");let r=await this.resolveEndpoints(),o=await b({...this.config,...r},e,t);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 P(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 k({...this.config,tokenUrl:e.tokenUrl});this.store.store(r);return}let t=this.store.getRefreshToken();if(t){let r=await R({...this.config,...e},t);this.store.store(r);return}throw new Error("No valid token available. Call getAuthorizationUrl() and handleCallback() first.")}};var p=class extends Error{constructor(t,r,o){super(`BCIS API error ${t} ${r}`);this.status=t;this.statusText=r;this.body=o;this.name="BcisApiError";}},s=class{constructor(e){this.auth=e;}async get(e,t,r={}){let o=await this.auth.getAccessToken(),i=new URL(e+t);for(let[c,l]of Object.entries(r))if(l!=null)if(Array.isArray(l))for(let x of l)i.searchParams.append(c,String(x));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,t){this.client=new s(e),this.baseUrl=t?.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,t){this.client=new s(e),this.baseUrl=t?.baseUrl??"https://api.bcis.co.uk/rebuild-core";}async getModels(e){return this.client.get(this.baseUrl,"/get-models",e)}async getOptions(e){return this.client.get(this.baseUrl,"/get-options",e)}async calculateDuration(e){return this.client.get(this.baseUrl,"/calculate-duration",e)}};var f=class{constructor(e,t){this.client=new s(e),this.baseUrl=t?.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 m=class{constructor(e,t){this.client=new s(e),this.baseUrl=t?.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
+ exports.AuthManager=d;exports.BcisApiError=p;exports.CoreApiClient=h;exports.DurationCalculatorClient=g;exports.ResidentialRebuildClient=f;exports.ScheduleOfRatesClient=m;//# 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/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,CAClB,aAAA,CAAeA,EAAO,YACxB,CAAC,CAAA,CAEGA,CAAAA,CAAO,QAAUA,CAAAA,CAAO,MAAA,CAAO,MAAA,CAAS,CAAA,EAC1CC,EAAK,GAAA,CAAI,OAAA,CAASD,CAAAA,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,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"]}
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/duration-calculator.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","DurationCalculatorClient","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,UAAA,EAAc,KACnB,IAAA,CAAK,GAAA,EAAI,CAAIA,CAAAA,CAAS,WAAa,GAAA,CACnC,IAAA,CAEN,IAAA,CAAK,KAAA,CAAQ,CACX,WAAA,CAAaA,CAAAA,CAAS,YAAA,CACtB,SAAA,CAAAC,EACA,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,OAAO,YAAA,EAAgB,IACrC,CAMA,SAAA,CAAUE,EAAgB,EAAA,CAAa,CACrC,OAAK,IAAA,CAAK,MACN,IAAA,CAAK,KAAA,CAAM,SAAA,GAAc,IAAA,C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AM,QAAA,CAAS9B,CAAAA,CAAqD,CAClE,OAAO,KAAK,MAAA,CAAO,GAAA,CAAwB,IAAA,CAAK,OAAA,CAAS,aAAcA,CAA4C,CACrH,CAGA,MAAM,aAAaA,CAAAA,CAA6D,CAC9E,OAAO,IAAA,CAAK,OAAO,GAAA,CAA4B,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 { DurationModelsDto, DurationModelOptionsDto, CalculationResultDto } from '../types/duration-calculator.types';\n\n// --- Parameter interfaces ---\n\nexport interface GetModelsParams {\n /** The date of the publication in YYYY-MM-DD format. Can be used to reproduce a calculation as it would have been performed at the given date. */\n 'publication-date'?: string;\n}\n\nexport interface GetOptionsParams {\n /** There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes. */\n 'model-id': number;\n}\n\nexport interface CalculateDurationParams {\n /** The date on which the project details are published. Can be used to reproduce a calculation as it would have been performed at the given date. */\n 'publication-date'?: string;\n /** The appropriate sector for the client organisation */\n 'organisation-id': number;\n /** The selection of contractor that best describes the way in which the contractor will be selected. */\n 'contractor-selection-id': number;\n /** The procurement process that best describes the way in which the project will be procured. */\n 'procurement-id': number;\n /** The building function of the project. It is based on groups of building functions rather than the full list of building function codes used elsewhere in BCIS. */\n 'function-group-id': number;\n /** The location of the project. Is used to adjust the contract value to UK mean location. */\n 'location-id': number;\n /** The quarter at which the contract value has been priced. Is used to adjust the contract value to the base price level used by the models */\n 'date-applicable': string;\n /** The anticipated cost of construction expressed as at the anticipated start on site. */\n 'contract-value': number;\n /** There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes. */\n 'model-id': number;\n}\n\n// --- Client ---\n\nexport class DurationCalculatorClient {\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/rebuild-core';\n }\n\n /** Retrieve the list of models, quarters, and locations available for duration calculations */\n async getModels(params: GetModelsParams): Promise<DurationModelsDto> {\n return this.client.get<DurationModelsDto>(this.baseUrl, '/get-models', params as unknown as Record<string, unknown>);\n }\n\n /** Retrieve a list of options for the duration-calculation parameters */\n async getOptions(params: GetOptionsParams): Promise<DurationModelOptionsDto> {\n return this.client.get<DurationModelOptionsDto>(this.baseUrl, '/get-options', params as unknown as Record<string, unknown>);\n }\n\n /** Retrieve the calculated construction duration */\n async calculateDuration(params: CalculateDurationParams): Promise<CalculationResultDto> {\n return this.client.get<CalculationResultDto>(this.baseUrl, '/calculate-duration', 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 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
- export{d as AuthManager,p as BcisApiError,h as CoreApiClient,g as ResidentialRebuildClient,f as ScheduleOfRatesClient};//# sourceMappingURL=index.mjs.map
1
+ var u=class{constructor(){this.token=null;}store(e){let t=e.expires_in!=null?Date.now()+e.expires_in*1e3:null;this.token={accessToken:e.access_token,expiresAt:t,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 k(n){let e=new URLSearchParams({grant_type:"client_credentials",client_id:n.clientId,client_secret:n.clientSecret});n.scopes&&n.scopes.length>0&&e.set("scope",n.scopes.join(" "));let t=n.tokenUrl;if(!t)throw new Error("tokenUrl is required for client credentials flow");let r=await fetch(t,{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 n=new Uint8Array(32);return crypto.getRandomValues(n),y(n)}async function T(n){let t=new TextEncoder().encode(n),r=await crypto.subtle.digest("SHA-256",t);return y(new Uint8Array(r))}function y(n){let e=String.fromCharCode(...n);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function w(n,e){let t=A(),r=await T(t),o=new URLSearchParams({response_type:"code",client_id:n.clientId,redirect_uri:n.redirectUri,code_challenge:r,code_challenge_method:"S256"});n.scopes&&n.scopes.length>0&&o.set("scope",n.scopes.join(" ")),e&&o.set("state",e);let i=n.authorizationUrl;if(!i)throw new Error("authorizationUrl is required for authorization-code flow");return {url:`${i}?${o.toString()}`,codeVerifier:t}}async function b(n,e,t){let r=new URLSearchParams({grant_type:"authorization_code",client_id:n.clientId,redirect_uri:n.redirectUri,code:e,code_verifier:t}),o=n.tokenUrl;if(!o)throw new Error("tokenUrl is required for authorization-code flow");return U(o,r)}async function R(n,e){let t=new URLSearchParams({grant_type:"refresh_token",client_id:n.clientId,refresh_token:e}),r=n.tokenUrl;if(!r)throw new Error("tokenUrl is required for authorization-code flow");return U(r,t)}async function U(n,e){let t=await fetch(n,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e.toString()});if(!t.ok){let r=await t.text().catch(()=>"");throw new Error(`Token request failed: ${t.status} ${t.statusText}${r?` \u2014 ${r}`:""}`)}return t.json()}var D="https://id.bcis.co.uk/.well-known/openid-configuration",C=new Map;async function P(n=D){let e=C.get(n);if(e)return e;let t=await fetch(n);if(!t.ok)throw new Error(`OIDC discovery failed: ${t.status} ${t.statusText} (${n})`);let r=await t.json();if(!r.token_endpoint||!r.authorization_endpoint)throw new Error(`OIDC discovery document at ${n} is missing required endpoints`);return C.set(n,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 t=await this.resolveEndpoints();return w({...this.config,...t},e)}async handleCallback(e,t){if(this.config.flow!=="authorization-code")throw new Error("handleCallback is only available for authorization-code flow");let r=await this.resolveEndpoints(),o=await b({...this.config,...r},e,t);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 P(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 k({...this.config,tokenUrl:e.tokenUrl});this.store.store(r);return}let t=this.store.getRefreshToken();if(t){let r=await R({...this.config,...e},t);this.store.store(r);return}throw new Error("No valid token available. Call getAuthorizationUrl() and handleCallback() first.")}};var p=class extends Error{constructor(t,r,o){super(`BCIS API error ${t} ${r}`);this.status=t;this.statusText=r;this.body=o;this.name="BcisApiError";}},s=class{constructor(e){this.auth=e;}async get(e,t,r={}){let o=await this.auth.getAccessToken(),i=new URL(e+t);for(let[c,l]of Object.entries(r))if(l!=null)if(Array.isArray(l))for(let x of l)i.searchParams.append(c,String(x));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,t){this.client=new s(e),this.baseUrl=t?.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,t){this.client=new s(e),this.baseUrl=t?.baseUrl??"https://api.bcis.co.uk/rebuild-core";}async getModels(e){return this.client.get(this.baseUrl,"/get-models",e)}async getOptions(e){return this.client.get(this.baseUrl,"/get-options",e)}async calculateDuration(e){return this.client.get(this.baseUrl,"/calculate-duration",e)}};var f=class{constructor(e,t){this.client=new s(e),this.baseUrl=t?.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 m=class{constructor(e,t){this.client=new s(e),this.baseUrl=t?.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
+ export{d as AuthManager,p as BcisApiError,h as CoreApiClient,g as DurationCalculatorClient,f as ResidentialRebuildClient,m as ScheduleOfRatesClient};//# sourceMappingURL=index.mjs.map
3
3
  //# sourceMappingURL=index.mjs.map
@@ -1 +1 @@
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,SA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AAA,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"]}
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/duration-calculator.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","DurationCalculatorClient","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,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AAA,CAAK,QAAS,iBAAA,CAAmBA,CAA4C,CAC3H,CAGA,MAAM,WAAA,CAAYA,CAAAA,CAAmD,CACnE,OAAO,KAAK,MAAA,CAAO,GAAA,CAAmB,IAAA,CAAK,OAAA,CAAS,mBAAoBA,CAA4C,CACtH,CACF,ECjCO,IAAMiC,CAAAA,CAAN,KAA4B,CAIjC,YAAYX,CAAAA,CAAmBQ,CAAAA,CAAgC,CAC7D,IAAA,CAAK,OAAS,IAAIT,CAAAA,CAAYC,CAAI,CAAA,CAClC,KAAK,OAAA,CAAUQ,CAAAA,EAAS,OAAA,EAAW,2CACrC,CAGA,MAAM,eAAA,EAAwC,CAC5C,OAAO,KAAK,MAAA,CAAO,GAAA,CAAiB,IAAA,CAAK,OAAA,CAAS,qBAAsB,EAAE,CAC5E,CAGA,MAAM,QAAA,CAAS9B,CAAAA,CAAqD,CAClE,OAAO,KAAK,MAAA,CAAO,GAAA,CAAwB,IAAA,CAAK,OAAA,CAAS,aAAcA,CAA4C,CACrH,CAGA,MAAM,aAAaA,CAAAA,CAA6D,CAC9E,OAAO,IAAA,CAAK,OAAO,GAAA,CAA4B,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 { DurationModelsDto, DurationModelOptionsDto, CalculationResultDto } from '../types/duration-calculator.types';\n\n// --- Parameter interfaces ---\n\nexport interface GetModelsParams {\n /** The date of the publication in YYYY-MM-DD format. Can be used to reproduce a calculation as it would have been performed at the given date. */\n 'publication-date'?: string;\n}\n\nexport interface GetOptionsParams {\n /** There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes. */\n 'model-id': number;\n}\n\nexport interface CalculateDurationParams {\n /** The date on which the project details are published. Can be used to reproduce a calculation as it would have been performed at the given date. */\n 'publication-date'?: string;\n /** The appropriate sector for the client organisation */\n 'organisation-id': number;\n /** The selection of contractor that best describes the way in which the contractor will be selected. */\n 'contractor-selection-id': number;\n /** The procurement process that best describes the way in which the project will be procured. */\n 'procurement-id': number;\n /** The building function of the project. It is based on groups of building functions rather than the full list of building function codes used elsewhere in BCIS. */\n 'function-group-id': number;\n /** The location of the project. Is used to adjust the contract value to UK mean location. */\n 'location-id': number;\n /** The quarter at which the contract value has been priced. Is used to adjust the contract value to the base price level used by the models */\n 'date-applicable': string;\n /** The anticipated cost of construction expressed as at the anticipated start on site. */\n 'contract-value': number;\n /** There are two separate models that underlie the calculator: one for new build projects and one for refurbishment schemes. */\n 'model-id': number;\n}\n\n// --- Client ---\n\nexport class DurationCalculatorClient {\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/rebuild-core';\n }\n\n /** Retrieve the list of models, quarters, and locations available for duration calculations */\n async getModels(params: GetModelsParams): Promise<DurationModelsDto> {\n return this.client.get<DurationModelsDto>(this.baseUrl, '/get-models', params as unknown as Record<string, unknown>);\n }\n\n /** Retrieve a list of options for the duration-calculation parameters */\n async getOptions(params: GetOptionsParams): Promise<DurationModelOptionsDto> {\n return this.client.get<DurationModelOptionsDto>(this.baseUrl, '/get-options', params as unknown as Record<string, unknown>);\n }\n\n /** Retrieve the calculated construction duration */\n async calculateDuration(params: CalculateDurationParams): Promise<CalculationResultDto> {\n return this.client.get<CalculationResultDto>(this.baseUrl, '/calculate-duration', 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bcis/sdk",
3
- "version": "0.1.4",
3
+ "version": "0.2.0",
4
4
  "description": "Type-safe TypeScript SDK for BCIS APIs",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",