@healthier-business/hub-sdk 0.3.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 CHANGED
@@ -289,6 +289,7 @@ Every event below is sent by the Hub frame. The callbacks (`onProgress`, `onComp
289
289
  | `completed` | The learner finished the course. Final. | `{ courseId }`: the Online Training course id of the session. |
290
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. |
291
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. |
292
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. |
293
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). |
294
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. |
@@ -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.3.0";
7
+ readonly version: "0.4.0";
8
8
  };
9
- export declare const version = "0.3.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;
@@ -111,6 +111,9 @@ function mount(element, options) {
111
111
  case 'submitted':
112
112
  options.onSubmitted?.(d);
113
113
  break;
114
+ case 'test-requested':
115
+ options.onTestRequested?.(d);
116
+ break;
114
117
  case 'terms-accepted':
115
118
  options.onTermsAccepted?.(d);
116
119
  break;
@@ -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 +1 @@
1
- export declare const VERSION = "0.3.0";
1
+ export declare const VERSION = "0.4.0";
@@ -1,4 +1,4 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.VERSION = void 0;
4
- exports.VERSION = '0.3.0';
4
+ exports.VERSION = '0.4.0';
@@ -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.3.0";
7
+ readonly version: "0.4.0";
8
8
  };
9
- export declare const version = "0.3.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;
@@ -106,6 +106,9 @@ export function mount(element, options) {
106
106
  case 'submitted':
107
107
  options.onSubmitted?.(d);
108
108
  break;
109
+ case 'test-requested':
110
+ options.onTestRequested?.(d);
111
+ break;
109
112
  case 'terms-accepted':
110
113
  options.onTermsAccepted?.(d);
111
114
  break;
@@ -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 +1 @@
1
- export declare const VERSION = "0.3.0";
1
+ export declare const VERSION = "0.4.0";
@@ -1 +1 @@
1
- export const VERSION = '0.3.0';
1
+ export const VERSION = '0.4.0';
@@ -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.3.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.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",