@healthier-business/hub-sdk 0.2.0 → 0.4.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 +48 -0
- package/dist/cjs/browser/index.d.ts +2 -2
- package/dist/cjs/browser/mount.d.ts +2 -0
- package/dist/cjs/browser/mount.js +3 -0
- package/dist/cjs/core/errors.d.ts +43 -2
- package/dist/cjs/core/errors.js +92 -5
- package/dist/cjs/core/http.js +1 -1
- package/dist/cjs/embed/protocol.d.ts +6 -1
- package/dist/cjs/generated/operations.js +6 -0
- package/dist/cjs/generated/resources.d.ts +13 -1
- package/dist/cjs/generated/types.d.ts +32 -2
- package/dist/cjs/index.d.ts +1 -1
- package/dist/cjs/index.js +6 -1
- package/dist/cjs/version.d.ts +1 -1
- package/dist/cjs/version.js +1 -1
- package/dist/cjs/webhooks.d.ts +6 -0
- package/dist/cjs/webhooks.js +6 -0
- package/dist/esm/browser/index.d.ts +2 -2
- package/dist/esm/browser/mount.d.ts +2 -0
- package/dist/esm/browser/mount.js +3 -0
- package/dist/esm/core/errors.d.ts +43 -2
- package/dist/esm/core/errors.js +87 -4
- package/dist/esm/core/http.js +1 -1
- package/dist/esm/embed/protocol.d.ts +6 -1
- package/dist/esm/generated/operations.js +6 -0
- package/dist/esm/generated/resources.d.ts +13 -1
- package/dist/esm/generated/types.d.ts +32 -2
- package/dist/esm/index.d.ts +1 -1
- package/dist/esm/index.js +1 -1
- package/dist/esm/version.d.ts +1 -1
- package/dist/esm/version.js +1 -1
- package/dist/esm/webhooks.d.ts +6 -0
- package/dist/esm/webhooks.js +6 -0
- package/dist/iife/hb-embed.min.js +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -37,6 +37,7 @@ That is all the setup there is. No token calls, no refresh logic, no storage.
|
|
|
37
37
|
- [Calling the API](#calling-the-api)
|
|
38
38
|
- [Pagination](#pagination)
|
|
39
39
|
- [Errors](#errors)
|
|
40
|
+
- [Approval for sensitive areas](#approval-for-sensitive-areas)
|
|
40
41
|
- [Retries, timeouts and idempotency](#retries-timeouts-and-idempotency)
|
|
41
42
|
- [Files](#files)
|
|
42
43
|
- [Webhooks](#webhooks)
|
|
@@ -111,6 +112,8 @@ Everything the Hub refuses is an `ApiError` with `status`, `code` (the stable `s
|
|
|
111
112
|
| --- | --- |
|
|
112
113
|
| `ValidationError` (422) | `error.fields` maps each field to its messages. Nothing was changed. |
|
|
113
114
|
| `PermissionError` (403) | `insufficient_scope`, `portal_unavailable`, `key_inactive`, `ip_not_allowed`. |
|
|
115
|
+
| `ApiAccessError` (403, a `PermissionError`) | `api_access_not_approved`, `api_access_pending`, `api_access_rejected`, `api_access_revoked`: the area needs the Hub's manual approval. `error.areas`, `error.docsUrl`, `error.state`. Not retried. See [Approval for sensitive areas](#approval-for-sensitive-areas). |
|
|
116
|
+
| `WebhookEventsNotApprovedError` (403, a `PermissionError`) | `webhook_events_not_approved`: an endpoint asked for events of an area you are not approved for. `error.events`, `error.areas`. |
|
|
114
117
|
| `AuthenticationError` (401) | The key is wrong, or was regenerated. |
|
|
115
118
|
| `NotFoundError` (404), `ConflictError` (409) | |
|
|
116
119
|
| `EmbedAccessError` (409, a `ConflictError`) | An embed session was refused because the candidate's access is not in place. `error.access` is `{ state, payer, next }`. See [Access, payment and renewal](#access-payment-and-renewal). |
|
|
@@ -130,6 +133,49 @@ try {
|
|
|
130
133
|
}
|
|
131
134
|
```
|
|
132
135
|
|
|
136
|
+
## Approval for sensitive areas
|
|
137
|
+
|
|
138
|
+
Occupational Health and DBS & Right To Work (by default; Hub staff choose the list) hold health and criminal record information. With a **live** key, their API calls and their webhook events work only after a member of the Hub team has approved your organisation. A user of your organisation asks for it once, in the Hub under **Developer > API access**; you are emailed the decision. The [sandbox](#sandbox) is always open. The full rules are in the [API access approval guide](https://dev.hbcompliance.co.uk/docs/api-access-approval).
|
|
139
|
+
|
|
140
|
+
**Check where you stand** (works with any valid key, no scope needed):
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
const { data } = await hb.account.apiAccess.get();
|
|
144
|
+
for (const a of data.filter((x) => x.sensitive)) {
|
|
145
|
+
console.log(a.label, a.status); // not_requested | pending | approved | rejected | revoked
|
|
146
|
+
}
|
|
147
|
+
```
|
|
148
|
+
|
|
149
|
+
`status` is `not_required` (the area is open, always the case in the sandbox), `not_requested`, `pending`, `approved`, `rejected` or `revoked`. Read the list instead of hard-coding the areas. The reason for a rejection or a withdrawal is shown in the Hub and in the email, never in the API.
|
|
150
|
+
|
|
151
|
+
**Catch the refusals.** A call to an area you are not approved for answers `403` and the SDK throws an `ApiAccessError`. It is never retried: show a message and fix the approval.
|
|
152
|
+
|
|
153
|
+
```ts
|
|
154
|
+
import { ApiAccessError, WebhookEventsNotApprovedError } from '@healthier-business/hub-sdk';
|
|
155
|
+
|
|
156
|
+
try {
|
|
157
|
+
await hb.occupationalHealth.requests.list();
|
|
158
|
+
} catch (e) {
|
|
159
|
+
if (e instanceof ApiAccessError) {
|
|
160
|
+
// e.code: api_access_not_approved | api_access_pending | api_access_rejected | api_access_revoked
|
|
161
|
+
// e.state: 'not_requested' | 'pending' | 'rejected' | 'revoked'
|
|
162
|
+
console.warn(`${e.areas.join(', ')} needs approval (${e.state}). ${e.docsUrl}`);
|
|
163
|
+
} else if (e instanceof WebhookEventsNotApprovedError) {
|
|
164
|
+
console.warn('Remove these events or get approved first:', e.events);
|
|
165
|
+
} else throw e;
|
|
166
|
+
}
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
`isApiAccessError(e)` and `isWebhookEventsNotApprovedError(e)` do the same checks as type guards, and `e.hint` is a plain-words next step.
|
|
170
|
+
|
|
171
|
+
**Webhooks.** `WEBHOOK_EVENT_TYPES` lists every event type, but events of an area that needs approval (`occupational-health.*`, `dbs-rtw.*` by default) are only sent to an approved organisation, are not queued and are not replayed after approval (fetch what you missed from the API). Creating or updating an endpoint with such events before approval throws `WebhookEventsNotApprovedError`. Create those endpoints once `hb.account.apiAccess.get()` shows `approved`.
|
|
172
|
+
|
|
173
|
+
**Try the refusals in the sandbox.** Send the header `X-HB-Simulate-Access` with `not_approved`, `pending`, `rejected` or `revoked` on a sandbox call to get the matching error:
|
|
174
|
+
|
|
175
|
+
```ts
|
|
176
|
+
await hb.occupationalHealth.requests.list({}, { headers: { 'X-HB-Simulate-Access': 'pending' } });
|
|
177
|
+
```
|
|
178
|
+
|
|
133
179
|
## Retries, timeouts and idempotency
|
|
134
180
|
|
|
135
181
|
- Reads and deletes are retried on network errors, `429`, `502`, `503` and `504` (twice by default, with exponential backoff and jitter). A `429` waits for `Retry-After` (or the rate-limit reset) when it is 30 seconds or less, otherwise the error is raised straight away.
|
|
@@ -243,6 +289,7 @@ Every event below is sent by the Hub frame. The callbacks (`onProgress`, `onComp
|
|
|
243
289
|
| `completed` | The learner finished the course. Final. | `{ courseId }`: the Online Training course id of the session. |
|
|
244
290
|
| `passed` / `failed` | The learner submitted the test. Final. | `{ score, passMark }`: both percentages, `score` with one decimal. The frame does not say how many attempts are left. |
|
|
245
291
|
| `submitted` | The OH form was submitted. Final. | `{ requestId }`: the numeric OH request id. |
|
|
292
|
+
| `test-requested` | **Course only.** The learner pressed a Take test button in a lesson. Not final: the course session stays open. Open the test with `createTestSession` for the same `courseId`. Sent by the browser, so use it to change the screen, not to decide anything. | `{ courseId, testId }`: the Online Training course id of the session, and the Hub test id. |
|
|
246
293
|
| `terms-accepted` | The candidate accepted the Hub terms on the first screen of the frame. Not final: the content follows. | `{ version, acceptedAt }`: the terms version and an ISO 8601 time. |
|
|
247
294
|
| `error` | The frame could not show the session, or a call was refused after it started. | `{ code }`, plus a plain-words `message` added by the SDK, and `details` (`{ state, payer, next }`) for the four access codes. See [Troubleshooting](#troubleshooting). |
|
|
248
295
|
| `token-expiring` | About 2 minutes before the frame's access ends. The SDK renews it for you; you only see the event. | `{ expires_at }`: ISO 8601. |
|
|
@@ -318,6 +365,7 @@ Errors from creating or refreshing a session (these are `ApiError`s; `error.hint
|
|
|
318
365
|
| `409 session_finished` | The session is complete. | Create a new session. |
|
|
319
366
|
| `410 session_expired` | 60 minutes passed without a refresh, or 12 hours in all. (`GoneError`) | Create a new session. |
|
|
320
367
|
| `403 insufficient_scope` | The key lacks `online-training:embed:create` or `occupational-health:embed:create`. | Add the scope on the Developer page. |
|
|
368
|
+
| `403 api_access_*` | An OH embed session needs the Hub's approval for Occupational Health (live keys). | See [Approval for sensitive areas](#approval-for-sensitive-areas). |
|
|
321
369
|
|
|
322
370
|
The `error` event of `mount` (what the frame or the SDK reports; `embedErrorHint(code)` returns the text):
|
|
323
371
|
|
|
@@ -4,6 +4,6 @@ export { cleanAccessDetails, EMBED_ACCESS_CODES, embedErrorHint, isEmbedSession,
|
|
|
4
4
|
/** `HealthierBusiness.mount(element, options)` for the browser. It holds no API key and cannot make API calls. */
|
|
5
5
|
export declare const HealthierBusiness: {
|
|
6
6
|
readonly mount: typeof mount;
|
|
7
|
-
readonly version: "0.
|
|
7
|
+
readonly version: "0.4.0";
|
|
8
8
|
};
|
|
9
|
-
export declare const version = "0.
|
|
9
|
+
export declare const version = "0.4.0";
|
|
@@ -36,6 +36,8 @@ export interface MountOptions {
|
|
|
36
36
|
onPassed?: (data: EmbedEventMap['passed']) => void;
|
|
37
37
|
onFailed?: (data: EmbedEventMap['failed']) => void;
|
|
38
38
|
onSubmitted?: (data: EmbedEventMap['submitted']) => void;
|
|
39
|
+
/** The learner pressed a Take test button in a lesson: open that course's test (`createTestSession` with the same `courseId`). */
|
|
40
|
+
onTestRequested?: (data: EmbedEventMap['test-requested']) => void;
|
|
39
41
|
/** The candidate accepted the Hub terms in the frame. */
|
|
40
42
|
onTermsAccepted?: (data: EmbedEventMap['terms-accepted']) => void;
|
|
41
43
|
onError?: (error: EmbedEventMap['error']) => void;
|
|
@@ -30,13 +30,17 @@ export declare class ApiError extends HubError {
|
|
|
30
30
|
readonly requestId: string | undefined;
|
|
31
31
|
readonly retryAfterSeconds: number | undefined;
|
|
32
32
|
readonly rateLimit: RateLimitInfo;
|
|
33
|
+
/** The whole error body as the Hub sent it, for the extra fields some codes carry (`areas`, `docs_url`, `events`). */
|
|
34
|
+
readonly body: Record<string, unknown>;
|
|
33
35
|
constructor(
|
|
34
36
|
/** HTTP status. */
|
|
35
37
|
status: number,
|
|
36
38
|
/** Stable snake_case code to program against, for example `not_found` or `insufficient_scope`. */
|
|
37
39
|
code: string, message: string,
|
|
38
40
|
/** The `details` object (for a 422 it maps each field to its messages). */
|
|
39
|
-
details: unknown, requestId: string | undefined, retryAfterSeconds: number | undefined, rateLimit?: RateLimitInfo
|
|
41
|
+
details: unknown, requestId: string | undefined, retryAfterSeconds: number | undefined, rateLimit?: RateLimitInfo,
|
|
42
|
+
/** The whole error body as the Hub sent it, for the extra fields some codes carry (`areas`, `docs_url`, `events`). */
|
|
43
|
+
body?: Record<string, unknown>);
|
|
40
44
|
/** A plain-words next step for the codes people hit most, or undefined. */
|
|
41
45
|
get hint(): string | undefined;
|
|
42
46
|
toJSON(): Record<string, unknown>;
|
|
@@ -51,6 +55,43 @@ export declare class AuthenticationError extends ApiError {
|
|
|
51
55
|
/** 403: the key may not do this (`insufficient_scope`, `portal_unavailable`, `key_inactive`, `ip_not_allowed`). */
|
|
52
56
|
export declare class PermissionError extends ApiError {
|
|
53
57
|
}
|
|
58
|
+
/** The four codes of a call refused because the area needs the Hub's manual approval and the client does not have it. */
|
|
59
|
+
export declare const API_ACCESS_CODES: readonly ["api_access_not_approved", "api_access_pending", "api_access_rejected", "api_access_revoked"];
|
|
60
|
+
export type ApiAccessCode = (typeof API_ACCESS_CODES)[number];
|
|
61
|
+
/** The states of an area that needs approval, as `hb.account.apiAccess.get()` reports them (`not_requested` when nothing was asked). */
|
|
62
|
+
export type ApiAccessRefusal = 'not_requested' | 'pending' | 'rejected' | 'revoked';
|
|
63
|
+
/**
|
|
64
|
+
* 403 `api_access_not_approved`, `api_access_pending`, `api_access_rejected` or `api_access_revoked`: the key holds a scope of an area
|
|
65
|
+
* that needs the Hub's manual approval (by default Occupational Health and DBS & Right To Work) and your organisation does not have it.
|
|
66
|
+
* Not retryable: retrying changes nothing until the state does. Live keys only; the sandbox is always open.
|
|
67
|
+
*/
|
|
68
|
+
export declare class ApiAccessError extends PermissionError {
|
|
69
|
+
/** The portal keys involved, for example `['occupational-health']`. */
|
|
70
|
+
get areas(): string[];
|
|
71
|
+
/** Where to read more about the approval. */
|
|
72
|
+
get docsUrl(): string | undefined;
|
|
73
|
+
/** Where your organisation stands, matching the `status` of `hb.account.apiAccess.get()`. */
|
|
74
|
+
get state(): ApiAccessRefusal;
|
|
75
|
+
toJSON(): Record<string, unknown>;
|
|
76
|
+
/** Always false: do not loop on this error. Ask for, or follow up, the approval in the Hub under Developer > API access. */
|
|
77
|
+
get retryable(): false;
|
|
78
|
+
}
|
|
79
|
+
/** True for an `ApiAccessError` (any of the four `api_access_*` codes). */
|
|
80
|
+
export declare function isApiAccessError(error: unknown): error is ApiAccessError;
|
|
81
|
+
/**
|
|
82
|
+
* 403 `webhook_events_not_approved`: a webhook endpoint was created or updated with events of an area that needs approval your
|
|
83
|
+
* organisation does not hold. `events` lists the offending event names and `areas` their portal keys. Nothing was saved.
|
|
84
|
+
*/
|
|
85
|
+
export declare class WebhookEventsNotApprovedError extends PermissionError {
|
|
86
|
+
/** The portal keys involved. */
|
|
87
|
+
get areas(): string[];
|
|
88
|
+
/** The event names that were refused, for example `['occupational-health.request.submitted']`. */
|
|
89
|
+
get events(): string[];
|
|
90
|
+
get docsUrl(): string | undefined;
|
|
91
|
+
get retryable(): false;
|
|
92
|
+
}
|
|
93
|
+
/** True for a `WebhookEventsNotApprovedError`. */
|
|
94
|
+
export declare function isWebhookEventsNotApprovedError(error: unknown): error is WebhookEventsNotApprovedError;
|
|
54
95
|
/** 404. */
|
|
55
96
|
export declare class NotFoundError extends ApiError {
|
|
56
97
|
}
|
|
@@ -109,4 +150,4 @@ export declare class EmbedError extends HubError {
|
|
|
109
150
|
readonly status?: number | undefined;
|
|
110
151
|
constructor(message: string, code: string, status?: number | undefined);
|
|
111
152
|
}
|
|
112
|
-
export declare function apiErrorFrom(status: number, code: string, message: string, details: unknown, requestId: string | undefined, retryAfter: number | undefined, rateLimit: RateLimitInfo): ApiError;
|
|
153
|
+
export declare function apiErrorFrom(status: number, code: string, message: string, details: unknown, requestId: string | undefined, retryAfter: number | undefined, rateLimit: RateLimitInfo, body?: Record<string, unknown>): ApiError;
|
package/dist/cjs/core/errors.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.EmbedError = exports.WebhookSignatureError = exports.AuthThrottledError = exports.AbortedError = exports.NetworkError = exports.ServerError = exports.RateLimitError = exports.GoneError = exports.ValidationError = exports.InsufficientCreditsError = exports.EmbedAccessError = exports.ConflictError = exports.NotFoundError = exports.PermissionError = exports.AuthenticationError = exports.NEXT_HINTS = exports.CODE_HINTS = exports.ApiError = exports.ConfigError = exports.HubError = void 0;
|
|
3
|
+
exports.EmbedError = exports.WebhookSignatureError = exports.AuthThrottledError = exports.AbortedError = exports.NetworkError = exports.ServerError = exports.RateLimitError = exports.GoneError = exports.ValidationError = exports.InsufficientCreditsError = exports.EmbedAccessError = exports.ConflictError = exports.NotFoundError = exports.WebhookEventsNotApprovedError = exports.ApiAccessError = exports.API_ACCESS_CODES = exports.PermissionError = exports.AuthenticationError = exports.NEXT_HINTS = exports.CODE_HINTS = exports.ApiError = exports.ConfigError = exports.HubError = void 0;
|
|
4
|
+
exports.isApiAccessError = isApiAccessError;
|
|
5
|
+
exports.isWebhookEventsNotApprovedError = isWebhookEventsNotApprovedError;
|
|
4
6
|
exports.isEmbedAccessError = isEmbedAccessError;
|
|
5
7
|
exports.apiErrorFrom = apiErrorFrom;
|
|
6
8
|
const protocol_js_1 = require("../embed/protocol.js");
|
|
@@ -27,13 +29,16 @@ class ApiError extends HubError {
|
|
|
27
29
|
requestId;
|
|
28
30
|
retryAfterSeconds;
|
|
29
31
|
rateLimit;
|
|
32
|
+
body;
|
|
30
33
|
constructor(
|
|
31
34
|
/** HTTP status. */
|
|
32
35
|
status,
|
|
33
36
|
/** Stable snake_case code to program against, for example `not_found` or `insufficient_scope`. */
|
|
34
37
|
code, message,
|
|
35
38
|
/** The `details` object (for a 422 it maps each field to its messages). */
|
|
36
|
-
details, requestId, retryAfterSeconds, rateLimit = {}
|
|
39
|
+
details, requestId, retryAfterSeconds, rateLimit = {},
|
|
40
|
+
/** The whole error body as the Hub sent it, for the extra fields some codes carry (`areas`, `docs_url`, `events`). */
|
|
41
|
+
body = {}) {
|
|
37
42
|
super(message);
|
|
38
43
|
this.status = status;
|
|
39
44
|
this.code = code;
|
|
@@ -41,12 +46,17 @@ class ApiError extends HubError {
|
|
|
41
46
|
this.requestId = requestId;
|
|
42
47
|
this.retryAfterSeconds = retryAfterSeconds;
|
|
43
48
|
this.rateLimit = rateLimit;
|
|
49
|
+
this.body = body;
|
|
44
50
|
}
|
|
45
51
|
/** A plain-words next step for the codes people hit most, or undefined. */
|
|
46
52
|
get hint() {
|
|
47
53
|
if (this.code === 'validation_failed' && this.details && typeof this.details === 'object' && 'origin' in this.details) {
|
|
48
54
|
return exports.CODE_HINTS.origin_not_registered;
|
|
49
55
|
}
|
|
56
|
+
if (this.code === 'webhook_events_not_approved')
|
|
57
|
+
return exports.CODE_HINTS.webhook_events_not_approved;
|
|
58
|
+
if (exports.API_ACCESS_CODES.includes(this.code))
|
|
59
|
+
return exports.CODE_HINTS[this.code];
|
|
50
60
|
if (protocol_js_1.EMBED_ACCESS_CODES.includes(this.code)) {
|
|
51
61
|
const next = (0, protocol_js_1.cleanAccessDetails)(this.details).next;
|
|
52
62
|
if (next)
|
|
@@ -66,6 +76,11 @@ exports.CODE_HINTS = {
|
|
|
66
76
|
key_inactive: 'The key is switched off or has expired. Switch it on or create a new one in Hub.',
|
|
67
77
|
portal_unavailable: 'The account does not use this portal.',
|
|
68
78
|
invalid_credentials: 'The API key is wrong, deleted or regenerated.',
|
|
79
|
+
api_access_not_approved: 'The area holds health or criminal record information and needs a one-off approval. A user of your organisation asks for it in the Hub under Developer > API access. Do not retry. Check where you stand with hb.account.apiAccess.get().',
|
|
80
|
+
api_access_pending: 'Your request for this area is waiting for review by Hub staff (Hub, Developer > API access) and you will be emailed the decision. Do not retry until it is approved. Check with hb.account.apiAccess.get().',
|
|
81
|
+
api_access_rejected: 'The last request for this area was not approved. The reason is in the Hub under Developer > API access, where a new request can be sent. Do not retry.',
|
|
82
|
+
api_access_revoked: 'Staff withdrew the approval for this area. The reason is in the Hub under Developer > API access, where a new request can be sent. Do not retry.',
|
|
83
|
+
webhook_events_not_approved: 'Some events belong to an area that needs approval your organisation does not hold. Remove those events (error.events), or get the area approved first (hb.account.apiAccess.get() shows where you stand).',
|
|
69
84
|
idempotency_conflict: 'The same Idempotency-Key was used earlier with a different body. Use a new key, or resend the original body.',
|
|
70
85
|
rate_limited: 'Wait for Retry-After before the next call.',
|
|
71
86
|
origin_not_registered: 'Origin not registered: add this website (scheme, host and port, for example https://learn.example.com) under Developer > Embed in Hub, then create the session again.',
|
|
@@ -94,6 +109,73 @@ exports.AuthenticationError = AuthenticationError;
|
|
|
94
109
|
class PermissionError extends ApiError {
|
|
95
110
|
}
|
|
96
111
|
exports.PermissionError = PermissionError;
|
|
112
|
+
/** The four codes of a call refused because the area needs the Hub's manual approval and the client does not have it. */
|
|
113
|
+
exports.API_ACCESS_CODES = ['api_access_not_approved', 'api_access_pending', 'api_access_rejected', 'api_access_revoked'];
|
|
114
|
+
const REFUSAL_BY_CODE = {
|
|
115
|
+
api_access_not_approved: 'not_requested',
|
|
116
|
+
api_access_pending: 'pending',
|
|
117
|
+
api_access_rejected: 'rejected',
|
|
118
|
+
api_access_revoked: 'revoked',
|
|
119
|
+
};
|
|
120
|
+
function stringList(value) {
|
|
121
|
+
return Array.isArray(value) ? value.filter((v) => typeof v === 'string') : [];
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* 403 `api_access_not_approved`, `api_access_pending`, `api_access_rejected` or `api_access_revoked`: the key holds a scope of an area
|
|
125
|
+
* that needs the Hub's manual approval (by default Occupational Health and DBS & Right To Work) and your organisation does not have it.
|
|
126
|
+
* Not retryable: retrying changes nothing until the state does. Live keys only; the sandbox is always open.
|
|
127
|
+
*/
|
|
128
|
+
class ApiAccessError extends PermissionError {
|
|
129
|
+
/** The portal keys involved, for example `['occupational-health']`. */
|
|
130
|
+
get areas() {
|
|
131
|
+
return stringList(this.body.areas);
|
|
132
|
+
}
|
|
133
|
+
/** Where to read more about the approval. */
|
|
134
|
+
get docsUrl() {
|
|
135
|
+
return typeof this.body.docs_url === 'string' ? this.body.docs_url : undefined;
|
|
136
|
+
}
|
|
137
|
+
/** Where your organisation stands, matching the `status` of `hb.account.apiAccess.get()`. */
|
|
138
|
+
get state() {
|
|
139
|
+
return REFUSAL_BY_CODE[this.code] ?? 'not_requested';
|
|
140
|
+
}
|
|
141
|
+
toJSON() {
|
|
142
|
+
return { ...super.toJSON(), areas: this.areas, docsUrl: this.docsUrl };
|
|
143
|
+
}
|
|
144
|
+
/** Always false: do not loop on this error. Ask for, or follow up, the approval in the Hub under Developer > API access. */
|
|
145
|
+
get retryable() {
|
|
146
|
+
return false;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
exports.ApiAccessError = ApiAccessError;
|
|
150
|
+
/** True for an `ApiAccessError` (any of the four `api_access_*` codes). */
|
|
151
|
+
function isApiAccessError(error) {
|
|
152
|
+
return error instanceof ApiAccessError;
|
|
153
|
+
}
|
|
154
|
+
/**
|
|
155
|
+
* 403 `webhook_events_not_approved`: a webhook endpoint was created or updated with events of an area that needs approval your
|
|
156
|
+
* organisation does not hold. `events` lists the offending event names and `areas` their portal keys. Nothing was saved.
|
|
157
|
+
*/
|
|
158
|
+
class WebhookEventsNotApprovedError extends PermissionError {
|
|
159
|
+
/** The portal keys involved. */
|
|
160
|
+
get areas() {
|
|
161
|
+
return stringList(this.body.areas);
|
|
162
|
+
}
|
|
163
|
+
/** The event names that were refused, for example `['occupational-health.request.submitted']`. */
|
|
164
|
+
get events() {
|
|
165
|
+
return stringList(this.body.events);
|
|
166
|
+
}
|
|
167
|
+
get docsUrl() {
|
|
168
|
+
return typeof this.body.docs_url === 'string' ? this.body.docs_url : undefined;
|
|
169
|
+
}
|
|
170
|
+
get retryable() {
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
exports.WebhookEventsNotApprovedError = WebhookEventsNotApprovedError;
|
|
175
|
+
/** True for a `WebhookEventsNotApprovedError`. */
|
|
176
|
+
function isWebhookEventsNotApprovedError(error) {
|
|
177
|
+
return error instanceof WebhookEventsNotApprovedError;
|
|
178
|
+
}
|
|
97
179
|
/** 404. */
|
|
98
180
|
class NotFoundError extends ApiError {
|
|
99
181
|
}
|
|
@@ -185,14 +267,19 @@ class EmbedError extends HubError {
|
|
|
185
267
|
}
|
|
186
268
|
}
|
|
187
269
|
exports.EmbedError = EmbedError;
|
|
188
|
-
function apiErrorFrom(status, code, message, details, requestId, retryAfter, rateLimit) {
|
|
189
|
-
const args = [status, code, message, details, requestId, retryAfter, rateLimit];
|
|
270
|
+
function apiErrorFrom(status, code, message, details, requestId, retryAfter, rateLimit, body = {}) {
|
|
271
|
+
const args = [status, code, message, details, requestId, retryAfter, rateLimit, body];
|
|
190
272
|
if (status === 401)
|
|
191
273
|
return new AuthenticationError(...args);
|
|
192
274
|
if (status === 402)
|
|
193
275
|
return new InsufficientCreditsError(...args);
|
|
194
|
-
if (status === 403)
|
|
276
|
+
if (status === 403) {
|
|
277
|
+
if (exports.API_ACCESS_CODES.includes(code))
|
|
278
|
+
return new ApiAccessError(...args);
|
|
279
|
+
if (code === 'webhook_events_not_approved')
|
|
280
|
+
return new WebhookEventsNotApprovedError(...args);
|
|
195
281
|
return new PermissionError(...args);
|
|
282
|
+
}
|
|
196
283
|
if (status === 404)
|
|
197
284
|
return new NotFoundError(...args);
|
|
198
285
|
if (status === 409)
|
package/dist/cjs/core/http.js
CHANGED
|
@@ -106,7 +106,7 @@ class HttpClient {
|
|
|
106
106
|
await this.sleep(meta.retryAfter !== undefined ? Math.min(meta.retryAfter * 1000, this.opts.maxRetryDelayMs) : this.backoff(attempt));
|
|
107
107
|
continue;
|
|
108
108
|
}
|
|
109
|
-
throw (0, errors_js_1.apiErrorFrom)(res.status, code, typeof errorBody.message === 'string' ? errorBody.message : `The Hub answered HTTP ${res.status}.`, errorBody.details, typeof errorBody.request_id === 'string' ? errorBody.request_id : meta.requestId, meta.retryAfter, meta.rateLimit);
|
|
109
|
+
throw (0, errors_js_1.apiErrorFrom)(res.status, code, typeof errorBody.message === 'string' ? errorBody.message : `The Hub answered HTTP ${res.status}.`, errorBody.details, typeof errorBody.request_id === 'string' ? errorBody.request_id : meta.requestId, meta.retryAfter, meta.rateLimit, errorBody);
|
|
110
110
|
}
|
|
111
111
|
}
|
|
112
112
|
/** Exponential backoff with jitter: about 0.5s, 1s, 2s, capped at 8s. */
|
|
@@ -19,7 +19,7 @@ export interface EmbedSession {
|
|
|
19
19
|
/** The one website origin allowed to show this frame. */
|
|
20
20
|
allowedOrigin: string;
|
|
21
21
|
}
|
|
22
|
-
export type EmbedEventName = 'ready' | 'progress' | 'completed' | 'passed' | 'failed' | 'submitted' | 'terms-accepted' | 'error' | 'token-expiring';
|
|
22
|
+
export type EmbedEventName = 'ready' | 'progress' | 'completed' | 'passed' | 'failed' | 'submitted' | 'test-requested' | 'terms-accepted' | 'error' | 'token-expiring';
|
|
23
23
|
/**
|
|
24
24
|
* The codes the Hub answers with (HTTP 409) when it will not create a session because the candidate's training access is not in
|
|
25
25
|
* place. Each carries `details` (see `EmbedAccessDetails`).
|
|
@@ -77,6 +77,11 @@ export interface EmbedEventMap {
|
|
|
77
77
|
score: number;
|
|
78
78
|
passMark: number;
|
|
79
79
|
};
|
|
80
|
+
/** Course only: the learner pressed a Take test button in a lesson. `courseId` is the Online Training course id you created the session with; open that course's test (`createTestSession` with the same `courseId`). Not final: the course session stays open. */
|
|
81
|
+
'test-requested': {
|
|
82
|
+
courseId: number;
|
|
83
|
+
testId: number;
|
|
84
|
+
};
|
|
80
85
|
/** The OH form was submitted: `requestId` is the numeric Occupational Health request id. Final. */
|
|
81
86
|
submitted: {
|
|
82
87
|
requestId: number;
|
|
@@ -3,6 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
|
|
|
3
3
|
exports.RESOURCE_TREE = exports.OPERATIONS = exports.SPEC_VERSION = void 0;
|
|
4
4
|
exports.SPEC_VERSION = "2.0.0";
|
|
5
5
|
exports.OPERATIONS = {
|
|
6
|
+
"account.api-access.show": { method: 'GET', path: "/api/v2/account/api-access", pathParams: [], query: [], body: null, idempotent: false, paginated: false, response: 'json', scope: null },
|
|
6
7
|
"auth.me.show": { method: 'GET', path: "/api/v2/auth/me", pathParams: [], query: [], body: null, idempotent: false, paginated: false, response: 'json', scope: null },
|
|
7
8
|
"clinical-appraisals.appraisal-types.list": { method: 'GET', path: "/api/v2/clinical-appraisals/appraisal-types", pathParams: [], query: ["page", "per_page", "sort"], body: null, idempotent: false, paginated: true, response: 'json', scope: "clinical-appraisals:catalogue:read" },
|
|
8
9
|
"clinical-appraisals.bookings.create": { method: 'POST', path: "/api/v2/clinical-appraisals/bookings", pathParams: [], query: [], body: 'json', idempotent: true, paginated: false, response: 'json', scope: "clinical-appraisals:bookings:write" },
|
|
@@ -214,6 +215,11 @@ exports.OPERATIONS = {
|
|
|
214
215
|
"webhooks.events.list": { method: 'GET', path: "/api/v2/webhooks/events", pathParams: [], query: ["page", "per_page"], body: null, idempotent: false, paginated: true, response: 'json', scope: "account:webhooks:read" },
|
|
215
216
|
};
|
|
216
217
|
exports.RESOURCE_TREE = {
|
|
218
|
+
"account": {
|
|
219
|
+
"apiAccess": {
|
|
220
|
+
"get": "account.api-access.show"
|
|
221
|
+
}
|
|
222
|
+
},
|
|
217
223
|
"auth": {
|
|
218
224
|
"me": {
|
|
219
225
|
"get": "auth.me.show"
|
|
@@ -2,6 +2,10 @@ import type { FileInput, HubFile } from '../core/files.js';
|
|
|
2
2
|
import type { PagePromise } from '../core/pagination.js';
|
|
3
3
|
import type { RequestOptions } from '../core/manifest.js';
|
|
4
4
|
import type * as Types from './types.js';
|
|
5
|
+
export type AccountApiAccessGetResponse = {
|
|
6
|
+
/** One row per portal area. */
|
|
7
|
+
data: Types.ApiAccessArea[];
|
|
8
|
+
};
|
|
5
9
|
export type AuthMeGetResponse = Types.ApiKeyInfo;
|
|
6
10
|
export interface ClinicalAppraisalsAppraisalTypesListParams {
|
|
7
11
|
/** The page to return, starting at 1. A page beyond the last returns an empty `data` with the real `total`. */
|
|
@@ -1069,6 +1073,8 @@ export interface OnlineTrainingCandidatesAccessStartParams {
|
|
|
1069
1073
|
months?: "12" | "24";
|
|
1070
1074
|
/** Where the payment pages may send the candidate back to (a "Back to" button). Must be on one of your registered embed origins. Only used when the candidate pays. */
|
|
1071
1075
|
return_url?: string | null;
|
|
1076
|
+
/** The most credits this start may take from the account (decimal). When the live quote is higher the call answers `409 quote_changed` with the current quote and starts, charges and creates nothing. Candidate-paid groups… */
|
|
1077
|
+
max_credits?: number | null;
|
|
1072
1078
|
};
|
|
1073
1079
|
}
|
|
1074
1080
|
export type OnlineTrainingCandidatesAccessStartResponse = {
|
|
@@ -2380,7 +2386,7 @@ export type WebhooksDeliveriesRedeliverResponse = Types.WebhookMessage;
|
|
|
2380
2386
|
export interface WebhooksEndpointsCreateParams {
|
|
2381
2387
|
body: Types.WebhookEndpointInput;
|
|
2382
2388
|
}
|
|
2383
|
-
export type WebhooksEndpointsCreateResponse = Types.WebhookEndpointCreated;
|
|
2389
|
+
export type WebhooksEndpointsCreateResponse = Types.WebhookEndpointExisting | Types.WebhookEndpointCreated;
|
|
2384
2390
|
export interface WebhooksEndpointsDeleteParams {
|
|
2385
2391
|
/** The webhook endpoint id (integer), from `GET /api/v2/webhooks`. */
|
|
2386
2392
|
webhook: string | number;
|
|
@@ -2443,6 +2449,12 @@ export type WebhooksEventsListResponse = {
|
|
|
2443
2449
|
};
|
|
2444
2450
|
/** Every operation of the Hub API, grouped by portal. */
|
|
2445
2451
|
export interface HubApi {
|
|
2452
|
+
account: {
|
|
2453
|
+
apiAccess: {
|
|
2454
|
+
/** Show which areas need approval. */
|
|
2455
|
+
get(options?: RequestOptions): Promise<AccountApiAccessGetResponse>;
|
|
2456
|
+
};
|
|
2457
|
+
};
|
|
2446
2458
|
auth: {
|
|
2447
2459
|
me: {
|
|
2448
2460
|
/** Show the key behind the token. */
|
|
@@ -1,4 +1,17 @@
|
|
|
1
1
|
import type { FileInput } from '../core/files.js';
|
|
2
|
+
/** One portal area and where your client stands on manual approval for it. Areas that need approval (by default Occupational Health and DBS & Right To Work) refuse API calls, and hold back their webhook events, until Hub… */
|
|
3
|
+
export type ApiAccessArea = {
|
|
4
|
+
/** The portal key, as used in scopes (`occupational-health:*`) and as the first part of event names (`occupational-health.request.submitted`). */
|
|
5
|
+
area: string;
|
|
6
|
+
/** The name of the area to show to people. */
|
|
7
|
+
label: string;
|
|
8
|
+
/** Whether the area needs manual approval. Hub staff choose which areas do, so read it instead of assuming. */
|
|
9
|
+
sensitive: boolean;
|
|
10
|
+
/** Where your client stands: `not_required` (the area is open), `not_requested` (nothing asked yet), `pending` (a request waits for review), `approved` (calls and webhook events work), `rejected` (the last request was… */
|
|
11
|
+
status: "not_required" | "not_requested" | "pending" | "approved" | "rejected" | "revoked";
|
|
12
|
+
/** When the current state was decided (approval, rejection or withdrawal), in UTC. Null for `not_required`, `not_requested` and `pending`. */
|
|
13
|
+
decided_at: string | null;
|
|
14
|
+
};
|
|
2
15
|
/** The API key behind the access token you sent: which client it belongs to and what it may do. The secret part of the key is never returned. */
|
|
3
16
|
export type ApiKeyInfo = {
|
|
4
17
|
/** The id of the Hub client the key belongs to (the account that is billed and whose data the key can read). The same id is in every portal for the same client. */
|
|
@@ -2921,6 +2934,8 @@ export type TvStoreVerificationBody = {
|
|
|
2921
2934
|
certificate_base64?: string | null;
|
|
2922
2935
|
/** The file name of the base64 certificate, with its extension (`.pdf`, `.jpg`, `.jpeg` or `.png`). Required with `certificate_base64`. */
|
|
2923
2936
|
certificate_filename?: string | null;
|
|
2937
|
+
/** The most this verification may cost, as its net price in pounds (the account's price for the request type in `GET /pricing`, VAT not counted; `0` allows only a free request). When the live price is higher the call… */
|
|
2938
|
+
max_credits?: number | null;
|
|
2924
2939
|
};
|
|
2925
2940
|
export type TvVerification = {
|
|
2926
2941
|
/** The verification id, an integer that never changes. Use it in every `/verifications/{verification}` path. */
|
|
@@ -3550,8 +3565,10 @@ export type WebhookEndpoint = {
|
|
|
3550
3565
|
url: string;
|
|
3551
3566
|
/** The events the endpoint receives, each `{portal}.{event}`. The list is the whole subscription: an event not in it is not sent. See `GET /api/v2/webhooks/events` for every name. */
|
|
3552
3567
|
events: string[];
|
|
3553
|
-
/** False when the endpoint is switched off
|
|
3568
|
+
/** False when the endpoint is switched off: by you (`is_active: false`), by Hub after 25 failed deliveries in a row, or by Hub at once when your server answers `410 Gone` (see `disabled_reason`). No events are queued for… */
|
|
3554
3569
|
is_active: boolean;
|
|
3570
|
+
/** Why Hub switched the endpoint off: `failures` (25 failed deliveries in a row; the client's developers are emailed) or `gone` (your server answered `410 Gone`, which stops events at once, without retries and without… */
|
|
3571
|
+
disabled_reason: "failures" | "gone" | null;
|
|
3555
3572
|
/** How long Hub waits for your server to answer each attempt, 5 to 30 seconds (the connection itself must open within 5). Null means the default of 10 seconds. */
|
|
3556
3573
|
timeout_seconds: number | null;
|
|
3557
3574
|
/** The first 12 characters of the signing secret (`whsec_` and six more) followed by bullets, to tell which secret is current after a rotation. It cannot be used to sign or verify anything; the full secret is shown only… */
|
|
@@ -3564,6 +3581,10 @@ export type WebhookEndpoint = {
|
|
|
3564
3581
|
consecutive_failures: number;
|
|
3565
3582
|
/** True for an endpoint copied from an old portal API when Hub moved to one webhook system. Such an endpoint is still sent that portal's own event names, body shape and signature headers (in addition to the standard… */
|
|
3566
3583
|
imported: boolean;
|
|
3584
|
+
/** Where the endpoint came from: `api` (this API), `zapier` (made by the Zapier app, sent as `source` when created), `developer_page` (made on the Developer page) or `imported` (copied from an old portal API). Fixed when… */
|
|
3585
|
+
source: "api" | "developer_page" | "zapier" | "imported";
|
|
3586
|
+
/** Your own reference for the endpoint, up to 191 characters, unique within your client; null if none was given. Creating an endpoint with an `external_ref` that already exists returns the existing endpoint instead of… */
|
|
3587
|
+
external_ref: string | null;
|
|
3567
3588
|
/** When the endpoint was created (ISO 8601 UTC). */
|
|
3568
3589
|
created_at: string;
|
|
3569
3590
|
};
|
|
@@ -3574,18 +3595,27 @@ export type WebhookEndpointCreated = WebhookEndpoint & {
|
|
|
3574
3595
|
/** A reminder to store the secret. */
|
|
3575
3596
|
notice: string;
|
|
3576
3597
|
};
|
|
3598
|
+
/** The endpoint that already exists for the `external_ref` you sent, plus a `notice`. It carries no `signing_secret`: a secret is shown only when an endpoint is first created (use `POST… */
|
|
3599
|
+
export type WebhookEndpointExisting = WebhookEndpoint & {
|
|
3600
|
+
/** A sentence saying no new endpoint was created and that the secret is not shown again. */
|
|
3601
|
+
notice: string;
|
|
3602
|
+
};
|
|
3577
3603
|
/** A new webhook endpoint. */
|
|
3578
3604
|
export type WebhookEndpointInput = {
|
|
3579
3605
|
/** A name to recognise the endpoint by, up to 100 characters. */
|
|
3580
3606
|
name: string;
|
|
3581
3607
|
/** The https address Hub sends events to, up to 2048 characters. It must be a full `https` URL to a public server: `http`, a username or password in the URL, and addresses on private networks are refused with `422` on… */
|
|
3582
3608
|
url: string;
|
|
3583
|
-
/** The events to receive, each `{portal}.{event}` from `GET /api/v2/webhooks/events`; at least one. On an update this replaces the whole list. */
|
|
3609
|
+
/** The events to receive, each `{portal}.{event}` from `GET /api/v2/webhooks/events`; at least one. On an update this replaces the whole list. Each event must belong to a portal the calling key can read (a scope for that… */
|
|
3584
3610
|
events: string[];
|
|
3585
3611
|
/** False to create the endpoint switched off (or to switch it off on an update); true to switch it on, which on an update also resets the failure count. Default true when creating. */
|
|
3586
3612
|
is_active?: boolean;
|
|
3587
3613
|
/** How long Hub waits for your server's answer, 5 to 30 seconds. Default 10; null on an update returns to the default. */
|
|
3588
3614
|
timeout_seconds?: number | null;
|
|
3615
|
+
/** On creation only: which tool makes the endpoint, `api` (the default) or `zapier`. Shown on the Developer page. Ignored on an update. */
|
|
3616
|
+
source?: "api" | "zapier";
|
|
3617
|
+
/** On creation only: your own reference for the endpoint, up to 191 characters, unique within your client. Sending one that already exists does not create a second endpoint: the call answers `200` with the existing… */
|
|
3618
|
+
external_ref?: string | null;
|
|
3589
3619
|
};
|
|
3590
3620
|
/** The fields to change; fields left out keep their value. */
|
|
3591
3621
|
export type WebhookEndpointPatch = {
|
package/dist/cjs/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { HealthierBusiness, type HealthierBusinessOptions } from './client.js';
|
|
2
|
-
export { AbortedError, ApiError, AuthenticationError, AuthThrottledError, ConfigError, ConflictError, EmbedAccessError, EmbedError, GoneError, HubError, InsufficientCreditsError, isEmbedAccessError, NetworkError, NotFoundError, PermissionError, RateLimitError, ServerError, ValidationError, WebhookSignatureError, CODE_HINTS, NEXT_HINTS, type RateLimitInfo, } from './core/errors.js';
|
|
2
|
+
export { AbortedError, API_ACCESS_CODES, ApiAccessError, ApiError, AuthenticationError, AuthThrottledError, ConfigError, ConflictError, EmbedAccessError, EmbedError, GoneError, HubError, InsufficientCreditsError, isApiAccessError, isEmbedAccessError, isWebhookEventsNotApprovedError, NetworkError, NotFoundError, PermissionError, RateLimitError, ServerError, ValidationError, WebhookEventsNotApprovedError, WebhookSignatureError, CODE_HINTS, NEXT_HINTS, type ApiAccessCode, type ApiAccessRefusal, type RateLimitInfo, } from './core/errors.js';
|
|
3
3
|
export type { Environment } from './core/env.js';
|
|
4
4
|
export { HubFile, type FileInput } from './core/files.js';
|
|
5
5
|
export type { Logger } from './core/logger.js';
|
package/dist/cjs/index.js
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.accessStartResult = exports.embedErrorHint = exports.EMBED_ACCESS_CODES = exports.VERSION = exports.verifyWebhook = exports.signWebhook = exports.constructEvent = exports.WEBHOOK_EVENT_TYPES = exports.MemoryTokenStore = exports.PagePromise = exports.HubFile = exports.NEXT_HINTS = exports.CODE_HINTS = exports.WebhookSignatureError = exports.ValidationError = exports.ServerError = exports.RateLimitError = exports.PermissionError = exports.NotFoundError = exports.NetworkError = exports.isEmbedAccessError = exports.InsufficientCreditsError = exports.HubError = exports.GoneError = exports.EmbedError = exports.EmbedAccessError = exports.ConflictError = exports.ConfigError = exports.AuthThrottledError = exports.AuthenticationError = exports.ApiError = exports.AbortedError = exports.HealthierBusiness = void 0;
|
|
3
|
+
exports.accessStartResult = exports.embedErrorHint = exports.EMBED_ACCESS_CODES = exports.VERSION = exports.verifyWebhook = exports.signWebhook = exports.constructEvent = exports.WEBHOOK_EVENT_TYPES = exports.MemoryTokenStore = exports.PagePromise = exports.HubFile = exports.NEXT_HINTS = exports.CODE_HINTS = exports.WebhookSignatureError = exports.WebhookEventsNotApprovedError = exports.ValidationError = exports.ServerError = exports.RateLimitError = exports.PermissionError = exports.NotFoundError = exports.NetworkError = exports.isWebhookEventsNotApprovedError = exports.isEmbedAccessError = exports.isApiAccessError = exports.InsufficientCreditsError = exports.HubError = exports.GoneError = exports.EmbedError = exports.EmbedAccessError = exports.ConflictError = exports.ConfigError = exports.AuthThrottledError = exports.AuthenticationError = exports.ApiError = exports.ApiAccessError = exports.API_ACCESS_CODES = exports.AbortedError = exports.HealthierBusiness = void 0;
|
|
4
4
|
var client_js_1 = require("./client.js");
|
|
5
5
|
Object.defineProperty(exports, "HealthierBusiness", { enumerable: true, get: function () { return client_js_1.HealthierBusiness; } });
|
|
6
6
|
var errors_js_1 = require("./core/errors.js");
|
|
7
7
|
Object.defineProperty(exports, "AbortedError", { enumerable: true, get: function () { return errors_js_1.AbortedError; } });
|
|
8
|
+
Object.defineProperty(exports, "API_ACCESS_CODES", { enumerable: true, get: function () { return errors_js_1.API_ACCESS_CODES; } });
|
|
9
|
+
Object.defineProperty(exports, "ApiAccessError", { enumerable: true, get: function () { return errors_js_1.ApiAccessError; } });
|
|
8
10
|
Object.defineProperty(exports, "ApiError", { enumerable: true, get: function () { return errors_js_1.ApiError; } });
|
|
9
11
|
Object.defineProperty(exports, "AuthenticationError", { enumerable: true, get: function () { return errors_js_1.AuthenticationError; } });
|
|
10
12
|
Object.defineProperty(exports, "AuthThrottledError", { enumerable: true, get: function () { return errors_js_1.AuthThrottledError; } });
|
|
@@ -15,13 +17,16 @@ Object.defineProperty(exports, "EmbedError", { enumerable: true, get: function (
|
|
|
15
17
|
Object.defineProperty(exports, "GoneError", { enumerable: true, get: function () { return errors_js_1.GoneError; } });
|
|
16
18
|
Object.defineProperty(exports, "HubError", { enumerable: true, get: function () { return errors_js_1.HubError; } });
|
|
17
19
|
Object.defineProperty(exports, "InsufficientCreditsError", { enumerable: true, get: function () { return errors_js_1.InsufficientCreditsError; } });
|
|
20
|
+
Object.defineProperty(exports, "isApiAccessError", { enumerable: true, get: function () { return errors_js_1.isApiAccessError; } });
|
|
18
21
|
Object.defineProperty(exports, "isEmbedAccessError", { enumerable: true, get: function () { return errors_js_1.isEmbedAccessError; } });
|
|
22
|
+
Object.defineProperty(exports, "isWebhookEventsNotApprovedError", { enumerable: true, get: function () { return errors_js_1.isWebhookEventsNotApprovedError; } });
|
|
19
23
|
Object.defineProperty(exports, "NetworkError", { enumerable: true, get: function () { return errors_js_1.NetworkError; } });
|
|
20
24
|
Object.defineProperty(exports, "NotFoundError", { enumerable: true, get: function () { return errors_js_1.NotFoundError; } });
|
|
21
25
|
Object.defineProperty(exports, "PermissionError", { enumerable: true, get: function () { return errors_js_1.PermissionError; } });
|
|
22
26
|
Object.defineProperty(exports, "RateLimitError", { enumerable: true, get: function () { return errors_js_1.RateLimitError; } });
|
|
23
27
|
Object.defineProperty(exports, "ServerError", { enumerable: true, get: function () { return errors_js_1.ServerError; } });
|
|
24
28
|
Object.defineProperty(exports, "ValidationError", { enumerable: true, get: function () { return errors_js_1.ValidationError; } });
|
|
29
|
+
Object.defineProperty(exports, "WebhookEventsNotApprovedError", { enumerable: true, get: function () { return errors_js_1.WebhookEventsNotApprovedError; } });
|
|
25
30
|
Object.defineProperty(exports, "WebhookSignatureError", { enumerable: true, get: function () { return errors_js_1.WebhookSignatureError; } });
|
|
26
31
|
Object.defineProperty(exports, "CODE_HINTS", { enumerable: true, get: function () { return errors_js_1.CODE_HINTS; } });
|
|
27
32
|
Object.defineProperty(exports, "NEXT_HINTS", { enumerable: true, get: function () { return errors_js_1.NEXT_HINTS; } });
|
package/dist/cjs/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const VERSION = "0.
|
|
1
|
+
export declare const VERSION = "0.4.0";
|
package/dist/cjs/version.js
CHANGED
package/dist/cjs/webhooks.d.ts
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
import type { HubWebhookEvent } from './generated/events.js';
|
|
2
|
+
/**
|
|
3
|
+
* Every event type the Hub can send. Not every type is open to every organisation: events of an area that needs the Hub's manual
|
|
4
|
+
* approval (by default `occupational-health.*` and `dbs-rtw.*`) are only sent to an approved organisation, and creating or updating an
|
|
5
|
+
* endpoint with them first fails with `WebhookEventsNotApprovedError` (`error.areas`, `error.events`). Read the areas from
|
|
6
|
+
* `hb.account.apiAccess.get()` instead of hard-coding them. The sandbox sends all events.
|
|
7
|
+
*/
|
|
2
8
|
export { WEBHOOK_EVENT_TYPES } from './generated/events.js';
|
|
3
9
|
export type { HubWebhookEvent, WebhookEventType, WebhookEvents } from './generated/events.js';
|
|
4
10
|
/** What the Hub sends with every delivery: `X-Hub-Signature` and `X-Hub-Timestamp`. */
|
package/dist/cjs/webhooks.js
CHANGED
|
@@ -6,6 +6,12 @@ exports.constructEvent = constructEvent;
|
|
|
6
6
|
exports.verifyWebhook = verifyWebhook;
|
|
7
7
|
const errors_js_1 = require("./core/errors.js");
|
|
8
8
|
const sha256_js_1 = require("./core/sha256.js");
|
|
9
|
+
/**
|
|
10
|
+
* Every event type the Hub can send. Not every type is open to every organisation: events of an area that needs the Hub's manual
|
|
11
|
+
* approval (by default `occupational-health.*` and `dbs-rtw.*`) are only sent to an approved organisation, and creating or updating an
|
|
12
|
+
* endpoint with them first fails with `WebhookEventsNotApprovedError` (`error.areas`, `error.events`). Read the areas from
|
|
13
|
+
* `hb.account.apiAccess.get()` instead of hard-coding them. The sandbox sends all events.
|
|
14
|
+
*/
|
|
9
15
|
var events_js_1 = require("./generated/events.js");
|
|
10
16
|
Object.defineProperty(exports, "WEBHOOK_EVENT_TYPES", { enumerable: true, get: function () { return events_js_1.WEBHOOK_EVENT_TYPES; } });
|
|
11
17
|
const encoder = new TextEncoder();
|
|
@@ -4,6 +4,6 @@ export { cleanAccessDetails, EMBED_ACCESS_CODES, embedErrorHint, isEmbedSession,
|
|
|
4
4
|
/** `HealthierBusiness.mount(element, options)` for the browser. It holds no API key and cannot make API calls. */
|
|
5
5
|
export declare const HealthierBusiness: {
|
|
6
6
|
readonly mount: typeof mount;
|
|
7
|
-
readonly version: "0.
|
|
7
|
+
readonly version: "0.4.0";
|
|
8
8
|
};
|
|
9
|
-
export declare const version = "0.
|
|
9
|
+
export declare const version = "0.4.0";
|
|
@@ -36,6 +36,8 @@ export interface MountOptions {
|
|
|
36
36
|
onPassed?: (data: EmbedEventMap['passed']) => void;
|
|
37
37
|
onFailed?: (data: EmbedEventMap['failed']) => void;
|
|
38
38
|
onSubmitted?: (data: EmbedEventMap['submitted']) => void;
|
|
39
|
+
/** The learner pressed a Take test button in a lesson: open that course's test (`createTestSession` with the same `courseId`). */
|
|
40
|
+
onTestRequested?: (data: EmbedEventMap['test-requested']) => void;
|
|
39
41
|
/** The candidate accepted the Hub terms in the frame. */
|
|
40
42
|
onTermsAccepted?: (data: EmbedEventMap['terms-accepted']) => void;
|
|
41
43
|
onError?: (error: EmbedEventMap['error']) => void;
|
|
@@ -30,13 +30,17 @@ export declare class ApiError extends HubError {
|
|
|
30
30
|
readonly requestId: string | undefined;
|
|
31
31
|
readonly retryAfterSeconds: number | undefined;
|
|
32
32
|
readonly rateLimit: RateLimitInfo;
|
|
33
|
+
/** The whole error body as the Hub sent it, for the extra fields some codes carry (`areas`, `docs_url`, `events`). */
|
|
34
|
+
readonly body: Record<string, unknown>;
|
|
33
35
|
constructor(
|
|
34
36
|
/** HTTP status. */
|
|
35
37
|
status: number,
|
|
36
38
|
/** Stable snake_case code to program against, for example `not_found` or `insufficient_scope`. */
|
|
37
39
|
code: string, message: string,
|
|
38
40
|
/** The `details` object (for a 422 it maps each field to its messages). */
|
|
39
|
-
details: unknown, requestId: string | undefined, retryAfterSeconds: number | undefined, rateLimit?: RateLimitInfo
|
|
41
|
+
details: unknown, requestId: string | undefined, retryAfterSeconds: number | undefined, rateLimit?: RateLimitInfo,
|
|
42
|
+
/** The whole error body as the Hub sent it, for the extra fields some codes carry (`areas`, `docs_url`, `events`). */
|
|
43
|
+
body?: Record<string, unknown>);
|
|
40
44
|
/** A plain-words next step for the codes people hit most, or undefined. */
|
|
41
45
|
get hint(): string | undefined;
|
|
42
46
|
toJSON(): Record<string, unknown>;
|
|
@@ -51,6 +55,43 @@ export declare class AuthenticationError extends ApiError {
|
|
|
51
55
|
/** 403: the key may not do this (`insufficient_scope`, `portal_unavailable`, `key_inactive`, `ip_not_allowed`). */
|
|
52
56
|
export declare class PermissionError extends ApiError {
|
|
53
57
|
}
|
|
58
|
+
/** The four codes of a call refused because the area needs the Hub's manual approval and the client does not have it. */
|
|
59
|
+
export declare const API_ACCESS_CODES: readonly ["api_access_not_approved", "api_access_pending", "api_access_rejected", "api_access_revoked"];
|
|
60
|
+
export type ApiAccessCode = (typeof API_ACCESS_CODES)[number];
|
|
61
|
+
/** The states of an area that needs approval, as `hb.account.apiAccess.get()` reports them (`not_requested` when nothing was asked). */
|
|
62
|
+
export type ApiAccessRefusal = 'not_requested' | 'pending' | 'rejected' | 'revoked';
|
|
63
|
+
/**
|
|
64
|
+
* 403 `api_access_not_approved`, `api_access_pending`, `api_access_rejected` or `api_access_revoked`: the key holds a scope of an area
|
|
65
|
+
* that needs the Hub's manual approval (by default Occupational Health and DBS & Right To Work) and your organisation does not have it.
|
|
66
|
+
* Not retryable: retrying changes nothing until the state does. Live keys only; the sandbox is always open.
|
|
67
|
+
*/
|
|
68
|
+
export declare class ApiAccessError extends PermissionError {
|
|
69
|
+
/** The portal keys involved, for example `['occupational-health']`. */
|
|
70
|
+
get areas(): string[];
|
|
71
|
+
/** Where to read more about the approval. */
|
|
72
|
+
get docsUrl(): string | undefined;
|
|
73
|
+
/** Where your organisation stands, matching the `status` of `hb.account.apiAccess.get()`. */
|
|
74
|
+
get state(): ApiAccessRefusal;
|
|
75
|
+
toJSON(): Record<string, unknown>;
|
|
76
|
+
/** Always false: do not loop on this error. Ask for, or follow up, the approval in the Hub under Developer > API access. */
|
|
77
|
+
get retryable(): false;
|
|
78
|
+
}
|
|
79
|
+
/** True for an `ApiAccessError` (any of the four `api_access_*` codes). */
|
|
80
|
+
export declare function isApiAccessError(error: unknown): error is ApiAccessError;
|
|
81
|
+
/**
|
|
82
|
+
* 403 `webhook_events_not_approved`: a webhook endpoint was created or updated with events of an area that needs approval your
|
|
83
|
+
* organisation does not hold. `events` lists the offending event names and `areas` their portal keys. Nothing was saved.
|
|
84
|
+
*/
|
|
85
|
+
export declare class WebhookEventsNotApprovedError extends PermissionError {
|
|
86
|
+
/** The portal keys involved. */
|
|
87
|
+
get areas(): string[];
|
|
88
|
+
/** The event names that were refused, for example `['occupational-health.request.submitted']`. */
|
|
89
|
+
get events(): string[];
|
|
90
|
+
get docsUrl(): string | undefined;
|
|
91
|
+
get retryable(): false;
|
|
92
|
+
}
|
|
93
|
+
/** True for a `WebhookEventsNotApprovedError`. */
|
|
94
|
+
export declare function isWebhookEventsNotApprovedError(error: unknown): error is WebhookEventsNotApprovedError;
|
|
54
95
|
/** 404. */
|
|
55
96
|
export declare class NotFoundError extends ApiError {
|
|
56
97
|
}
|
|
@@ -109,4 +150,4 @@ export declare class EmbedError extends HubError {
|
|
|
109
150
|
readonly status?: number | undefined;
|
|
110
151
|
constructor(message: string, code: string, status?: number | undefined);
|
|
111
152
|
}
|
|
112
|
-
export declare function apiErrorFrom(status: number, code: string, message: string, details: unknown, requestId: string | undefined, retryAfter: number | undefined, rateLimit: RateLimitInfo): ApiError;
|
|
153
|
+
export declare function apiErrorFrom(status: number, code: string, message: string, details: unknown, requestId: string | undefined, retryAfter: number | undefined, rateLimit: RateLimitInfo, body?: Record<string, unknown>): ApiError;
|
package/dist/esm/core/errors.js
CHANGED
|
@@ -20,13 +20,16 @@ export class ApiError extends HubError {
|
|
|
20
20
|
requestId;
|
|
21
21
|
retryAfterSeconds;
|
|
22
22
|
rateLimit;
|
|
23
|
+
body;
|
|
23
24
|
constructor(
|
|
24
25
|
/** HTTP status. */
|
|
25
26
|
status,
|
|
26
27
|
/** Stable snake_case code to program against, for example `not_found` or `insufficient_scope`. */
|
|
27
28
|
code, message,
|
|
28
29
|
/** The `details` object (for a 422 it maps each field to its messages). */
|
|
29
|
-
details, requestId, retryAfterSeconds, rateLimit = {}
|
|
30
|
+
details, requestId, retryAfterSeconds, rateLimit = {},
|
|
31
|
+
/** The whole error body as the Hub sent it, for the extra fields some codes carry (`areas`, `docs_url`, `events`). */
|
|
32
|
+
body = {}) {
|
|
30
33
|
super(message);
|
|
31
34
|
this.status = status;
|
|
32
35
|
this.code = code;
|
|
@@ -34,12 +37,17 @@ export class ApiError extends HubError {
|
|
|
34
37
|
this.requestId = requestId;
|
|
35
38
|
this.retryAfterSeconds = retryAfterSeconds;
|
|
36
39
|
this.rateLimit = rateLimit;
|
|
40
|
+
this.body = body;
|
|
37
41
|
}
|
|
38
42
|
/** A plain-words next step for the codes people hit most, or undefined. */
|
|
39
43
|
get hint() {
|
|
40
44
|
if (this.code === 'validation_failed' && this.details && typeof this.details === 'object' && 'origin' in this.details) {
|
|
41
45
|
return CODE_HINTS.origin_not_registered;
|
|
42
46
|
}
|
|
47
|
+
if (this.code === 'webhook_events_not_approved')
|
|
48
|
+
return CODE_HINTS.webhook_events_not_approved;
|
|
49
|
+
if (API_ACCESS_CODES.includes(this.code))
|
|
50
|
+
return CODE_HINTS[this.code];
|
|
43
51
|
if (EMBED_ACCESS_CODES.includes(this.code)) {
|
|
44
52
|
const next = cleanAccessDetails(this.details).next;
|
|
45
53
|
if (next)
|
|
@@ -58,6 +66,11 @@ export const CODE_HINTS = {
|
|
|
58
66
|
key_inactive: 'The key is switched off or has expired. Switch it on or create a new one in Hub.',
|
|
59
67
|
portal_unavailable: 'The account does not use this portal.',
|
|
60
68
|
invalid_credentials: 'The API key is wrong, deleted or regenerated.',
|
|
69
|
+
api_access_not_approved: 'The area holds health or criminal record information and needs a one-off approval. A user of your organisation asks for it in the Hub under Developer > API access. Do not retry. Check where you stand with hb.account.apiAccess.get().',
|
|
70
|
+
api_access_pending: 'Your request for this area is waiting for review by Hub staff (Hub, Developer > API access) and you will be emailed the decision. Do not retry until it is approved. Check with hb.account.apiAccess.get().',
|
|
71
|
+
api_access_rejected: 'The last request for this area was not approved. The reason is in the Hub under Developer > API access, where a new request can be sent. Do not retry.',
|
|
72
|
+
api_access_revoked: 'Staff withdrew the approval for this area. The reason is in the Hub under Developer > API access, where a new request can be sent. Do not retry.',
|
|
73
|
+
webhook_events_not_approved: 'Some events belong to an area that needs approval your organisation does not hold. Remove those events (error.events), or get the area approved first (hb.account.apiAccess.get() shows where you stand).',
|
|
61
74
|
idempotency_conflict: 'The same Idempotency-Key was used earlier with a different body. Use a new key, or resend the original body.',
|
|
62
75
|
rate_limited: 'Wait for Retry-After before the next call.',
|
|
63
76
|
origin_not_registered: 'Origin not registered: add this website (scheme, host and port, for example https://learn.example.com) under Developer > Embed in Hub, then create the session again.',
|
|
@@ -84,6 +97,71 @@ export class AuthenticationError extends ApiError {
|
|
|
84
97
|
/** 403: the key may not do this (`insufficient_scope`, `portal_unavailable`, `key_inactive`, `ip_not_allowed`). */
|
|
85
98
|
export class PermissionError extends ApiError {
|
|
86
99
|
}
|
|
100
|
+
/** The four codes of a call refused because the area needs the Hub's manual approval and the client does not have it. */
|
|
101
|
+
export const API_ACCESS_CODES = ['api_access_not_approved', 'api_access_pending', 'api_access_rejected', 'api_access_revoked'];
|
|
102
|
+
const REFUSAL_BY_CODE = {
|
|
103
|
+
api_access_not_approved: 'not_requested',
|
|
104
|
+
api_access_pending: 'pending',
|
|
105
|
+
api_access_rejected: 'rejected',
|
|
106
|
+
api_access_revoked: 'revoked',
|
|
107
|
+
};
|
|
108
|
+
function stringList(value) {
|
|
109
|
+
return Array.isArray(value) ? value.filter((v) => typeof v === 'string') : [];
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* 403 `api_access_not_approved`, `api_access_pending`, `api_access_rejected` or `api_access_revoked`: the key holds a scope of an area
|
|
113
|
+
* that needs the Hub's manual approval (by default Occupational Health and DBS & Right To Work) and your organisation does not have it.
|
|
114
|
+
* Not retryable: retrying changes nothing until the state does. Live keys only; the sandbox is always open.
|
|
115
|
+
*/
|
|
116
|
+
export class ApiAccessError extends PermissionError {
|
|
117
|
+
/** The portal keys involved, for example `['occupational-health']`. */
|
|
118
|
+
get areas() {
|
|
119
|
+
return stringList(this.body.areas);
|
|
120
|
+
}
|
|
121
|
+
/** Where to read more about the approval. */
|
|
122
|
+
get docsUrl() {
|
|
123
|
+
return typeof this.body.docs_url === 'string' ? this.body.docs_url : undefined;
|
|
124
|
+
}
|
|
125
|
+
/** Where your organisation stands, matching the `status` of `hb.account.apiAccess.get()`. */
|
|
126
|
+
get state() {
|
|
127
|
+
return REFUSAL_BY_CODE[this.code] ?? 'not_requested';
|
|
128
|
+
}
|
|
129
|
+
toJSON() {
|
|
130
|
+
return { ...super.toJSON(), areas: this.areas, docsUrl: this.docsUrl };
|
|
131
|
+
}
|
|
132
|
+
/** Always false: do not loop on this error. Ask for, or follow up, the approval in the Hub under Developer > API access. */
|
|
133
|
+
get retryable() {
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
/** True for an `ApiAccessError` (any of the four `api_access_*` codes). */
|
|
138
|
+
export function isApiAccessError(error) {
|
|
139
|
+
return error instanceof ApiAccessError;
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* 403 `webhook_events_not_approved`: a webhook endpoint was created or updated with events of an area that needs approval your
|
|
143
|
+
* organisation does not hold. `events` lists the offending event names and `areas` their portal keys. Nothing was saved.
|
|
144
|
+
*/
|
|
145
|
+
export class WebhookEventsNotApprovedError extends PermissionError {
|
|
146
|
+
/** The portal keys involved. */
|
|
147
|
+
get areas() {
|
|
148
|
+
return stringList(this.body.areas);
|
|
149
|
+
}
|
|
150
|
+
/** The event names that were refused, for example `['occupational-health.request.submitted']`. */
|
|
151
|
+
get events() {
|
|
152
|
+
return stringList(this.body.events);
|
|
153
|
+
}
|
|
154
|
+
get docsUrl() {
|
|
155
|
+
return typeof this.body.docs_url === 'string' ? this.body.docs_url : undefined;
|
|
156
|
+
}
|
|
157
|
+
get retryable() {
|
|
158
|
+
return false;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
/** True for a `WebhookEventsNotApprovedError`. */
|
|
162
|
+
export function isWebhookEventsNotApprovedError(error) {
|
|
163
|
+
return error instanceof WebhookEventsNotApprovedError;
|
|
164
|
+
}
|
|
87
165
|
/** 404. */
|
|
88
166
|
export class NotFoundError extends ApiError {
|
|
89
167
|
}
|
|
@@ -162,14 +240,19 @@ export class EmbedError extends HubError {
|
|
|
162
240
|
this.status = status;
|
|
163
241
|
}
|
|
164
242
|
}
|
|
165
|
-
export function apiErrorFrom(status, code, message, details, requestId, retryAfter, rateLimit) {
|
|
166
|
-
const args = [status, code, message, details, requestId, retryAfter, rateLimit];
|
|
243
|
+
export function apiErrorFrom(status, code, message, details, requestId, retryAfter, rateLimit, body = {}) {
|
|
244
|
+
const args = [status, code, message, details, requestId, retryAfter, rateLimit, body];
|
|
167
245
|
if (status === 401)
|
|
168
246
|
return new AuthenticationError(...args);
|
|
169
247
|
if (status === 402)
|
|
170
248
|
return new InsufficientCreditsError(...args);
|
|
171
|
-
if (status === 403)
|
|
249
|
+
if (status === 403) {
|
|
250
|
+
if (API_ACCESS_CODES.includes(code))
|
|
251
|
+
return new ApiAccessError(...args);
|
|
252
|
+
if (code === 'webhook_events_not_approved')
|
|
253
|
+
return new WebhookEventsNotApprovedError(...args);
|
|
172
254
|
return new PermissionError(...args);
|
|
255
|
+
}
|
|
173
256
|
if (status === 404)
|
|
174
257
|
return new NotFoundError(...args);
|
|
175
258
|
if (status === 409)
|
package/dist/esm/core/http.js
CHANGED
|
@@ -102,7 +102,7 @@ export class HttpClient {
|
|
|
102
102
|
await this.sleep(meta.retryAfter !== undefined ? Math.min(meta.retryAfter * 1000, this.opts.maxRetryDelayMs) : this.backoff(attempt));
|
|
103
103
|
continue;
|
|
104
104
|
}
|
|
105
|
-
throw apiErrorFrom(res.status, code, typeof errorBody.message === 'string' ? errorBody.message : `The Hub answered HTTP ${res.status}.`, errorBody.details, typeof errorBody.request_id === 'string' ? errorBody.request_id : meta.requestId, meta.retryAfter, meta.rateLimit);
|
|
105
|
+
throw apiErrorFrom(res.status, code, typeof errorBody.message === 'string' ? errorBody.message : `The Hub answered HTTP ${res.status}.`, errorBody.details, typeof errorBody.request_id === 'string' ? errorBody.request_id : meta.requestId, meta.retryAfter, meta.rateLimit, errorBody);
|
|
106
106
|
}
|
|
107
107
|
}
|
|
108
108
|
/** Exponential backoff with jitter: about 0.5s, 1s, 2s, capped at 8s. */
|
|
@@ -19,7 +19,7 @@ export interface EmbedSession {
|
|
|
19
19
|
/** The one website origin allowed to show this frame. */
|
|
20
20
|
allowedOrigin: string;
|
|
21
21
|
}
|
|
22
|
-
export type EmbedEventName = 'ready' | 'progress' | 'completed' | 'passed' | 'failed' | 'submitted' | 'terms-accepted' | 'error' | 'token-expiring';
|
|
22
|
+
export type EmbedEventName = 'ready' | 'progress' | 'completed' | 'passed' | 'failed' | 'submitted' | 'test-requested' | 'terms-accepted' | 'error' | 'token-expiring';
|
|
23
23
|
/**
|
|
24
24
|
* The codes the Hub answers with (HTTP 409) when it will not create a session because the candidate's training access is not in
|
|
25
25
|
* place. Each carries `details` (see `EmbedAccessDetails`).
|
|
@@ -77,6 +77,11 @@ export interface EmbedEventMap {
|
|
|
77
77
|
score: number;
|
|
78
78
|
passMark: number;
|
|
79
79
|
};
|
|
80
|
+
/** Course only: the learner pressed a Take test button in a lesson. `courseId` is the Online Training course id you created the session with; open that course's test (`createTestSession` with the same `courseId`). Not final: the course session stays open. */
|
|
81
|
+
'test-requested': {
|
|
82
|
+
courseId: number;
|
|
83
|
+
testId: number;
|
|
84
|
+
};
|
|
80
85
|
/** The OH form was submitted: `requestId` is the numeric Occupational Health request id. Final. */
|
|
81
86
|
submitted: {
|
|
82
87
|
requestId: number;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
export const SPEC_VERSION = "2.0.0";
|
|
2
2
|
export const OPERATIONS = {
|
|
3
|
+
"account.api-access.show": { method: 'GET', path: "/api/v2/account/api-access", pathParams: [], query: [], body: null, idempotent: false, paginated: false, response: 'json', scope: null },
|
|
3
4
|
"auth.me.show": { method: 'GET', path: "/api/v2/auth/me", pathParams: [], query: [], body: null, idempotent: false, paginated: false, response: 'json', scope: null },
|
|
4
5
|
"clinical-appraisals.appraisal-types.list": { method: 'GET', path: "/api/v2/clinical-appraisals/appraisal-types", pathParams: [], query: ["page", "per_page", "sort"], body: null, idempotent: false, paginated: true, response: 'json', scope: "clinical-appraisals:catalogue:read" },
|
|
5
6
|
"clinical-appraisals.bookings.create": { method: 'POST', path: "/api/v2/clinical-appraisals/bookings", pathParams: [], query: [], body: 'json', idempotent: true, paginated: false, response: 'json', scope: "clinical-appraisals:bookings:write" },
|
|
@@ -211,6 +212,11 @@ export const OPERATIONS = {
|
|
|
211
212
|
"webhooks.events.list": { method: 'GET', path: "/api/v2/webhooks/events", pathParams: [], query: ["page", "per_page"], body: null, idempotent: false, paginated: true, response: 'json', scope: "account:webhooks:read" },
|
|
212
213
|
};
|
|
213
214
|
export const RESOURCE_TREE = {
|
|
215
|
+
"account": {
|
|
216
|
+
"apiAccess": {
|
|
217
|
+
"get": "account.api-access.show"
|
|
218
|
+
}
|
|
219
|
+
},
|
|
214
220
|
"auth": {
|
|
215
221
|
"me": {
|
|
216
222
|
"get": "auth.me.show"
|
|
@@ -2,6 +2,10 @@ import type { FileInput, HubFile } from '../core/files.js';
|
|
|
2
2
|
import type { PagePromise } from '../core/pagination.js';
|
|
3
3
|
import type { RequestOptions } from '../core/manifest.js';
|
|
4
4
|
import type * as Types from './types.js';
|
|
5
|
+
export type AccountApiAccessGetResponse = {
|
|
6
|
+
/** One row per portal area. */
|
|
7
|
+
data: Types.ApiAccessArea[];
|
|
8
|
+
};
|
|
5
9
|
export type AuthMeGetResponse = Types.ApiKeyInfo;
|
|
6
10
|
export interface ClinicalAppraisalsAppraisalTypesListParams {
|
|
7
11
|
/** The page to return, starting at 1. A page beyond the last returns an empty `data` with the real `total`. */
|
|
@@ -1069,6 +1073,8 @@ export interface OnlineTrainingCandidatesAccessStartParams {
|
|
|
1069
1073
|
months?: "12" | "24";
|
|
1070
1074
|
/** Where the payment pages may send the candidate back to (a "Back to" button). Must be on one of your registered embed origins. Only used when the candidate pays. */
|
|
1071
1075
|
return_url?: string | null;
|
|
1076
|
+
/** The most credits this start may take from the account (decimal). When the live quote is higher the call answers `409 quote_changed` with the current quote and starts, charges and creates nothing. Candidate-paid groups… */
|
|
1077
|
+
max_credits?: number | null;
|
|
1072
1078
|
};
|
|
1073
1079
|
}
|
|
1074
1080
|
export type OnlineTrainingCandidatesAccessStartResponse = {
|
|
@@ -2380,7 +2386,7 @@ export type WebhooksDeliveriesRedeliverResponse = Types.WebhookMessage;
|
|
|
2380
2386
|
export interface WebhooksEndpointsCreateParams {
|
|
2381
2387
|
body: Types.WebhookEndpointInput;
|
|
2382
2388
|
}
|
|
2383
|
-
export type WebhooksEndpointsCreateResponse = Types.WebhookEndpointCreated;
|
|
2389
|
+
export type WebhooksEndpointsCreateResponse = Types.WebhookEndpointExisting | Types.WebhookEndpointCreated;
|
|
2384
2390
|
export interface WebhooksEndpointsDeleteParams {
|
|
2385
2391
|
/** The webhook endpoint id (integer), from `GET /api/v2/webhooks`. */
|
|
2386
2392
|
webhook: string | number;
|
|
@@ -2443,6 +2449,12 @@ export type WebhooksEventsListResponse = {
|
|
|
2443
2449
|
};
|
|
2444
2450
|
/** Every operation of the Hub API, grouped by portal. */
|
|
2445
2451
|
export interface HubApi {
|
|
2452
|
+
account: {
|
|
2453
|
+
apiAccess: {
|
|
2454
|
+
/** Show which areas need approval. */
|
|
2455
|
+
get(options?: RequestOptions): Promise<AccountApiAccessGetResponse>;
|
|
2456
|
+
};
|
|
2457
|
+
};
|
|
2446
2458
|
auth: {
|
|
2447
2459
|
me: {
|
|
2448
2460
|
/** Show the key behind the token. */
|
|
@@ -1,4 +1,17 @@
|
|
|
1
1
|
import type { FileInput } from '../core/files.js';
|
|
2
|
+
/** One portal area and where your client stands on manual approval for it. Areas that need approval (by default Occupational Health and DBS & Right To Work) refuse API calls, and hold back their webhook events, until Hub… */
|
|
3
|
+
export type ApiAccessArea = {
|
|
4
|
+
/** The portal key, as used in scopes (`occupational-health:*`) and as the first part of event names (`occupational-health.request.submitted`). */
|
|
5
|
+
area: string;
|
|
6
|
+
/** The name of the area to show to people. */
|
|
7
|
+
label: string;
|
|
8
|
+
/** Whether the area needs manual approval. Hub staff choose which areas do, so read it instead of assuming. */
|
|
9
|
+
sensitive: boolean;
|
|
10
|
+
/** Where your client stands: `not_required` (the area is open), `not_requested` (nothing asked yet), `pending` (a request waits for review), `approved` (calls and webhook events work), `rejected` (the last request was… */
|
|
11
|
+
status: "not_required" | "not_requested" | "pending" | "approved" | "rejected" | "revoked";
|
|
12
|
+
/** When the current state was decided (approval, rejection or withdrawal), in UTC. Null for `not_required`, `not_requested` and `pending`. */
|
|
13
|
+
decided_at: string | null;
|
|
14
|
+
};
|
|
2
15
|
/** The API key behind the access token you sent: which client it belongs to and what it may do. The secret part of the key is never returned. */
|
|
3
16
|
export type ApiKeyInfo = {
|
|
4
17
|
/** The id of the Hub client the key belongs to (the account that is billed and whose data the key can read). The same id is in every portal for the same client. */
|
|
@@ -2921,6 +2934,8 @@ export type TvStoreVerificationBody = {
|
|
|
2921
2934
|
certificate_base64?: string | null;
|
|
2922
2935
|
/** The file name of the base64 certificate, with its extension (`.pdf`, `.jpg`, `.jpeg` or `.png`). Required with `certificate_base64`. */
|
|
2923
2936
|
certificate_filename?: string | null;
|
|
2937
|
+
/** The most this verification may cost, as its net price in pounds (the account's price for the request type in `GET /pricing`, VAT not counted; `0` allows only a free request). When the live price is higher the call… */
|
|
2938
|
+
max_credits?: number | null;
|
|
2924
2939
|
};
|
|
2925
2940
|
export type TvVerification = {
|
|
2926
2941
|
/** The verification id, an integer that never changes. Use it in every `/verifications/{verification}` path. */
|
|
@@ -3550,8 +3565,10 @@ export type WebhookEndpoint = {
|
|
|
3550
3565
|
url: string;
|
|
3551
3566
|
/** The events the endpoint receives, each `{portal}.{event}`. The list is the whole subscription: an event not in it is not sent. See `GET /api/v2/webhooks/events` for every name. */
|
|
3552
3567
|
events: string[];
|
|
3553
|
-
/** False when the endpoint is switched off
|
|
3568
|
+
/** False when the endpoint is switched off: by you (`is_active: false`), by Hub after 25 failed deliveries in a row, or by Hub at once when your server answers `410 Gone` (see `disabled_reason`). No events are queued for… */
|
|
3554
3569
|
is_active: boolean;
|
|
3570
|
+
/** Why Hub switched the endpoint off: `failures` (25 failed deliveries in a row; the client's developers are emailed) or `gone` (your server answered `410 Gone`, which stops events at once, without retries and without… */
|
|
3571
|
+
disabled_reason: "failures" | "gone" | null;
|
|
3555
3572
|
/** How long Hub waits for your server to answer each attempt, 5 to 30 seconds (the connection itself must open within 5). Null means the default of 10 seconds. */
|
|
3556
3573
|
timeout_seconds: number | null;
|
|
3557
3574
|
/** The first 12 characters of the signing secret (`whsec_` and six more) followed by bullets, to tell which secret is current after a rotation. It cannot be used to sign or verify anything; the full secret is shown only… */
|
|
@@ -3564,6 +3581,10 @@ export type WebhookEndpoint = {
|
|
|
3564
3581
|
consecutive_failures: number;
|
|
3565
3582
|
/** True for an endpoint copied from an old portal API when Hub moved to one webhook system. Such an endpoint is still sent that portal's own event names, body shape and signature headers (in addition to the standard… */
|
|
3566
3583
|
imported: boolean;
|
|
3584
|
+
/** Where the endpoint came from: `api` (this API), `zapier` (made by the Zapier app, sent as `source` when created), `developer_page` (made on the Developer page) or `imported` (copied from an old portal API). Fixed when… */
|
|
3585
|
+
source: "api" | "developer_page" | "zapier" | "imported";
|
|
3586
|
+
/** Your own reference for the endpoint, up to 191 characters, unique within your client; null if none was given. Creating an endpoint with an `external_ref` that already exists returns the existing endpoint instead of… */
|
|
3587
|
+
external_ref: string | null;
|
|
3567
3588
|
/** When the endpoint was created (ISO 8601 UTC). */
|
|
3568
3589
|
created_at: string;
|
|
3569
3590
|
};
|
|
@@ -3574,18 +3595,27 @@ export type WebhookEndpointCreated = WebhookEndpoint & {
|
|
|
3574
3595
|
/** A reminder to store the secret. */
|
|
3575
3596
|
notice: string;
|
|
3576
3597
|
};
|
|
3598
|
+
/** The endpoint that already exists for the `external_ref` you sent, plus a `notice`. It carries no `signing_secret`: a secret is shown only when an endpoint is first created (use `POST… */
|
|
3599
|
+
export type WebhookEndpointExisting = WebhookEndpoint & {
|
|
3600
|
+
/** A sentence saying no new endpoint was created and that the secret is not shown again. */
|
|
3601
|
+
notice: string;
|
|
3602
|
+
};
|
|
3577
3603
|
/** A new webhook endpoint. */
|
|
3578
3604
|
export type WebhookEndpointInput = {
|
|
3579
3605
|
/** A name to recognise the endpoint by, up to 100 characters. */
|
|
3580
3606
|
name: string;
|
|
3581
3607
|
/** The https address Hub sends events to, up to 2048 characters. It must be a full `https` URL to a public server: `http`, a username or password in the URL, and addresses on private networks are refused with `422` on… */
|
|
3582
3608
|
url: string;
|
|
3583
|
-
/** The events to receive, each `{portal}.{event}` from `GET /api/v2/webhooks/events`; at least one. On an update this replaces the whole list. */
|
|
3609
|
+
/** The events to receive, each `{portal}.{event}` from `GET /api/v2/webhooks/events`; at least one. On an update this replaces the whole list. Each event must belong to a portal the calling key can read (a scope for that… */
|
|
3584
3610
|
events: string[];
|
|
3585
3611
|
/** False to create the endpoint switched off (or to switch it off on an update); true to switch it on, which on an update also resets the failure count. Default true when creating. */
|
|
3586
3612
|
is_active?: boolean;
|
|
3587
3613
|
/** How long Hub waits for your server's answer, 5 to 30 seconds. Default 10; null on an update returns to the default. */
|
|
3588
3614
|
timeout_seconds?: number | null;
|
|
3615
|
+
/** On creation only: which tool makes the endpoint, `api` (the default) or `zapier`. Shown on the Developer page. Ignored on an update. */
|
|
3616
|
+
source?: "api" | "zapier";
|
|
3617
|
+
/** On creation only: your own reference for the endpoint, up to 191 characters, unique within your client. Sending one that already exists does not create a second endpoint: the call answers `200` with the existing… */
|
|
3618
|
+
external_ref?: string | null;
|
|
3589
3619
|
};
|
|
3590
3620
|
/** The fields to change; fields left out keep their value. */
|
|
3591
3621
|
export type WebhookEndpointPatch = {
|
package/dist/esm/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { HealthierBusiness, type HealthierBusinessOptions } from './client.js';
|
|
2
|
-
export { AbortedError, ApiError, AuthenticationError, AuthThrottledError, ConfigError, ConflictError, EmbedAccessError, EmbedError, GoneError, HubError, InsufficientCreditsError, isEmbedAccessError, NetworkError, NotFoundError, PermissionError, RateLimitError, ServerError, ValidationError, WebhookSignatureError, CODE_HINTS, NEXT_HINTS, type RateLimitInfo, } from './core/errors.js';
|
|
2
|
+
export { AbortedError, API_ACCESS_CODES, ApiAccessError, ApiError, AuthenticationError, AuthThrottledError, ConfigError, ConflictError, EmbedAccessError, EmbedError, GoneError, HubError, InsufficientCreditsError, isApiAccessError, isEmbedAccessError, isWebhookEventsNotApprovedError, NetworkError, NotFoundError, PermissionError, RateLimitError, ServerError, ValidationError, WebhookEventsNotApprovedError, WebhookSignatureError, CODE_HINTS, NEXT_HINTS, type ApiAccessCode, type ApiAccessRefusal, type RateLimitInfo, } from './core/errors.js';
|
|
3
3
|
export type { Environment } from './core/env.js';
|
|
4
4
|
export { HubFile, type FileInput } from './core/files.js';
|
|
5
5
|
export type { Logger } from './core/logger.js';
|
package/dist/esm/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { HealthierBusiness } from './client.js';
|
|
2
|
-
export { AbortedError, ApiError, AuthenticationError, AuthThrottledError, ConfigError, ConflictError, EmbedAccessError, EmbedError, GoneError, HubError, InsufficientCreditsError, isEmbedAccessError, NetworkError, NotFoundError, PermissionError, RateLimitError, ServerError, ValidationError, WebhookSignatureError, CODE_HINTS, NEXT_HINTS, } from './core/errors.js';
|
|
2
|
+
export { AbortedError, API_ACCESS_CODES, ApiAccessError, ApiError, AuthenticationError, AuthThrottledError, ConfigError, ConflictError, EmbedAccessError, EmbedError, GoneError, HubError, InsufficientCreditsError, isApiAccessError, isEmbedAccessError, isWebhookEventsNotApprovedError, NetworkError, NotFoundError, PermissionError, RateLimitError, ServerError, ValidationError, WebhookEventsNotApprovedError, WebhookSignatureError, CODE_HINTS, NEXT_HINTS, } from './core/errors.js';
|
|
3
3
|
export { HubFile } from './core/files.js';
|
|
4
4
|
export { PagePromise } from './core/pagination.js';
|
|
5
5
|
export { MemoryTokenStore } from './core/tokens.js';
|
package/dist/esm/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const VERSION = "0.
|
|
1
|
+
export declare const VERSION = "0.4.0";
|
package/dist/esm/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const VERSION = '0.
|
|
1
|
+
export const VERSION = '0.4.0';
|
package/dist/esm/webhooks.d.ts
CHANGED
|
@@ -1,4 +1,10 @@
|
|
|
1
1
|
import type { HubWebhookEvent } from './generated/events.js';
|
|
2
|
+
/**
|
|
3
|
+
* Every event type the Hub can send. Not every type is open to every organisation: events of an area that needs the Hub's manual
|
|
4
|
+
* approval (by default `occupational-health.*` and `dbs-rtw.*`) are only sent to an approved organisation, and creating or updating an
|
|
5
|
+
* endpoint with them first fails with `WebhookEventsNotApprovedError` (`error.areas`, `error.events`). Read the areas from
|
|
6
|
+
* `hb.account.apiAccess.get()` instead of hard-coding them. The sandbox sends all events.
|
|
7
|
+
*/
|
|
2
8
|
export { WEBHOOK_EVENT_TYPES } from './generated/events.js';
|
|
3
9
|
export type { HubWebhookEvent, WebhookEventType, WebhookEvents } from './generated/events.js';
|
|
4
10
|
/** What the Hub sends with every delivery: `X-Hub-Signature` and `X-Hub-Timestamp`. */
|
package/dist/esm/webhooks.js
CHANGED
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
import { WebhookSignatureError } from './core/errors.js';
|
|
2
2
|
import { hmacSha256, safeEqual, toHex } from './core/sha256.js';
|
|
3
|
+
/**
|
|
4
|
+
* Every event type the Hub can send. Not every type is open to every organisation: events of an area that needs the Hub's manual
|
|
5
|
+
* approval (by default `occupational-health.*` and `dbs-rtw.*`) are only sent to an approved organisation, and creating or updating an
|
|
6
|
+
* endpoint with them first fails with `WebhookEventsNotApprovedError` (`error.areas`, `error.events`). Read the areas from
|
|
7
|
+
* `hb.account.apiAccess.get()` instead of hard-coding them. The sandbox sends all events.
|
|
8
|
+
*/
|
|
3
9
|
export { WEBHOOK_EVENT_TYPES } from './generated/events.js';
|
|
4
10
|
const encoder = new TextEncoder();
|
|
5
11
|
function headerValue(h, name) {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
var HealthierBusiness=(function(y){"use strict";const I=[...["course_access_required","payment_pending","renewal_approval_required","access_expired"],"course_not_pending"],W=["not_started","payment_pending","awaiting_approval","expired"],$=["start_access","pay","await_approval","renew"];function M(o){const e=typeof o=="object"&&o!==null?o:{},h={};return typeof e.state=="string"&&W.includes(e.state)&&(h.state=e.state),(e.payer==="client"||e.payer==="candidate")&&(h.payer=e.payer),typeof e.next=="string"&&$.includes(e.next)&&(h.next=e.next),h}const X={token_used:"The launch token was already used. A token works once: create or refresh the session and mount again.",token_invalid:"The launch token is not valid for this session. Make sure getSession returns the session your server just created or refreshed.",token_expired:"The launch token expired (it lasts 5 minutes and is renewed on refresh). Create or refresh the session and mount again.",frame_invalid:"The frame was not opened by the SDK. Show it only with HealthierBusiness.mount(), not with your own iframe.",origin_not_allowed:"This website is not the one the session was created for, or it is not registered. Add it under Developer > Embed in Hub and pass the same origin when your server creates the session.",not_allowed:"The content can only be opened through the SDK from the website the session was created for.",session_expired:"The session timed out (60 minutes without a refresh, 12 hours at most). Create a new session.",session_finished:"The session is complete. Create a new session if the person needs it again.",not_found:"The session does not exist (any more). Create a new session.",network:"The frame could not reach the Hub. Check the connection and try again.",frame_timeout:"The frame did not start. Common causes: the session expired or finished, the website is not allowed to show it, or the session was created for another origin.",origin_mismatch:"The session was created for a different origin than this page. Pass this page's origin when your server creates the session.",session_failed:"Your server route did not return a session. Check its response in the network tab.",session_changed:"Refreshing returned a different session. Your route must call hb.embed.refresh(sessionId) for a refresh.",token_refresh_failed:"Renewing the launch token failed twice. Check that your refresh route works and that the person is still signed in.",init_failed:"The frame could not be started with the token.",terms_required:"The candidate has not accepted the terms. The frame shows them first; nothing else can be used until they accept (watch for the terms-accepted event).",access_expired:"The candidate's access has ended. Renew it (accessStart, or the renewal calls when renewals need approval), then create a new session.",course_access_required:"The candidate's access has not been started. Start it with hb.onlineTraining.candidates.accessStart() on your server, then create the session again.",payment_pending:"The candidate has a payment link that is not paid yet. Ask them to pay it, then create the session again.",renewal_approval_required:"A renewal waits for approval. Approve it (renewalApprove or in Hub), then create the session again.",course_not_pending:"The candidate has already completed this course. Only courses still to do can be opened."};function b(o){return X[o]}function Y(o){if(typeof o!="object"||o===null)return!1;const e=o;return e.hb!==1?!1:e.type==="ready"?typeof e.nonce=="string"&&e.nonce.length>0&&e.nonce.length<=200:e.type==="event"?typeof e.name=="string":e.type==="resize"?typeof e.height=="number"&&Number.isFinite(e.height):e.type==="scroll-top"}function K(o){if(typeof o!="object"||o===null)return!1;const e=o;return typeof e.sessionId=="string"&&(e.kind==="course"||e.kind==="test"||e.kind==="oh_form")&&typeof e.launchToken=="string"&&typeof e.frameUrl=="string"&&(typeof e.expiresAt=="string"||e.expiresAt===null)&&typeof e.sessionExpiresAt=="string"&&typeof e.allowedOrigin=="string"}const D="allow-scripts allow-same-origin allow-forms allow-downloads allow-popups allow-popups-to-escape-sandbox",z="fullscreen; picture-in-picture; encrypted-media",G={course:"Course",test:"Test",oh_form:"Occupational health form"},J=100,Q=3e4;function R(o){let e;try{e=new URL(o.frameUrl)}catch{throw new Error("The session has no valid frameUrl.")}const h=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname.endsWith(".localhost")||e.hostname.endsWith(".test");if(e.protocol!=="https:"&&!(e.protocol==="http:"&&h))throw new Error("The frame must be served over https.");return e.origin}function H(o){const{endpoint:e,kind:h,courseId:d,formShortcode:C,fetchInit:u}=o;if(!e||!h)throw new Error("mount needs either getSession, or endpoint and kind.");return async({reason:l,sessionId:a})=>{const g=await fetch(e,{credentials:"same-origin",...u,method:"POST",headers:{"content-type":"application/json",...u==null?void 0:u.headers},body:JSON.stringify(l==="refresh"?{action:"refresh",sessionId:a}:{action:"create",kind:h,courseId:d,formShortcode:C})}),s=await g.json().catch(()=>({}));if(!g.ok){const f=typeof s.message=="string"?s.message:`Your server answered HTTP ${g.status}.`,w=typeof s.error=="string"&&I.includes(s.error)?s.error:void 0;throw Object.assign(new Error(f),w?{code:w,details:M(s.details)}:{})}return s}}function Z(o,e){var q;const h=o.ownerDocument,d=h.defaultView,C=(q=e.getSession)!=null?q:H(e),u=new Map;let l=!1,a,g="",s,f,w,j=0,A=!1,N,x;const P=new Promise((n,t)=>{N=n,x=t});P.catch(()=>{});const _=(n,t)=>{var c,T,k,E,S,i,m,v,U,V;if(l)return;const r=t!=null?t:{};switch((c=e.onEvent)==null||c.call(e,{name:n,data:t}),n){case"ready":(T=e.onReady)==null||T.call(e);break;case"progress":(k=e.onProgress)==null||k.call(e,r);break;case"completed":(E=e.onCompleted)==null||E.call(e,r);break;case"passed":(S=e.onPassed)==null||S.call(e,r);break;case"failed":(i=e.onFailed)==null||i.call(e,r);break;case"submitted":(m=e.onSubmitted)==null||m.call(e,r);break;case"terms-accepted":(v=e.onTermsAccepted)==null||v.call(e,r);break;case"error":(U=e.onError)==null||U.call(e,r);break}(V=u.get(n))==null||V.forEach(re=>re(r))},p=(n,t,r)=>{d.clearTimeout(f),x(new Error(t)),_("error",{code:n,message:t||b(n),...r?{details:r}:{}})},B=()=>{var n;d.clearTimeout(f),f=d.setTimeout(()=>p("frame_timeout",b("frame_timeout")),(n=e.readyTimeoutMs)!=null?n:2e4)},F=n=>{var t;(t=s==null?void 0:s.contentWindow)==null||t.postMessage(n,g)},O=async n=>{const t=await C(n);if(!K(t))throw new Error("getSession must return the session your server got from the SDK.");return t},te=()=>w||(w=(async()=>{let n;for(let t=0;t<2;t++)try{const r=await O({reason:"refresh",sessionId:a==null?void 0:a.sessionId});if(l)return;if(r.sessionId!==(a==null?void 0:a.sessionId)||R(r)!==g){p("session_changed","The refresh returned a different session. Your route must call hb.embed.refresh(sessionId).");return}a=r,F({hb:1,type:"token",token:r.launchToken});return}catch(r){if(n=r,l)return;await new Promise(c=>setTimeout(c,1500))}l||_("error",{code:"token_refresh_failed",message:n instanceof Error?n.message:"Could not renew the session."})})().finally(()=>{w=void 0}),w),L=n=>{var r,c,T,k,E,S;if(l||!s||n.source!==s.contentWindow||n.origin!==g||!Y(n.data))return;const t=n.data;if(t.type==="ready")j+=1,A=!1,d.clearTimeout(f),(async()=>{try{let i=a==null?void 0:a.launchToken;const m=a!=null&&a.expiresAt?Date.parse(a.expiresAt)<=Date.now():!1;if(j>1||m){const v=await O({reason:"refresh",sessionId:a==null?void 0:a.sessionId});if(l)return;a=v,i=v.launchToken}F({hb:1,type:"init",nonce:t.nonce,token:i}),B()}catch(i){p("init_failed",i instanceof Error?i.message:"Could not start the frame.")}})();else if(t.type==="resize"){if(e.height===void 0||e.height==="auto"){const i=Math.min(Q,Math.max((r=e.minHeight)!=null?r:320,Math.ceil(t.height)));s&&(s.style.height=`${Math.max(J,i)}px`)}}else if(t.type==="scroll-top"){if(s&&((c=e.onScrollTop)==null?void 0:c.call(e,s))!==!1&&e.scrollIntoView!==!1&&s.getBoundingClientRect().top<0){const i=typeof d.matchMedia=="function"&&d.matchMedia("(prefers-reduced-motion: reduce)").matches;s.scrollIntoView({block:"start",behavior:i?"auto":"smooth"})}}else if(t.type==="event"){if(t.name==="token-expiring"){_("token-expiring",t.data),te();return}if(t.name==="ready"){if(d.clearTimeout(f),A)return;A=!0,N()}else if(t.name==="error"){const i=(T=t.data)!=null?T:{},m=typeof i.code=="string"?i.code:"error";d.clearTimeout(f),A||x(new Error((E=(k=i.message)!=null?k:b(m))!=null?E:m)),_("error",{...typeof t.data=="object"&&t.data?t.data:{},code:m,message:(S=i.message)!=null?S:b(m)});return}_(t.name,t.data)}};return d.addEventListener("message",L),(async()=>{var n,t;try{const r=await O({reason:"initial"});if(l)return;if(g=R(r),r.allowedOrigin!==d.location.origin){p("origin_mismatch",`This session was created for ${r.allowedOrigin} but this page is ${d.location.origin}. Pass the right origin when your server creates the session.`);return}a=r,s=h.createElement("iframe"),s.setAttribute("sandbox",D),s.setAttribute("allow",z),s.setAttribute("allowfullscreen",""),s.setAttribute("referrerpolicy","origin"),s.setAttribute("title",(n=e.title)!=null?n:G[r.kind]),s.setAttribute("scrolling",typeof e.height=="number"?"auto":"no"),s.style.cssText="display:block;width:100%;border:0;background:#fff;color-scheme:light;",s.style.height=`${typeof e.height=="number"?e.height:(t=e.minHeight)!=null?t:320}px`,B(),s.src=r.frameUrl,o.appendChild(s)}catch(r){const c=r==null?void 0:r.code;if(typeof c=="string"&&I.includes(c)){p(c,r.message||b(c)||c,M(r.details));return}p("session_failed",r instanceof Error?r.message:"Could not get a session from your server.")}})(),{destroy(){l||(l=!0,d.removeEventListener("message",L),d.clearTimeout(f),u.clear(),s==null||s.remove(),s=void 0)},on(n,t){var c;const r=(c=u.get(n))!=null?c:new Set;return r.add(t),u.set(n,r),()=>r.delete(t)},off(n,t){var r;(r=u.get(n))==null||r.delete(t)},ready:P,get session(){return a},get destroyed(){return l}}}const ee="0.2.0";return y.SANDBOX=D,y.mount=Z,y.sessionFetcher=H,y.version=ee,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"}),y})({});
|
|
1
|
+
var HealthierBusiness=(function(y){"use strict";const I=[...["course_access_required","payment_pending","renewal_approval_required","access_expired"],"course_not_pending"],$=["not_started","payment_pending","awaiting_approval","expired"],X=["start_access","pay","await_approval","renew"];function M(o){const e=typeof o=="object"&&o!==null?o:{},h={};return typeof e.state=="string"&&$.includes(e.state)&&(h.state=e.state),(e.payer==="client"||e.payer==="candidate")&&(h.payer=e.payer),typeof e.next=="string"&&X.includes(e.next)&&(h.next=e.next),h}const Y={token_used:"The launch token was already used. A token works once: create or refresh the session and mount again.",token_invalid:"The launch token is not valid for this session. Make sure getSession returns the session your server just created or refreshed.",token_expired:"The launch token expired (it lasts 5 minutes and is renewed on refresh). Create or refresh the session and mount again.",frame_invalid:"The frame was not opened by the SDK. Show it only with HealthierBusiness.mount(), not with your own iframe.",origin_not_allowed:"This website is not the one the session was created for, or it is not registered. Add it under Developer > Embed in Hub and pass the same origin when your server creates the session.",not_allowed:"The content can only be opened through the SDK from the website the session was created for.",session_expired:"The session timed out (60 minutes without a refresh, 12 hours at most). Create a new session.",session_finished:"The session is complete. Create a new session if the person needs it again.",not_found:"The session does not exist (any more). Create a new session.",network:"The frame could not reach the Hub. Check the connection and try again.",frame_timeout:"The frame did not start. Common causes: the session expired or finished, the website is not allowed to show it, or the session was created for another origin.",origin_mismatch:"The session was created for a different origin than this page. Pass this page's origin when your server creates the session.",session_failed:"Your server route did not return a session. Check its response in the network tab.",session_changed:"Refreshing returned a different session. Your route must call hb.embed.refresh(sessionId) for a refresh.",token_refresh_failed:"Renewing the launch token failed twice. Check that your refresh route works and that the person is still signed in.",init_failed:"The frame could not be started with the token.",terms_required:"The candidate has not accepted the terms. The frame shows them first; nothing else can be used until they accept (watch for the terms-accepted event).",access_expired:"The candidate's access has ended. Renew it (accessStart, or the renewal calls when renewals need approval), then create a new session.",course_access_required:"The candidate's access has not been started. Start it with hb.onlineTraining.candidates.accessStart() on your server, then create the session again.",payment_pending:"The candidate has a payment link that is not paid yet. Ask them to pay it, then create the session again.",renewal_approval_required:"A renewal waits for approval. Approve it (renewalApprove or in Hub), then create the session again.",course_not_pending:"The candidate has already completed this course. Only courses still to do can be opened."};function b(o){return Y[o]}function K(o){if(typeof o!="object"||o===null)return!1;const e=o;return e.hb!==1?!1:e.type==="ready"?typeof e.nonce=="string"&&e.nonce.length>0&&e.nonce.length<=200:e.type==="event"?typeof e.name=="string":e.type==="resize"?typeof e.height=="number"&&Number.isFinite(e.height):e.type==="scroll-top"}function z(o){if(typeof o!="object"||o===null)return!1;const e=o;return typeof e.sessionId=="string"&&(e.kind==="course"||e.kind==="test"||e.kind==="oh_form")&&typeof e.launchToken=="string"&&typeof e.frameUrl=="string"&&(typeof e.expiresAt=="string"||e.expiresAt===null)&&typeof e.sessionExpiresAt=="string"&&typeof e.allowedOrigin=="string"}const R="allow-scripts allow-same-origin allow-forms allow-downloads allow-popups allow-popups-to-escape-sandbox",G="fullscreen; picture-in-picture; encrypted-media",J={course:"Course",test:"Test",oh_form:"Occupational health form"},Q=100,Z=3e4;function D(o){let e;try{e=new URL(o.frameUrl)}catch{throw new Error("The session has no valid frameUrl.")}const h=e.hostname==="localhost"||e.hostname==="127.0.0.1"||e.hostname.endsWith(".localhost")||e.hostname.endsWith(".test");if(e.protocol!=="https:"&&!(e.protocol==="http:"&&h))throw new Error("The frame must be served over https.");return e.origin}function H(o){const{endpoint:e,kind:h,courseId:d,formShortcode:C,fetchInit:u}=o;if(!e||!h)throw new Error("mount needs either getSession, or endpoint and kind.");return async({reason:l,sessionId:a})=>{const g=await fetch(e,{credentials:"same-origin",...u,method:"POST",headers:{"content-type":"application/json",...u==null?void 0:u.headers},body:JSON.stringify(l==="refresh"?{action:"refresh",sessionId:a}:{action:"create",kind:h,courseId:d,formShortcode:C})}),s=await g.json().catch(()=>({}));if(!g.ok){const f=typeof s.message=="string"?s.message:`Your server answered HTTP ${g.status}.`,w=typeof s.error=="string"&&I.includes(s.error)?s.error:void 0;throw Object.assign(new Error(f),w?{code:w,details:M(s.details)}:{})}return s}}function ee(o,e){var L;const h=o.ownerDocument,d=h.defaultView,C=(L=e.getSession)!=null?L:H(e),u=new Map;let l=!1,a,g="",s,f,w,j=0,A=!1,N,x;const P=new Promise((n,r)=>{N=n,x=r});P.catch(()=>{});const _=(n,r)=>{var c,T,k,E,S,i,m,v,U,V,W;if(l)return;const t=r!=null?r:{};switch((c=e.onEvent)==null||c.call(e,{name:n,data:r}),n){case"ready":(T=e.onReady)==null||T.call(e);break;case"progress":(k=e.onProgress)==null||k.call(e,t);break;case"completed":(E=e.onCompleted)==null||E.call(e,t);break;case"passed":(S=e.onPassed)==null||S.call(e,t);break;case"failed":(i=e.onFailed)==null||i.call(e,t);break;case"submitted":(m=e.onSubmitted)==null||m.call(e,t);break;case"test-requested":(v=e.onTestRequested)==null||v.call(e,t);break;case"terms-accepted":(U=e.onTermsAccepted)==null||U.call(e,t);break;case"error":(V=e.onError)==null||V.call(e,t);break}(W=u.get(n))==null||W.forEach(se=>se(t))},p=(n,r,t)=>{d.clearTimeout(f),x(new Error(r)),_("error",{code:n,message:r||b(n),...t?{details:t}:{}})},B=()=>{var n;d.clearTimeout(f),f=d.setTimeout(()=>p("frame_timeout",b("frame_timeout")),(n=e.readyTimeoutMs)!=null?n:2e4)},q=n=>{var r;(r=s==null?void 0:s.contentWindow)==null||r.postMessage(n,g)},O=async n=>{const r=await C(n);if(!z(r))throw new Error("getSession must return the session your server got from the SDK.");return r},re=()=>w||(w=(async()=>{let n;for(let r=0;r<2;r++)try{const t=await O({reason:"refresh",sessionId:a==null?void 0:a.sessionId});if(l)return;if(t.sessionId!==(a==null?void 0:a.sessionId)||D(t)!==g){p("session_changed","The refresh returned a different session. Your route must call hb.embed.refresh(sessionId).");return}a=t,q({hb:1,type:"token",token:t.launchToken});return}catch(t){if(n=t,l)return;await new Promise(c=>setTimeout(c,1500))}l||_("error",{code:"token_refresh_failed",message:n instanceof Error?n.message:"Could not renew the session."})})().finally(()=>{w=void 0}),w),F=n=>{var t,c,T,k,E,S;if(l||!s||n.source!==s.contentWindow||n.origin!==g||!K(n.data))return;const r=n.data;if(r.type==="ready")j+=1,A=!1,d.clearTimeout(f),(async()=>{try{let i=a==null?void 0:a.launchToken;const m=a!=null&&a.expiresAt?Date.parse(a.expiresAt)<=Date.now():!1;if(j>1||m){const v=await O({reason:"refresh",sessionId:a==null?void 0:a.sessionId});if(l)return;a=v,i=v.launchToken}q({hb:1,type:"init",nonce:r.nonce,token:i}),B()}catch(i){p("init_failed",i instanceof Error?i.message:"Could not start the frame.")}})();else if(r.type==="resize"){if(e.height===void 0||e.height==="auto"){const i=Math.min(Z,Math.max((t=e.minHeight)!=null?t:320,Math.ceil(r.height)));s&&(s.style.height=`${Math.max(Q,i)}px`)}}else if(r.type==="scroll-top"){if(s&&((c=e.onScrollTop)==null?void 0:c.call(e,s))!==!1&&e.scrollIntoView!==!1&&s.getBoundingClientRect().top<0){const i=typeof d.matchMedia=="function"&&d.matchMedia("(prefers-reduced-motion: reduce)").matches;s.scrollIntoView({block:"start",behavior:i?"auto":"smooth"})}}else if(r.type==="event"){if(r.name==="token-expiring"){_("token-expiring",r.data),re();return}if(r.name==="ready"){if(d.clearTimeout(f),A)return;A=!0,N()}else if(r.name==="error"){const i=(T=r.data)!=null?T:{},m=typeof i.code=="string"?i.code:"error";d.clearTimeout(f),A||x(new Error((E=(k=i.message)!=null?k:b(m))!=null?E:m)),_("error",{...typeof r.data=="object"&&r.data?r.data:{},code:m,message:(S=i.message)!=null?S:b(m)});return}_(r.name,r.data)}};return d.addEventListener("message",F),(async()=>{var n,r;try{const t=await O({reason:"initial"});if(l)return;if(g=D(t),t.allowedOrigin!==d.location.origin){p("origin_mismatch",`This session was created for ${t.allowedOrigin} but this page is ${d.location.origin}. Pass the right origin when your server creates the session.`);return}a=t,s=h.createElement("iframe"),s.setAttribute("sandbox",R),s.setAttribute("allow",G),s.setAttribute("allowfullscreen",""),s.setAttribute("referrerpolicy","origin"),s.setAttribute("title",(n=e.title)!=null?n:J[t.kind]),s.setAttribute("scrolling",typeof e.height=="number"?"auto":"no"),s.style.cssText="display:block;width:100%;border:0;background:#fff;color-scheme:light;",s.style.height=`${typeof e.height=="number"?e.height:(r=e.minHeight)!=null?r:320}px`,B(),s.src=t.frameUrl,o.appendChild(s)}catch(t){const c=t==null?void 0:t.code;if(typeof c=="string"&&I.includes(c)){p(c,t.message||b(c)||c,M(t.details));return}p("session_failed",t instanceof Error?t.message:"Could not get a session from your server.")}})(),{destroy(){l||(l=!0,d.removeEventListener("message",F),d.clearTimeout(f),u.clear(),s==null||s.remove(),s=void 0)},on(n,r){var c;const t=(c=u.get(n))!=null?c:new Set;return t.add(r),u.set(n,t),()=>t.delete(r)},off(n,r){var t;(t=u.get(n))==null||t.delete(r)},ready:P,get session(){return a},get destroyed(){return l}}}const te="0.4.0";return y.SANDBOX=R,y.mount=ee,y.sessionFetcher=H,y.version=te,Object.defineProperty(y,Symbol.toStringTag,{value:"Module"}),y})({});
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@healthier-business/hub-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.4.0",
|
|
4
4
|
"description": "The official JavaScript and TypeScript SDK for the Healthier Business Hub API v2: automatic tokens, typed resources for every portal, signed webhooks and embeddable courses, tests and OH forms.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Sanchit Patil",
|