@bcis/sdk 0.0.1 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/auth/token-store.ts","../src/auth/client-credentials.ts","../src/auth/authorization-code.ts","../src/auth/auth-manager.ts","../src/http/fetch-client.ts","../src/clients/core-api.ts","../src/clients/residential-rebuild.ts","../src/clients/schedule-of-rates.ts"],"names":["TokenStore","response","expiresAt","bufferSeconds","fetchClientCredentialsToken","config","body","text","generateCodeVerifier","array","base64UrlEncode","generateCodeChallenge","verifier","data","digest","bytes","str","getAuthorizationUrl","state","codeVerifier","codeChallenge","params","exchangeCode","code","tokenRequest","refreshAccessToken","refreshToken","tokenUrl","AuthManager","token","tokenResponse","BcisApiError","status","statusText","FetchClient","auth","baseUrl","path","url","key","value","item","CoreApiClient","ResidentialRebuildClient","ScheduleOfRatesClient"],"mappings":"aAGO,IAAMA,CAAAA,CAAN,KAAiB,CAAjB,WAAA,EAAA,CACL,IAAA,CAAQ,MAA4B,KAAA,CAEpC,KAAA,CAAMC,CAAAA,CAA+B,CACnC,IAAMC,CAAAA,CACJD,EAAS,UAAA,EAAc,IAAA,CACnB,IAAA,CAAK,GAAA,EAAI,CAAIA,CAAAA,CAAS,UAAA,CAAa,GAAA,CACnC,IAAA,CAEN,IAAA,CAAK,KAAA,CAAQ,CACX,WAAA,CAAaA,CAAAA,CAAS,aACtB,SAAA,CAAAC,CAAAA,CACA,YAAA,CAAcD,CAAAA,CAAS,aAAA,EAAiB,IAC1C,EACF,CAEA,cAAA,EAAgC,CAC9B,OAAO,IAAA,CAAK,KAAA,EAAO,WAAA,EAAe,IACpC,CAEA,eAAA,EAAiC,CAC/B,OAAO,IAAA,CAAK,KAAA,EAAO,YAAA,EAAgB,IACrC,CAMA,SAAA,CAAUE,CAAAA,CAAgB,EAAA,CAAa,CACrC,OAAK,KAAK,KAAA,CACN,IAAA,CAAK,KAAA,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CAAO,GAAA,CAA4B,0CAAA,CAA4C,gBAAA,CAAkBA,CAA4C,CAC3J,CAGA,MAAM,UAAA,CAAWA,CAAAA,CAA0D,CACzE,OAAO,IAAA,CAAK,MAAA,CAAO,GAAA,CAA2B,0CAAA,CAA4C,eAAA,CAAiBA,CAA4C,CACzJ,CACF","file":"index.js","sourcesContent":["import type { StoredToken, TokenResponse } from './types';\n\n/** In-memory token storage with expiry awareness. */\nexport class TokenStore {\n private token: StoredToken | null = null;\n\n store(response: TokenResponse): void {\n const expiresAt =\n response.expires_in != null\n ? Date.now() + response.expires_in * 1000\n : null;\n\n this.token = {\n accessToken: response.access_token,\n expiresAt,\n refreshToken: response.refresh_token ?? null,\n };\n }\n\n getAccessToken(): string | null {\n return this.token?.accessToken ?? null;\n }\n\n getRefreshToken(): string | null {\n return this.token?.refreshToken ?? null;\n }\n\n /**\n * Returns true if there is no token or the token is within `bufferSeconds`\n * of expiry. Defaults to a 30-second buffer to allow for clock skew.\n */\n isExpired(bufferSeconds = 30): boolean {\n if (!this.token) return true;\n if (this.token.expiresAt === null) return false;\n return Date.now() >= this.token.expiresAt - bufferSeconds * 1000;\n }\n\n clear(): void {\n this.token = null;\n }\n}\n","import type { ClientCredentialsConfig, TokenResponse } from './types';\n\n/**\n * Fetches a new access token using the OAuth2 Client Credentials flow.\n */\nexport async function fetchClientCredentialsToken(\n config: ClientCredentialsConfig\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: config.clientId,\n client_secret: config.clientSecret,\n });\n\n if (config.scopes && config.scopes.length > 0) {\n body.set('scope', config.scopes.join(' '));\n }\n\n const response = await fetch(config.tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","import type { AuthorizationCodeConfig, TokenResponse } from './types';\n\n// ---------------------------------------------------------------------------\n// PKCE helpers\n// ---------------------------------------------------------------------------\n\n/** Generates a cryptographically random PKCE code verifier (43-128 chars). */\nexport function generateCodeVerifier(): string {\n const array = new Uint8Array(32);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\n/** Derives a PKCE code challenge (S256) from a code verifier. */\nexport async function generateCodeChallenge(verifier: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const digest = await crypto.subtle.digest('SHA-256', data);\n return base64UrlEncode(new Uint8Array(digest));\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n const str = String.fromCharCode(...bytes);\n return btoa(str).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n// ---------------------------------------------------------------------------\n// Authorization Code flows\n// ---------------------------------------------------------------------------\n\n/**\n * Builds the authorization URL to redirect the user to.\n * Returns the URL and the code verifier (must be stored and passed to exchangeCode).\n */\nexport async function getAuthorizationUrl(\n config: AuthorizationCodeConfig,\n state?: string\n): Promise<{ url: string; codeVerifier: string }> {\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = await generateCodeChallenge(codeVerifier);\n\n const params = new URLSearchParams({\n response_type: 'code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code_challenge: codeChallenge,\n code_challenge_method: 'S256',\n });\n\n if (config.scopes && config.scopes.length > 0) {\n params.set('scope', config.scopes.join(' '));\n }\n\n if (state) {\n params.set('state', state);\n }\n\n return {\n url: `${config.authorizationUrl}?${params.toString()}`,\n codeVerifier,\n };\n}\n\n/**\n * Exchanges an authorization code for tokens.\n */\nexport async function exchangeCode(\n config: AuthorizationCodeConfig,\n code: string,\n codeVerifier: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code,\n code_verifier: codeVerifier,\n });\n\n return tokenRequest(config.tokenUrl, body);\n}\n\n/**\n * Refreshes an access token using a refresh token.\n */\nexport async function refreshAccessToken(\n config: AuthorizationCodeConfig,\n refreshToken: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: config.clientId,\n refresh_token: refreshToken,\n });\n\n return tokenRequest(config.tokenUrl, body);\n}\n\nasync function tokenRequest(\n tokenUrl: string,\n body: URLSearchParams\n): Promise<TokenResponse> {\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","import type { AuthConfig, AuthorizationCodeConfig } from './types';\nimport { TokenStore } from './token-store';\nimport { fetchClientCredentialsToken } from './client-credentials';\nimport {\n getAuthorizationUrl as buildAuthorizationUrl,\n exchangeCode,\n refreshAccessToken,\n} from './authorization-code';\n\n/**\n * Centralized OAuth2 authentication manager.\n *\n * Supports:\n * - Client Credentials flow (server-to-server, fully automatic)\n * - Authorization Code + PKCE flow (user-facing applications)\n *\n * @example Client Credentials\n * ```ts\n * const auth = new AuthManager({\n * flow: 'client-credentials',\n * clientId: 'my-id',\n * clientSecret: 'my-secret',\n * tokenUrl: 'https://auth.bcis.co.uk/oauth/token',\n * });\n * const token = await auth.getAccessToken();\n * ```\n *\n * @example Authorization Code\n * ```ts\n * const auth = new AuthManager({\n * flow: 'authorization-code',\n * clientId: 'my-id',\n * tokenUrl: 'https://auth.bcis.co.uk/oauth/token',\n * authorizationUrl: 'https://auth.bcis.co.uk/authorize',\n * redirectUri: 'https://myapp.com/callback',\n * scopes: ['openid', 'profile'],\n * });\n *\n * // Step 1: redirect user\n * const { url, codeVerifier } = await auth.getAuthorizationUrl();\n * // store codeVerifier in session, redirect user to url\n *\n * // Step 2: on callback\n * await auth.handleCallback(code, codeVerifier);\n *\n * // Step 3: use the SDK\n * const token = await auth.getAccessToken();\n * ```\n */\nexport class AuthManager {\n private readonly store = new TokenStore();\n /** Pending token fetch promise to prevent concurrent requests */\n private inflight: Promise<void> | null = null;\n\n constructor(private readonly config: AuthConfig) {}\n\n /**\n * Returns a valid access token, fetching or refreshing as needed.\n * For Client Credentials flow this is fully automatic.\n * For Authorization Code flow, `handleCallback` must have been called first.\n */\n async getAccessToken(): Promise<string> {\n if (!this.store.isExpired()) {\n return this.store.getAccessToken()!;\n }\n\n if (this.inflight) {\n await this.inflight;\n return this.store.getAccessToken()!;\n }\n\n this.inflight = this.refresh();\n try {\n await this.inflight;\n } finally {\n this.inflight = null;\n }\n\n const token = this.store.getAccessToken();\n if (!token) throw new Error('Failed to obtain access token');\n return token;\n }\n\n /**\n * Authorization Code flow only.\n * Builds and returns the authorization URL to redirect the user to.\n * The returned `codeVerifier` must be persisted (e.g. in session storage)\n * and passed to `handleCallback`.\n */\n async getAuthorizationUrl(state?: string): Promise<{ url: string; codeVerifier: string }> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('getAuthorizationUrl is only available for authorization-code flow');\n }\n return buildAuthorizationUrl(this.config, state);\n }\n\n /**\n * Authorization Code flow only.\n * Exchanges the authorization code (from the redirect callback) for tokens\n * and stores them internally.\n */\n async handleCallback(code: string, codeVerifier: string): Promise<void> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('handleCallback is only available for authorization-code flow');\n }\n const tokenResponse = await exchangeCode(this.config, code, codeVerifier);\n this.store.store(tokenResponse);\n }\n\n /** Clears all stored tokens. */\n clearTokens(): void {\n this.store.clear();\n }\n\n private async refresh(): Promise<void> {\n if (this.config.flow === 'client-credentials') {\n const tokenResponse = await fetchClientCredentialsToken(this.config);\n this.store.store(tokenResponse);\n return;\n }\n\n // Authorization Code flow: try refresh token first, else throw\n const refreshToken = this.store.getRefreshToken();\n if (refreshToken) {\n const tokenResponse = await refreshAccessToken(\n this.config as AuthorizationCodeConfig,\n refreshToken\n );\n this.store.store(tokenResponse);\n return;\n }\n\n throw new Error(\n 'No valid token available. Call getAuthorizationUrl() and handleCallback() first.'\n );\n }\n}\n","import type { AuthManager } from '../auth/auth-manager';\n\n/** Thrown when an API response is not 2xx. */\nexport class BcisApiError extends Error {\n constructor(\n public readonly status: number,\n public readonly statusText: string,\n public readonly body: unknown\n ) {\n super(`BCIS API error ${status} ${statusText}`);\n this.name = 'BcisApiError';\n }\n}\n\n/**\n * Thin fetch wrapper that:\n * - Injects the Authorization: Bearer header from AuthManager\n * - Serialises query parameters (including arrays as repeated params)\n * - Throws BcisApiError on non-2xx responses\n */\nexport class FetchClient {\n constructor(private readonly auth: AuthManager) {}\n\n async get<T>(\n baseUrl: string,\n path: string,\n params: Record<string, unknown> = {}\n ): Promise<T> {\n const token = await this.auth.getAccessToken();\n const url = new URL(baseUrl + path);\n\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) {\n url.searchParams.append(key, String(item));\n }\n } else {\n url.searchParams.set(key, String(value));\n }\n }\n\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n body = await response.text();\n }\n throw new BcisApiError(response.status, response.statusText, body);\n }\n\n return response.json() as Promise<T>;\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { AbpResponseDto, IndicesResponseDto, TpsResponseDto, CodesResponseDto } from '../types/core-api.types';\n\n// --- Parameter interfaces ---\n\nexport interface AbpRetrieveParams {\n /** When true, returns additional data for graph plotting. Default false. */\n 'include-data-for-graph'?: boolean;\n /** When true, includes sub-divided categories (e.g., size bands) in results. Default false. */\n 'include-subclasses'?: boolean;\n /** A comma-separated list of building function codes used to filter study results. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'building-function': string[];\n /** A list of type of work codes to filter the results by, the example contains all valid codes. */\n 'type-of-work': string[];\n /** A six-character code identifying the BCIS study */\n 'abp-study': 'ABPBUI' | 'ABPFUN' | 'ABPGRP' | 'ABPEM2' | 'ABPEUR' | 'ABPEXT';\n}\n\nexport interface IndicesRetrieveParams {\n /** Restricts the index series by year e.g. `1985` or description `1985 mean = 100`. Ignored if a series number is provided. Descriptions must match text exactly, case-insensitive but including spaces. */\n 'base-of-series'?: string;\n /** Restricts index series by `regularity` (`monthly`, `quarterly`, `annual`). Ignored if a series number is used. Defaults to `quarterly`, then `monthly`, then `annual`. */\n regularity?: string[];\n /** Restricts index figures up to a specific month `yyyy-mm`, or leave blank for latest available. */\n 'end-date'?: string;\n /** Restricts index figures to a specific month `yyyy-mm`, or leave blank for earliest available. */\n 'start-date'?: string;\n /** Comma-delimited list of short names (e.g. `BCISTPI:AllIn`) or series numbers. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'series-identification': string[];\n}\n\nexport interface TpsRetrieveParams {\n /** Supports suffixes to filter or refine the study data: - Level Filters: - `:region`, `:county`, `:district` - Example: `location2000:region` (regional indices), `location2000:county,district` (county and district indices) - Postcode Filter: - `:postcode:<POSTCODE>` (no spaces) - Example: `location2000:postcode:SW1P3AD` - Cannot be combined with level filters. - Effective Date Filter: - `:EffectiveDate:<YYYYQn>` - Example: `location2000:EffectiveDate:2015Q2` - Can be combined with postcode or level filters. - Outcode List: - `:outcode` - Example: `location2000:outcode` - Not supported for 1980 boundaries or with EffectiveDate. `short-tps-name` is not case sensitive. For available studies, use the `codesUpdate` web service with `codeType=shortTPSName`. */\n 'short-tps-name': string;\n}\n\nexport interface CodesUpdateParams {\n /** A date in `yyyy-mm-dd` format. Returns only codes added or modified since this date. Not supported for all code types. Leave blank to return all codes. */\n 'if-changed-since'?: string;\n /** A version string to select relevant code tables. */\n version?: string;\n /** A string to select the code list required. The supported values are: - `seriesIdentification`: All regularity names (for `/indices-retrieve`) - `shortTPSName`: Tender Price Studies - short names (for `/tps-retrieve`) - `ABPStudy`: Average building prices study codes (for `/abp-retrieve`) - `BuildingFunction`: List of building function codes (for `/abp-retrieve`, and `/analyses-search`) - `BuildingFunction:Categories`: List of building function categories - `BuildingFunction:[1-9]`: List of building function codes for the category specified after the colon - `BuildingFunction:Duration`: List of building function codes for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:Categories`: List of building function categories for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:[1-9]`: List of building function codes for duration calculator for category specified after the colon (for `Duration Model Calculate Api`) - `BuildingFunction:ABP`: List of building function codes for average building prices study where results are available to the user (for `/abp-retrieve`) - `SimplifiedTypeOfWork`: List of shorter type of work codes (for `/abp-retrieve`) The list of supported code types may be extended in the future. */\n 'code-type': 'shortTPSName' | 'ABPStudy' | 'BuildingFunction' | 'BuildingFunction:Categories' | 'BuildingFunction:[1-9]' | 'BuildingFunction:Duration' | 'BuildingFunction:Duration:Categories' | 'BuildingFunction:Duration:[1-9]' | 'BuildingFunction:ABP' | 'SimplifiedTypeOfWork';\n}\n\n// --- Client ---\n\nexport class CoreApiClient {\n private readonly client: FetchClient;\n\n constructor(auth: AuthManager) {\n this.client = new FetchClient(auth);\n }\n\n /** abp-retrieve */\n async abpRetrieve(params: AbpRetrieveParams): Promise<AbpResponseDto> {\n return this.client.get<AbpResponseDto>('https://api.bcis.co.uk/core-apis', '/abp-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** indices-retrieve */\n async indicesRetrieve(params: IndicesRetrieveParams): Promise<IndicesResponseDto> {\n return this.client.get<IndicesResponseDto>('https://api.bcis.co.uk/core-apis', '/indices-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** tps-retrieve */\n async tpsRetrieve(params: TpsRetrieveParams): Promise<TpsResponseDto> {\n return this.client.get<TpsResponseDto>('https://api.bcis.co.uk/core-apis', '/tps-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** codes-update */\n async codesUpdate(params: CodesUpdateParams): Promise<CodesResponseDto> {\n return this.client.get<CodesResponseDto>('https://api.bcis.co.uk/core-apis', '/codes-update', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { CalculationResponse, UsageResponse } from '../types/residential-rebuild.types';\n\n// --- Parameter interfaces ---\n\nexport interface CalculateParams {\n /** Postcode of the property */\n postCode: string;\n /** Type of the property */\n type: string;\n /** Number of storeys in the property */\n storeys: string;\n /** Style of the property: detached, terraced, etc */\n style: string;\n /** Type of the walls of the property */\n wallType: string;\n /** Type of the roof of the property */\n roofType?: string;\n /** Year the property was built */\n yearBuilt: number;\n /** Number of flats */\n noOfFlats?: number;\n /** Area of the property in sq.m. */\n area?: number;\n /** Number of rooms in the property */\n noOfRooms?: number;\n /** Number of bedrooms in the property */\n noOfBedrooms?: number;\n /** Number of garage spaces in the property */\n noOfGarageSpaces?: number;\n /** Number of bathrooms in the property */\n noOfBathrooms?: number;\n /** Special features of the property, Must be blank, or a comma delimited list containing one or more of 'cellar' or 'noexternals' */\n specialFeatures?: string;\n}\n\nexport interface ReportUsageParams {\n /** First month of the usage report */\n startMonth?: string;\n /** Last month of the usage report */\n endMonth?: string;\n}\n\n// --- Client ---\n\nexport class ResidentialRebuildClient {\n private readonly client: FetchClient;\n\n constructor(auth: AuthManager) {\n this.client = new FetchClient(auth);\n }\n\n /** rbls-calculate */\n async calculate(params: CalculateParams): Promise<CalculationResponse> {\n return this.client.get<CalculationResponse>('https://api.bcis.co.uk/residential-rebuild-calculator', '/rbls-calculate', params as unknown as Record<string, unknown>);\n }\n\n /** rbls-report-use */\n async reportUsage(params: ReportUsageParams): Promise<UsageResponse> {\n return this.client.get<UsageResponse>('https://api.bcis.co.uk/residential-rebuild-calculator', '/rbls-report-use', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { EditionsDto, GetRateResponseDto, GetResourceResponseDto, GetBuildUpResponseDto } from '../types/schedule-of-rates.types';\n\n// --- Parameter interfaces ---\n\nexport interface GetRatesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetResourcesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetBuildUpParams {\n /** Id as returned from GetRates or GetResources */\n 'entity-id': string;\n}\n\n// --- Client ---\n\nexport class ScheduleOfRatesClient {\n private readonly client: FetchClient;\n\n constructor(auth: AuthManager) {\n this.client = new FetchClient(auth);\n }\n\n /** Lists books and editions available to user */\n async getBooksEdition(): Promise<EditionsDto> {\n return this.client.get<EditionsDto>('https://api.bcis.co.uk/schedule-of-rates', '/get-books-edition', {});\n }\n\n /** Lists matching rates */\n async getRates(params: GetRatesParams): Promise<GetRateResponseDto> {\n return this.client.get<GetRateResponseDto>('https://api.bcis.co.uk/schedule-of-rates', '/get-rates', params as unknown as Record<string, unknown>);\n }\n\n /** Lists matching resources */\n async getResources(params: GetResourcesParams): Promise<GetResourceResponseDto> {\n return this.client.get<GetResourceResponseDto>('https://api.bcis.co.uk/schedule-of-rates', '/get-resources', params as unknown as Record<string, unknown>);\n }\n\n /** Lists components of a rate or buildUp */\n async getBuildUp(params: GetBuildUpParams): Promise<GetBuildUpResponseDto> {\n return this.client.get<GetBuildUpResponseDto>('https://api.bcis.co.uk/schedule-of-rates', '/get-build-up', params as unknown as Record<string, unknown>);\n }\n}\n"]}
package/dist/index.mjs ADDED
@@ -0,0 +1,3 @@
1
+ var l=class{constructor(){this.token=null;}store(e){let r=e.expires_in!=null?Date.now()+e.expires_in*1e3:null;this.token={accessToken:e.access_token,expiresAt:r,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 r=await fetch(t.tokenUrl,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e.toString()});if(!r.ok){let n=await r.text().catch(()=>"");throw new Error(`Token request failed: ${r.status} ${r.statusText}${n?` \u2014 ${n}`:""}`)}return r.json()}function b(){let t=new Uint8Array(32);return crypto.getRandomValues(t),y(t)}async function A(t){let r=new TextEncoder().encode(t),n=await crypto.subtle.digest("SHA-256",r);return y(new Uint8Array(n))}function y(t){let e=String.fromCharCode(...t);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function k(t,e){let r=b(),n=await A(r),s=new URLSearchParams({response_type:"code",client_id:t.clientId,redirect_uri:t.redirectUri,code_challenge:n,code_challenge_method:"S256"});return t.scopes&&t.scopes.length>0&&s.set("scope",t.scopes.join(" ")),e&&s.set("state",e),{url:`${t.authorizationUrl}?${s.toString()}`,codeVerifier:r}}async function R(t,e,r){let n=new URLSearchParams({grant_type:"authorization_code",client_id:t.clientId,redirect_uri:t.redirectUri,code:e,code_verifier:r});return C(t.tokenUrl,n)}async function w(t,e){let r=new URLSearchParams({grant_type:"refresh_token",client_id:t.clientId,refresh_token:e});return C(t.tokenUrl,r)}async function C(t,e){let r=await fetch(t,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:e.toString()});if(!r.ok){let n=await r.text().catch(()=>"");throw new Error(`Token request failed: ${r.status} ${r.statusText}${n?` \u2014 ${n}`:""}`)}return r.json()}var d=class{constructor(e){this.config=e;this.store=new l;this.inflight=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");return k(this.config,e)}async handleCallback(e,r){if(this.config.flow!=="authorization-code")throw new Error("handleCallback is only available for authorization-code flow");let n=await R(this.config,e,r);this.store.store(n);}clearTokens(){this.store.clear();}async refresh(){if(this.config.flow==="client-credentials"){let r=await m(this.config);this.store.store(r);return}let e=this.store.getRefreshToken();if(e){let r=await w(this.config,e);this.store.store(r);return}throw new Error("No valid token available. Call getAuthorizationUrl() and handleCallback() first.")}};var p=class extends Error{constructor(r,n,s){super(`BCIS API error ${r} ${n}`);this.status=r;this.statusText=n;this.body=s;this.name="BcisApiError";}},o=class{constructor(e){this.auth=e;}async get(e,r,n={}){let s=await this.auth.getAccessToken(),u=new URL(e+r);for(let[a,c]of Object.entries(n))if(c!=null)if(Array.isArray(c))for(let P of c)u.searchParams.append(a,String(P));else u.searchParams.set(a,String(c));let i=await fetch(u.toString(),{method:"GET",headers:{Authorization:`Bearer ${s}`,Accept:"application/json"}});if(!i.ok){let a;try{a=await i.json();}catch{a=await i.text();}throw new p(i.status,i.statusText,a)}return i.json()}};var h=class{constructor(e){this.client=new o(e);}async abpRetrieve(e){return this.client.get("https://api.bcis.co.uk/core-apis","/abp-retrieve",e)}async indicesRetrieve(e){return this.client.get("https://api.bcis.co.uk/core-apis","/indices-retrieve",e)}async tpsRetrieve(e){return this.client.get("https://api.bcis.co.uk/core-apis","/tps-retrieve",e)}async codesUpdate(e){return this.client.get("https://api.bcis.co.uk/core-apis","/codes-update",e)}};var g=class{constructor(e){this.client=new o(e);}async calculate(e){return this.client.get("https://api.bcis.co.uk/residential-rebuild-calculator","/rbls-calculate",e)}async reportUsage(e){return this.client.get("https://api.bcis.co.uk/residential-rebuild-calculator","/rbls-report-use",e)}};var f=class{constructor(e){this.client=new o(e);}async getBooksEdition(){return this.client.get("https://api.bcis.co.uk/schedule-of-rates","/get-books-edition",{})}async getRates(e){return this.client.get("https://api.bcis.co.uk/schedule-of-rates","/get-rates",e)}async getResources(e){return this.client.get("https://api.bcis.co.uk/schedule-of-rates","/get-resources",e)}async getBuildUp(e){return this.client.get("https://api.bcis.co.uk/schedule-of-rates","/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
3
+ //# sourceMappingURL=index.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/auth/token-store.ts","../src/auth/client-credentials.ts","../src/auth/authorization-code.ts","../src/auth/auth-manager.ts","../src/http/fetch-client.ts","../src/clients/core-api.ts","../src/clients/residential-rebuild.ts","../src/clients/schedule-of-rates.ts"],"names":["TokenStore","response","expiresAt","bufferSeconds","fetchClientCredentialsToken","config","body","text","generateCodeVerifier","array","base64UrlEncode","generateCodeChallenge","verifier","data","digest","bytes","str","getAuthorizationUrl","state","codeVerifier","codeChallenge","params","exchangeCode","code","tokenRequest","refreshAccessToken","refreshToken","tokenUrl","AuthManager","token","tokenResponse","BcisApiError","status","statusText","FetchClient","auth","baseUrl","path","url","key","value","item","CoreApiClient","ResidentialRebuildClient","ScheduleOfRatesClient"],"mappings":"AAGO,IAAMA,CAAAA,CAAN,KAAiB,CAAjB,WAAA,EAAA,CACL,IAAA,CAAQ,MAA4B,KAAA,CAEpC,KAAA,CAAMC,CAAAA,CAA+B,CACnC,IAAMC,CAAAA,CACJD,EAAS,UAAA,EAAc,IAAA,CACnB,IAAA,CAAK,GAAA,EAAI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C/BO,IAAMuB,CAAAA,CAAN,KAA4B,CAGjC,WAAA,CAAYT,CAAAA,CAAmB,CAC7B,KAAK,MAAA,CAAS,IAAID,CAAAA,CAAYC,CAAI,EACpC,CAGA,MAAM,eAAA,EAAwC,CAC5C,OAAO,IAAA,CAAK,MAAA,CAAO,GAAA,CAAiB,0CAAA,CAA4C,qBAAsB,EAAE,CAC1G,CAGA,MAAM,QAAA,CAASd,CAAAA,CAAqD,CAClE,OAAO,IAAA,CAAK,MAAA,CAAO,GAAA,CAAwB,0CAAA,CAA4C,YAAA,CAAcA,CAA4C,CACnJ,CAGA,MAAM,YAAA,CAAaA,CAAAA,CAA6D,CAC9E,OAAO,IAAA,CAAK,MAAA,CAAO,GAAA,CAA4B,0CAAA,CAA4C,gBAAA,CAAkBA,CAA4C,CAC3J,CAGA,MAAM,UAAA,CAAWA,CAAAA,CAA0D,CACzE,OAAO,IAAA,CAAK,MAAA,CAAO,GAAA,CAA2B,0CAAA,CAA4C,eAAA,CAAiBA,CAA4C,CACzJ,CACF","file":"index.mjs","sourcesContent":["import type { StoredToken, TokenResponse } from './types';\n\n/** In-memory token storage with expiry awareness. */\nexport class TokenStore {\n private token: StoredToken | null = null;\n\n store(response: TokenResponse): void {\n const expiresAt =\n response.expires_in != null\n ? Date.now() + response.expires_in * 1000\n : null;\n\n this.token = {\n accessToken: response.access_token,\n expiresAt,\n refreshToken: response.refresh_token ?? null,\n };\n }\n\n getAccessToken(): string | null {\n return this.token?.accessToken ?? null;\n }\n\n getRefreshToken(): string | null {\n return this.token?.refreshToken ?? null;\n }\n\n /**\n * Returns true if there is no token or the token is within `bufferSeconds`\n * of expiry. Defaults to a 30-second buffer to allow for clock skew.\n */\n isExpired(bufferSeconds = 30): boolean {\n if (!this.token) return true;\n if (this.token.expiresAt === null) return false;\n return Date.now() >= this.token.expiresAt - bufferSeconds * 1000;\n }\n\n clear(): void {\n this.token = null;\n }\n}\n","import type { ClientCredentialsConfig, TokenResponse } from './types';\n\n/**\n * Fetches a new access token using the OAuth2 Client Credentials flow.\n */\nexport async function fetchClientCredentialsToken(\n config: ClientCredentialsConfig\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'client_credentials',\n client_id: config.clientId,\n client_secret: config.clientSecret,\n });\n\n if (config.scopes && config.scopes.length > 0) {\n body.set('scope', config.scopes.join(' '));\n }\n\n const response = await fetch(config.tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","import type { AuthorizationCodeConfig, TokenResponse } from './types';\n\n// ---------------------------------------------------------------------------\n// PKCE helpers\n// ---------------------------------------------------------------------------\n\n/** Generates a cryptographically random PKCE code verifier (43-128 chars). */\nexport function generateCodeVerifier(): string {\n const array = new Uint8Array(32);\n crypto.getRandomValues(array);\n return base64UrlEncode(array);\n}\n\n/** Derives a PKCE code challenge (S256) from a code verifier. */\nexport async function generateCodeChallenge(verifier: string): Promise<string> {\n const encoder = new TextEncoder();\n const data = encoder.encode(verifier);\n const digest = await crypto.subtle.digest('SHA-256', data);\n return base64UrlEncode(new Uint8Array(digest));\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n const str = String.fromCharCode(...bytes);\n return btoa(str).replace(/\\+/g, '-').replace(/\\//g, '_').replace(/=+$/, '');\n}\n\n// ---------------------------------------------------------------------------\n// Authorization Code flows\n// ---------------------------------------------------------------------------\n\n/**\n * Builds the authorization URL to redirect the user to.\n * Returns the URL and the code verifier (must be stored and passed to exchangeCode).\n */\nexport async function getAuthorizationUrl(\n config: AuthorizationCodeConfig,\n state?: string\n): Promise<{ url: string; codeVerifier: string }> {\n const codeVerifier = generateCodeVerifier();\n const codeChallenge = await generateCodeChallenge(codeVerifier);\n\n const params = new URLSearchParams({\n response_type: 'code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code_challenge: codeChallenge,\n code_challenge_method: 'S256',\n });\n\n if (config.scopes && config.scopes.length > 0) {\n params.set('scope', config.scopes.join(' '));\n }\n\n if (state) {\n params.set('state', state);\n }\n\n return {\n url: `${config.authorizationUrl}?${params.toString()}`,\n codeVerifier,\n };\n}\n\n/**\n * Exchanges an authorization code for tokens.\n */\nexport async function exchangeCode(\n config: AuthorizationCodeConfig,\n code: string,\n codeVerifier: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'authorization_code',\n client_id: config.clientId,\n redirect_uri: config.redirectUri,\n code,\n code_verifier: codeVerifier,\n });\n\n return tokenRequest(config.tokenUrl, body);\n}\n\n/**\n * Refreshes an access token using a refresh token.\n */\nexport async function refreshAccessToken(\n config: AuthorizationCodeConfig,\n refreshToken: string\n): Promise<TokenResponse> {\n const body = new URLSearchParams({\n grant_type: 'refresh_token',\n client_id: config.clientId,\n refresh_token: refreshToken,\n });\n\n return tokenRequest(config.tokenUrl, body);\n}\n\nasync function tokenRequest(\n tokenUrl: string,\n body: URLSearchParams\n): Promise<TokenResponse> {\n const response = await fetch(tokenUrl, {\n method: 'POST',\n headers: { 'Content-Type': 'application/x-www-form-urlencoded' },\n body: body.toString(),\n });\n\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Token request failed: ${response.status} ${response.statusText}${text ? ` — ${text}` : ''}`\n );\n }\n\n return response.json() as Promise<TokenResponse>;\n}\n","import type { AuthConfig, AuthorizationCodeConfig } from './types';\nimport { TokenStore } from './token-store';\nimport { fetchClientCredentialsToken } from './client-credentials';\nimport {\n getAuthorizationUrl as buildAuthorizationUrl,\n exchangeCode,\n refreshAccessToken,\n} from './authorization-code';\n\n/**\n * Centralized OAuth2 authentication manager.\n *\n * Supports:\n * - Client Credentials flow (server-to-server, fully automatic)\n * - Authorization Code + PKCE flow (user-facing applications)\n *\n * @example Client Credentials\n * ```ts\n * const auth = new AuthManager({\n * flow: 'client-credentials',\n * clientId: 'my-id',\n * clientSecret: 'my-secret',\n * tokenUrl: 'https://auth.bcis.co.uk/oauth/token',\n * });\n * const token = await auth.getAccessToken();\n * ```\n *\n * @example Authorization Code\n * ```ts\n * const auth = new AuthManager({\n * flow: 'authorization-code',\n * clientId: 'my-id',\n * tokenUrl: 'https://auth.bcis.co.uk/oauth/token',\n * authorizationUrl: 'https://auth.bcis.co.uk/authorize',\n * redirectUri: 'https://myapp.com/callback',\n * scopes: ['openid', 'profile'],\n * });\n *\n * // Step 1: redirect user\n * const { url, codeVerifier } = await auth.getAuthorizationUrl();\n * // store codeVerifier in session, redirect user to url\n *\n * // Step 2: on callback\n * await auth.handleCallback(code, codeVerifier);\n *\n * // Step 3: use the SDK\n * const token = await auth.getAccessToken();\n * ```\n */\nexport class AuthManager {\n private readonly store = new TokenStore();\n /** Pending token fetch promise to prevent concurrent requests */\n private inflight: Promise<void> | null = null;\n\n constructor(private readonly config: AuthConfig) {}\n\n /**\n * Returns a valid access token, fetching or refreshing as needed.\n * For Client Credentials flow this is fully automatic.\n * For Authorization Code flow, `handleCallback` must have been called first.\n */\n async getAccessToken(): Promise<string> {\n if (!this.store.isExpired()) {\n return this.store.getAccessToken()!;\n }\n\n if (this.inflight) {\n await this.inflight;\n return this.store.getAccessToken()!;\n }\n\n this.inflight = this.refresh();\n try {\n await this.inflight;\n } finally {\n this.inflight = null;\n }\n\n const token = this.store.getAccessToken();\n if (!token) throw new Error('Failed to obtain access token');\n return token;\n }\n\n /**\n * Authorization Code flow only.\n * Builds and returns the authorization URL to redirect the user to.\n * The returned `codeVerifier` must be persisted (e.g. in session storage)\n * and passed to `handleCallback`.\n */\n async getAuthorizationUrl(state?: string): Promise<{ url: string; codeVerifier: string }> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('getAuthorizationUrl is only available for authorization-code flow');\n }\n return buildAuthorizationUrl(this.config, state);\n }\n\n /**\n * Authorization Code flow only.\n * Exchanges the authorization code (from the redirect callback) for tokens\n * and stores them internally.\n */\n async handleCallback(code: string, codeVerifier: string): Promise<void> {\n if (this.config.flow !== 'authorization-code') {\n throw new Error('handleCallback is only available for authorization-code flow');\n }\n const tokenResponse = await exchangeCode(this.config, code, codeVerifier);\n this.store.store(tokenResponse);\n }\n\n /** Clears all stored tokens. */\n clearTokens(): void {\n this.store.clear();\n }\n\n private async refresh(): Promise<void> {\n if (this.config.flow === 'client-credentials') {\n const tokenResponse = await fetchClientCredentialsToken(this.config);\n this.store.store(tokenResponse);\n return;\n }\n\n // Authorization Code flow: try refresh token first, else throw\n const refreshToken = this.store.getRefreshToken();\n if (refreshToken) {\n const tokenResponse = await refreshAccessToken(\n this.config as AuthorizationCodeConfig,\n refreshToken\n );\n this.store.store(tokenResponse);\n return;\n }\n\n throw new Error(\n 'No valid token available. Call getAuthorizationUrl() and handleCallback() first.'\n );\n }\n}\n","import type { AuthManager } from '../auth/auth-manager';\n\n/** Thrown when an API response is not 2xx. */\nexport class BcisApiError extends Error {\n constructor(\n public readonly status: number,\n public readonly statusText: string,\n public readonly body: unknown\n ) {\n super(`BCIS API error ${status} ${statusText}`);\n this.name = 'BcisApiError';\n }\n}\n\n/**\n * Thin fetch wrapper that:\n * - Injects the Authorization: Bearer header from AuthManager\n * - Serialises query parameters (including arrays as repeated params)\n * - Throws BcisApiError on non-2xx responses\n */\nexport class FetchClient {\n constructor(private readonly auth: AuthManager) {}\n\n async get<T>(\n baseUrl: string,\n path: string,\n params: Record<string, unknown> = {}\n ): Promise<T> {\n const token = await this.auth.getAccessToken();\n const url = new URL(baseUrl + path);\n\n for (const [key, value] of Object.entries(params)) {\n if (value === undefined || value === null) continue;\n\n if (Array.isArray(value)) {\n for (const item of value) {\n url.searchParams.append(key, String(item));\n }\n } else {\n url.searchParams.set(key, String(value));\n }\n }\n\n const response = await fetch(url.toString(), {\n method: 'GET',\n headers: {\n Authorization: `Bearer ${token}`,\n Accept: 'application/json',\n },\n });\n\n if (!response.ok) {\n let body: unknown;\n try {\n body = await response.json();\n } catch {\n body = await response.text();\n }\n throw new BcisApiError(response.status, response.statusText, body);\n }\n\n return response.json() as Promise<T>;\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { AbpResponseDto, IndicesResponseDto, TpsResponseDto, CodesResponseDto } from '../types/core-api.types';\n\n// --- Parameter interfaces ---\n\nexport interface AbpRetrieveParams {\n /** When true, returns additional data for graph plotting. Default false. */\n 'include-data-for-graph'?: boolean;\n /** When true, includes sub-divided categories (e.g., size bands) in results. Default false. */\n 'include-subclasses'?: boolean;\n /** A comma-separated list of building function codes used to filter study results. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'building-function': string[];\n /** A list of type of work codes to filter the results by, the example contains all valid codes. */\n 'type-of-work': string[];\n /** A six-character code identifying the BCIS study */\n 'abp-study': 'ABPBUI' | 'ABPFUN' | 'ABPGRP' | 'ABPEM2' | 'ABPEUR' | 'ABPEXT';\n}\n\nexport interface IndicesRetrieveParams {\n /** Restricts the index series by year e.g. `1985` or description `1985 mean = 100`. Ignored if a series number is provided. Descriptions must match text exactly, case-insensitive but including spaces. */\n 'base-of-series'?: string;\n /** Restricts index series by `regularity` (`monthly`, `quarterly`, `annual`). Ignored if a series number is used. Defaults to `quarterly`, then `monthly`, then `annual`. */\n regularity?: string[];\n /** Restricts index figures up to a specific month `yyyy-mm`, or leave blank for latest available. */\n 'end-date'?: string;\n /** Restricts index figures to a specific month `yyyy-mm`, or leave blank for earliest available. */\n 'start-date'?: string;\n /** Comma-delimited list of short names (e.g. `BCISTPI:AllIn`) or series numbers. [See the Codes Update API](/docs/bcis-grace-svc-core-apis/1a5fdc770c00d-codes-update). */\n 'series-identification': string[];\n}\n\nexport interface TpsRetrieveParams {\n /** Supports suffixes to filter or refine the study data: - Level Filters: - `:region`, `:county`, `:district` - Example: `location2000:region` (regional indices), `location2000:county,district` (county and district indices) - Postcode Filter: - `:postcode:<POSTCODE>` (no spaces) - Example: `location2000:postcode:SW1P3AD` - Cannot be combined with level filters. - Effective Date Filter: - `:EffectiveDate:<YYYYQn>` - Example: `location2000:EffectiveDate:2015Q2` - Can be combined with postcode or level filters. - Outcode List: - `:outcode` - Example: `location2000:outcode` - Not supported for 1980 boundaries or with EffectiveDate. `short-tps-name` is not case sensitive. For available studies, use the `codesUpdate` web service with `codeType=shortTPSName`. */\n 'short-tps-name': string;\n}\n\nexport interface CodesUpdateParams {\n /** A date in `yyyy-mm-dd` format. Returns only codes added or modified since this date. Not supported for all code types. Leave blank to return all codes. */\n 'if-changed-since'?: string;\n /** A version string to select relevant code tables. */\n version?: string;\n /** A string to select the code list required. The supported values are: - `seriesIdentification`: All regularity names (for `/indices-retrieve`) - `shortTPSName`: Tender Price Studies - short names (for `/tps-retrieve`) - `ABPStudy`: Average building prices study codes (for `/abp-retrieve`) - `BuildingFunction`: List of building function codes (for `/abp-retrieve`, and `/analyses-search`) - `BuildingFunction:Categories`: List of building function categories - `BuildingFunction:[1-9]`: List of building function codes for the category specified after the colon - `BuildingFunction:Duration`: List of building function codes for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:Categories`: List of building function categories for duration calculator (for `Duration Model Calculate Api`) - `BuildingFunction:Duration:[1-9]`: List of building function codes for duration calculator for category specified after the colon (for `Duration Model Calculate Api`) - `BuildingFunction:ABP`: List of building function codes for average building prices study where results are available to the user (for `/abp-retrieve`) - `SimplifiedTypeOfWork`: List of shorter type of work codes (for `/abp-retrieve`) The list of supported code types may be extended in the future. */\n 'code-type': 'shortTPSName' | 'ABPStudy' | 'BuildingFunction' | 'BuildingFunction:Categories' | 'BuildingFunction:[1-9]' | 'BuildingFunction:Duration' | 'BuildingFunction:Duration:Categories' | 'BuildingFunction:Duration:[1-9]' | 'BuildingFunction:ABP' | 'SimplifiedTypeOfWork';\n}\n\n// --- Client ---\n\nexport class CoreApiClient {\n private readonly client: FetchClient;\n\n constructor(auth: AuthManager) {\n this.client = new FetchClient(auth);\n }\n\n /** abp-retrieve */\n async abpRetrieve(params: AbpRetrieveParams): Promise<AbpResponseDto> {\n return this.client.get<AbpResponseDto>('https://api.bcis.co.uk/core-apis', '/abp-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** indices-retrieve */\n async indicesRetrieve(params: IndicesRetrieveParams): Promise<IndicesResponseDto> {\n return this.client.get<IndicesResponseDto>('https://api.bcis.co.uk/core-apis', '/indices-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** tps-retrieve */\n async tpsRetrieve(params: TpsRetrieveParams): Promise<TpsResponseDto> {\n return this.client.get<TpsResponseDto>('https://api.bcis.co.uk/core-apis', '/tps-retrieve', params as unknown as Record<string, unknown>);\n }\n\n /** codes-update */\n async codesUpdate(params: CodesUpdateParams): Promise<CodesResponseDto> {\n return this.client.get<CodesResponseDto>('https://api.bcis.co.uk/core-apis', '/codes-update', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { CalculationResponse, UsageResponse } from '../types/residential-rebuild.types';\n\n// --- Parameter interfaces ---\n\nexport interface CalculateParams {\n /** Postcode of the property */\n postCode: string;\n /** Type of the property */\n type: string;\n /** Number of storeys in the property */\n storeys: string;\n /** Style of the property: detached, terraced, etc */\n style: string;\n /** Type of the walls of the property */\n wallType: string;\n /** Type of the roof of the property */\n roofType?: string;\n /** Year the property was built */\n yearBuilt: number;\n /** Number of flats */\n noOfFlats?: number;\n /** Area of the property in sq.m. */\n area?: number;\n /** Number of rooms in the property */\n noOfRooms?: number;\n /** Number of bedrooms in the property */\n noOfBedrooms?: number;\n /** Number of garage spaces in the property */\n noOfGarageSpaces?: number;\n /** Number of bathrooms in the property */\n noOfBathrooms?: number;\n /** Special features of the property, Must be blank, or a comma delimited list containing one or more of 'cellar' or 'noexternals' */\n specialFeatures?: string;\n}\n\nexport interface ReportUsageParams {\n /** First month of the usage report */\n startMonth?: string;\n /** Last month of the usage report */\n endMonth?: string;\n}\n\n// --- Client ---\n\nexport class ResidentialRebuildClient {\n private readonly client: FetchClient;\n\n constructor(auth: AuthManager) {\n this.client = new FetchClient(auth);\n }\n\n /** rbls-calculate */\n async calculate(params: CalculateParams): Promise<CalculationResponse> {\n return this.client.get<CalculationResponse>('https://api.bcis.co.uk/residential-rebuild-calculator', '/rbls-calculate', params as unknown as Record<string, unknown>);\n }\n\n /** rbls-report-use */\n async reportUsage(params: ReportUsageParams): Promise<UsageResponse> {\n return this.client.get<UsageResponse>('https://api.bcis.co.uk/residential-rebuild-calculator', '/rbls-report-use', params as unknown as Record<string, unknown>);\n }\n}\n","// This file is auto-generated. Do not edit manually.\n// Re-run `npm run generate` to regenerate.\n\nimport { FetchClient } from '../http/fetch-client';\nimport type { AuthManager } from '../auth/auth-manager';\nimport type { EditionsDto, GetRateResponseDto, GetResourceResponseDto, GetBuildUpResponseDto } from '../types/schedule-of-rates.types';\n\n// --- Parameter interfaces ---\n\nexport interface GetRatesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetResourcesParams {\n /** node id, returned data are for the selected node */\n 'selected-node-id'?: string;\n /** filter term, returned nodes contain the text somewhere in that branch */\n 'filter-text'?: string;\n /** id obtained from get-books-edition */\n 'edition-id': string;\n}\n\nexport interface GetBuildUpParams {\n /** Id as returned from GetRates or GetResources */\n 'entity-id': string;\n}\n\n// --- Client ---\n\nexport class ScheduleOfRatesClient {\n private readonly client: FetchClient;\n\n constructor(auth: AuthManager) {\n this.client = new FetchClient(auth);\n }\n\n /** Lists books and editions available to user */\n async getBooksEdition(): Promise<EditionsDto> {\n return this.client.get<EditionsDto>('https://api.bcis.co.uk/schedule-of-rates', '/get-books-edition', {});\n }\n\n /** Lists matching rates */\n async getRates(params: GetRatesParams): Promise<GetRateResponseDto> {\n return this.client.get<GetRateResponseDto>('https://api.bcis.co.uk/schedule-of-rates', '/get-rates', params as unknown as Record<string, unknown>);\n }\n\n /** Lists matching resources */\n async getResources(params: GetResourcesParams): Promise<GetResourceResponseDto> {\n return this.client.get<GetResourceResponseDto>('https://api.bcis.co.uk/schedule-of-rates', '/get-resources', params as unknown as Record<string, unknown>);\n }\n\n /** Lists components of a rate or buildUp */\n async getBuildUp(params: GetBuildUpParams): Promise<GetBuildUpResponseDto> {\n return this.client.get<GetBuildUpResponseDto>('https://api.bcis.co.uk/schedule-of-rates', '/get-build-up', params as unknown as Record<string, unknown>);\n }\n}\n"]}
package/package.json CHANGED
@@ -1,23 +1,39 @@
1
1
  {
2
2
  "name": "@bcis/sdk",
3
- "version": "0.0.1",
4
- "description": "",
5
- "homepage": "https://github.com/BCIS-Engineering/sdk-typescript#readme",
6
- "bugs": {
7
- "url": "https://github.com/BCIS-Engineering/sdk-typescript/issues"
8
- },
9
- "repository": {
10
- "type": "git",
11
- "url": "git+https://github.com/BCIS-Engineering/sdk-typescript.git"
3
+ "version": "0.1.1",
4
+ "description": "Type-safe TypeScript SDK for BCIS APIs",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/index.mjs",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "import": {
11
+ "types": "./dist/index.d.mts",
12
+ "default": "./dist/index.mjs"
13
+ },
14
+ "require": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ }
18
+ }
12
19
  },
20
+ "files": ["dist"],
13
21
  "scripts": {
14
- "test": "echo \"Warning: no test specified\" && exit 0"
22
+ "build": "tsup",
23
+ "typecheck": "tsc --noEmit",
24
+ "test": "vitest run",
25
+ "test:watch": "vitest"
15
26
  },
16
- "license": "Apache-2.0",
17
- "author": "",
18
- "type": "module",
19
- "main": "index.js",
27
+ "keywords": ["bcis", "construction", "cost", "sdk", "typescript"],
28
+ "license": "Unlicensed",
20
29
  "publishConfig": {
30
+ "registry": "https://registry.npmjs.org/",
21
31
  "access": "public"
32
+ },
33
+ "dependencies": {},
34
+ "devDependencies": {
35
+ "tsup": "^8.3.5",
36
+ "typescript": "^5.7.3",
37
+ "vitest": "^2.1.0"
22
38
  }
23
- }
39
+ }
@@ -1,31 +0,0 @@
1
- # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
2
- # For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages
3
-
4
- name: Node.js Package
5
-
6
- on:
7
- release:
8
- types: [created]
9
-
10
- jobs:
11
- build:
12
- runs-on: ubuntu-latest
13
- steps:
14
- - uses: actions/checkout@v4
15
- - uses: actions/setup-node@v4
16
- with:
17
- node-version: 20
18
- - run: npm test
19
-
20
- publish-npm:
21
- needs: build
22
- runs-on: ubuntu-latest
23
- steps:
24
- - uses: actions/checkout@v4
25
- - uses: actions/setup-node@v4
26
- with:
27
- node-version: 20
28
- registry-url: https://registry.npmjs.org/
29
- - run: npm publish
30
- env:
31
- NODE_AUTH_TOKEN: ${{secrets.npm_token}}
@@ -1,30 +0,0 @@
1
- name: release
2
-
3
- on:
4
- push:
5
- branches:
6
- - main
7
- tags:
8
- - 'v*.*.*'
9
-
10
- jobs:
11
-
12
- # Do something
13
-
14
- deploy:
15
- runs-on: ubuntu-latest
16
- steps:
17
- - name: Checkout code
18
- uses: actions/checkout@v4
19
- - name: Create Release
20
- id: create_release
21
- uses: comnoco/create-release@v2
22
- env:
23
- GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This token is provided by Actions, you do not need to create your own token
24
- with:
25
- tag_name: ${{ github.ref }}
26
- release_name: Release ${{ github.ref }}
27
- body: |
28
- Auto Release for ${{ github.ref }}
29
- draft: false
30
- prerelease: false
@@ -1,17 +0,0 @@
1
- name: release
2
-
3
- on:
4
- push:
5
- branches:
6
- - main
7
-
8
- jobs:
9
- tag:
10
- runs-on: ubuntu-latest
11
- steps:
12
- - uses: actions/checkout@master
13
- - name: Bump version and push tag
14
- uses: laputansoft/github-tag-action@v4.6
15
- with:
16
- github_token: ${{ secrets.GITHUB_TOKEN }}
17
- tag: 0.0.1
package/LICENSE DELETED
@@ -1,201 +0,0 @@
1
- Apache License
2
- Version 2.0, January 2004
3
- http://www.apache.org/licenses/
4
-
5
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
-
7
- 1. Definitions.
8
-
9
- "License" shall mean the terms and conditions for use, reproduction,
10
- and distribution as defined by Sections 1 through 9 of this document.
11
-
12
- "Licensor" shall mean the copyright owner or entity authorized by
13
- the copyright owner that is granting the License.
14
-
15
- "Legal Entity" shall mean the union of the acting entity and all
16
- other entities that control, are controlled by, or are under common
17
- control with that entity. For the purposes of this definition,
18
- "control" means (i) the power, direct or indirect, to cause the
19
- direction or management of such entity, whether by contract or
20
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
- outstanding shares, or (iii) beneficial ownership of such entity.
22
-
23
- "You" (or "Your") shall mean an individual or Legal Entity
24
- exercising permissions granted by this License.
25
-
26
- "Source" form shall mean the preferred form for making modifications,
27
- including but not limited to software source code, documentation
28
- source, and configuration files.
29
-
30
- "Object" form shall mean any form resulting from mechanical
31
- transformation or translation of a Source form, including but
32
- not limited to compiled object code, generated documentation,
33
- and conversions to other media types.
34
-
35
- "Work" shall mean the work of authorship, whether in Source or
36
- Object form, made available under the License, as indicated by a
37
- copyright notice that is included in or attached to the work
38
- (an example is provided in the Appendix below).
39
-
40
- "Derivative Works" shall mean any work, whether in Source or Object
41
- form, that is based on (or derived from) the Work and for which the
42
- editorial revisions, annotations, elaborations, or other modifications
43
- represent, as a whole, an original work of authorship. For the purposes
44
- of this License, Derivative Works shall not include works that remain
45
- separable from, or merely link (or bind by name) to the interfaces of,
46
- the Work and Derivative Works thereof.
47
-
48
- "Contribution" shall mean any work of authorship, including
49
- the original version of the Work and any modifications or additions
50
- to that Work or Derivative Works thereof, that is intentionally
51
- submitted to Licensor for inclusion in the Work by the copyright owner
52
- or by an individual or Legal Entity authorized to submit on behalf of
53
- the copyright owner. For the purposes of this definition, "submitted"
54
- means any form of electronic, verbal, or written communication sent
55
- to the Licensor or its representatives, including but not limited to
56
- communication on electronic mailing lists, source code control systems,
57
- and issue tracking systems that are managed by, or on behalf of, the
58
- Licensor for the purpose of discussing and improving the Work, but
59
- excluding communication that is conspicuously marked or otherwise
60
- designated in writing by the copyright owner as "Not a Contribution."
61
-
62
- "Contributor" shall mean Licensor and any individual or Legal Entity
63
- on behalf of whom a Contribution has been received by Licensor and
64
- subsequently incorporated within the Work.
65
-
66
- 2. Grant of Copyright License. Subject to the terms and conditions of
67
- this License, each Contributor hereby grants to You a perpetual,
68
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
- copyright license to reproduce, prepare Derivative Works of,
70
- publicly display, publicly perform, sublicense, and distribute the
71
- Work and such Derivative Works in Source or Object form.
72
-
73
- 3. Grant of Patent License. Subject to the terms and conditions of
74
- this License, each Contributor hereby grants to You a perpetual,
75
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
- (except as stated in this section) patent license to make, have made,
77
- use, offer to sell, sell, import, and otherwise transfer the Work,
78
- where such license applies only to those patent claims licensable
79
- by such Contributor that are necessarily infringed by their
80
- Contribution(s) alone or by combination of their Contribution(s)
81
- with the Work to which such Contribution(s) was submitted. If You
82
- institute patent litigation against any entity (including a
83
- cross-claim or counterclaim in a lawsuit) alleging that the Work
84
- or a Contribution incorporated within the Work constitutes direct
85
- or contributory patent infringement, then any patent licenses
86
- granted to You under this License for that Work shall terminate
87
- as of the date such litigation is filed.
88
-
89
- 4. Redistribution. You may reproduce and distribute copies of the
90
- Work or Derivative Works thereof in any medium, with or without
91
- modifications, and in Source or Object form, provided that You
92
- meet the following conditions:
93
-
94
- (a) You must give any other recipients of the Work or
95
- Derivative Works a copy of this License; and
96
-
97
- (b) You must cause any modified files to carry prominent notices
98
- stating that You changed the files; and
99
-
100
- (c) You must retain, in the Source form of any Derivative Works
101
- that You distribute, all copyright, patent, trademark, and
102
- attribution notices from the Source form of the Work,
103
- excluding those notices that do not pertain to any part of
104
- the Derivative Works; and
105
-
106
- (d) If the Work includes a "NOTICE" text file as part of its
107
- distribution, then any Derivative Works that You distribute must
108
- include a readable copy of the attribution notices contained
109
- within such NOTICE file, excluding those notices that do not
110
- pertain to any part of the Derivative Works, in at least one
111
- of the following places: within a NOTICE text file distributed
112
- as part of the Derivative Works; within the Source form or
113
- documentation, if provided along with the Derivative Works; or,
114
- within a display generated by the Derivative Works, if and
115
- wherever such third-party notices normally appear. The contents
116
- of the NOTICE file are for informational purposes only and
117
- do not modify the License. You may add Your own attribution
118
- notices within Derivative Works that You distribute, alongside
119
- or as an addendum to the NOTICE text from the Work, provided
120
- that such additional attribution notices cannot be construed
121
- as modifying the License.
122
-
123
- You may add Your own copyright statement to Your modifications and
124
- may provide additional or different license terms and conditions
125
- for use, reproduction, or distribution of Your modifications, or
126
- for any such Derivative Works as a whole, provided Your use,
127
- reproduction, and distribution of the Work otherwise complies with
128
- the conditions stated in this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work
132
- by You to the Licensor shall be under the terms and conditions of
133
- this License, without any additional terms or conditions.
134
- Notwithstanding the above, nothing herein shall supersede or modify
135
- the terms of any separate license agreement you may have executed
136
- with Licensor regarding such Contributions.
137
-
138
- 6. Trademarks. This License does not grant permission to use the trade
139
- names, trademarks, service marks, or product names of the Licensor,
140
- except as required for reasonable and customary use in describing the
141
- origin of the Work and reproducing the content of the NOTICE file.
142
-
143
- 7. Disclaimer of Warranty. Unless required by applicable law or
144
- agreed to in writing, Licensor provides the Work (and each
145
- Contributor provides its Contributions) on an "AS IS" BASIS,
146
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
- implied, including, without limitation, any warranties or conditions
148
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
- PARTICULAR PURPOSE. You are solely responsible for determining the
150
- appropriateness of using or redistributing the Work and assume any
151
- risks associated with Your exercise of permissions under this License.
152
-
153
- 8. Limitation of Liability. In no event and under no legal theory,
154
- whether in tort (including negligence), contract, or otherwise,
155
- unless required by applicable law (such as deliberate and grossly
156
- negligent acts) or agreed to in writing, shall any Contributor be
157
- liable to You for damages, including any direct, indirect, special,
158
- incidental, or consequential damages of any character arising as a
159
- result of this License or out of the use or inability to use the
160
- Work (including but not limited to damages for loss of goodwill,
161
- work stoppage, computer failure or malfunction, or any and all
162
- other commercial damages or losses), even if such Contributor
163
- has been advised of the possibility of such damages.
164
-
165
- 9. Accepting Warranty or Additional Liability. While redistributing
166
- the Work or Derivative Works thereof, You may choose to offer,
167
- and charge a fee for, acceptance of support, warranty, indemnity,
168
- or other liability obligations and/or rights consistent with this
169
- License. However, in accepting such obligations, You may act only
170
- on Your own behalf and on Your sole responsibility, not on behalf
171
- of any other Contributor, and only if You agree to indemnify,
172
- defend, and hold each Contributor harmless for any liability
173
- incurred by, or claims asserted against, such Contributor by reason
174
- of your accepting any such warranty or additional liability.
175
-
176
- END OF TERMS AND CONDITIONS
177
-
178
- APPENDIX: How to apply the Apache License to your work.
179
-
180
- To apply the Apache License to your work, attach the following
181
- boilerplate notice, with the fields enclosed by brackets "[]"
182
- replaced with your own identifying information. (Don't include
183
- the brackets!) The text should be enclosed in the appropriate
184
- comment syntax for the file format. We also recommend that a
185
- file or class name and description of purpose be included on the
186
- same "printed page" as the copyright notice for easier
187
- identification within third-party archives.
188
-
189
- Copyright [yyyy] [name of copyright owner]
190
-
191
- Licensed under the Apache License, Version 2.0 (the "License");
192
- you may not use this file except in compliance with the License.
193
- You may obtain a copy of the License at
194
-
195
- http://www.apache.org/licenses/LICENSE-2.0
196
-
197
- Unless required by applicable law or agreed to in writing, software
198
- distributed under the License is distributed on an "AS IS" BASIS,
199
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
- See the License for the specific language governing permissions and
201
- limitations under the License.
package/index.js DELETED
@@ -1,5 +0,0 @@
1
- const greet = (name) => {
2
- return `Hello, ${name}!`;
3
- }
4
-
5
- export greet