@puzzmo/sdk 1.0.70 → 1.0.71
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/dist/bootstrapPayload.spec.d.ts +2 -0
- package/dist/bootstrapPayload.spec.d.ts.map +1 -0
- package/dist/{createSimulator-DUZOd1Hx.js → createSimulator-treFHkmV.js} +19 -18
- package/dist/{createSimulator-DUZOd1Hx.js.map → createSimulator-treFHkmV.js.map} +1 -1
- package/dist/{createSimulator-Ce3StrQI.cjs → createSimulator-uk8H5md8.cjs} +2 -2
- package/dist/{createSimulator-Ce3StrQI.cjs.map → createSimulator-uk8H5md8.cjs.map} +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.global.js +1 -1
- package/dist/index.global.js.map +1 -1
- package/dist/index.js +100 -107
- package/dist/index.js.map +1 -1
- package/dist/pico8/index.cjs.map +1 -1
- package/dist/pico8/index.d.ts +2 -2
- package/dist/pico8/index.d.ts.map +1 -1
- package/dist/pico8/index.js.map +1 -1
- package/dist/sdk.d.ts +13 -6
- package/dist/sdk.d.ts.map +1 -1
- package/dist/sdk.session.spec.d.ts +2 -0
- package/dist/sdk.session.spec.d.ts.map +1 -0
- package/dist/simulator/createSimulator.d.ts.map +1 -1
- package/dist/simulator/index.cjs +1 -1
- package/dist/simulator/index.js +1 -1
- package/dist/simulator/standalone.cjs +1 -1
- package/dist/simulator/standalone.js +1 -1
- package/dist/simulator/types.d.ts +5 -0
- package/dist/simulator/types.d.ts.map +1 -1
- package/dist/types.d.ts +2 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/vite.cjs.map +1 -1
- package/dist/vite.d.ts +5 -0
- package/dist/vite.d.ts.map +1 -1
- package/dist/vite.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./objectWithoutProperties-CL_8JSCP.cjs`),t=require(`./objectSpread2-BU9HzoRm.cjs`),n=require(`./asyncToGenerator-Tjg_Hpik.cjs`);var r=[`startOrFindGameplay`],i=[`puzzle`],a=[`game`,`viewerMetadata`];const o=n=>{var o,c,l;let{startOrFindGameplay:u}=n,d=e.t(n,r);if(d.game)return d;let f=u==null?void 0:u.gamePlayed,p=s((o=f==null||(c=f.puzzle)==null?void 0:c.game)==null?{}:o);if(!f)return t.t(t.t({},d),{},{game:p});let{puzzle:m}=f,h=e.t(f,i),{game:g,viewerMetadata:_}=m,v=e.t(m,a);return t.t(t.t({},d),{},{game:p,session:{gameplay:h,puzzle:v},viewerMetadata:(l=d.viewerMetadata)==null?_:l})};var s=e=>{var t,n,r,i,a,o,s,c;let l=e.flagsArr;return{id:(t=e.id)==null?``:t,slug:(n=e.slug)==null?``:n,stableSlug:(r=(i=e.stableSlug)==null?e.slug:i)==null?``:r,displayName:(a=e.displayName)==null?``:a,version:{id:``,label:null,featuresArr:(o=e.featuresArr)==null?[0]:o,flagsArr:Array.isArray(l)?l:typeof l==`number`?[l]:[0],runtime:{id:``,version:e.assetsSha||e.assetsBaseURL?{id:``,assetsSha:(s=e.assetsSha)==null?``:s,assetsBaseURL:(c=e.assetsBaseURL)==null?``:c}:null}}}},c=function(){var e=n.t(function*(e,n,r,i){try{let a=t.t(t.t({},e),{},{eventType:n,elapsedTimeOnComplete:i,metadata:r}),o=yield fetch(`${e.apiRoot}events`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(a),keepalive:!0});o.ok||console.warn(`Analytics event failed: ${n} - ${o.status} ${o.statusText}`)}catch(e){console.warn(`Analytics event error: ${n}`,e)}});return function(t,n,r,i){return e.apply(this,arguments)}}();const l=e=>{var n;let r={context:t.t(t.t({},e),{},{deviceType:(n=e.deviceType)==null?u():n}),updateCount:0,startTime:new Date,tracked:{pageView:!1,gameplayActive:!1,active30s:!1,completed:!1}};return{trackEvent:(e,t)=>{let n=(new Date().getTime()-r.startTime.getTime())/1e3;switch(e){case`READY_GAME_LOADED`:r.tracked.pageView||(c(r.context,`page_view`),r.tracked.pageView=!0);break;case`UPLOAD_NEW_GAME_STATE`:r.updateCount++,r.updateCount>2&&!r.tracked.gameplayActive&&(c(r.context,`gameplay_active`),r.tracked.gameplayActive=!0),n>30&&(r.tracked.gameplayActive||(c(r.context,`gameplay_active`),r.tracked.gameplayActive=!0),r.tracked.active30s||(c(r.context,`active_30s`),r.tracked.active30s=!0));break;case`GAME_COMPLETED`:!r.tracked.completed&&t!=null&&t.input&&(c(r.context,`completed`,{},t.input.elapsedTimeSecs),r.tracked.completed=!0);break}},trackLinkClick:e=>{c(r.context,`link_click`,e)}}};var u=()=>{var e,t,n;if(typeof navigator>`u`||typeof window>`u`)return`unknown`;let r=navigator.userAgent;if(/iPad/.test(r)||/Macintosh/.test(r)&&navigator.maxTouchPoints>1)return`tablet`;let i=(e=navigator.userAgentData)==null?void 0:e.mobile;return/iPhone|iPod/.test(r)||i?`mobile`:/Android/.test(r)?/Mobile/.test(r)?`mobile`:`tablet`:/Mobile|Windows Phone/.test(r)?`mobile`:(t=(n=window).matchMedia)!=null&&t.call(n,`(pointer: coarse)`).matches?Math.min(screen.width,screen.height)<600?`mobile`:`tablet`:`desktop`};const d=e=>{if(!_(e))return null;let t=p();if(!t.enabled)return null;let n=m(e,t.apiRoot);return n?l(n):null},f=e=>{if(typeof document>`u`)return()=>{};let t=t=>{var n,r;let i=t.target;if(!(i instanceof Element))return;let a=i.closest(`a[href]`);a instanceof HTMLAnchorElement&&e({href:a.href,text:(n=(r=a.textContent)==null?void 0:r.trim())==null?``:n,target:a.target})};return document.addEventListener(`click`,t),()=>document.removeEventListener(`click`,t)};var p=()=>{if(typeof window>`u`||!window.location)return{apiRoot:``,enabled:!1};let e=window.location.hostname;return e===`localhost`||e===`127.0.0.1`||e===`0.0.0.0`||e===`[::1]`||e.endsWith(`.localhost`)?{apiRoot:``,enabled:!1}:{apiRoot:e.includes(`staging`)?`https://api-staging.puzzmo.com/`:`https://api.puzzmo.com/`,enabled:!0}};const m=(e,t)=>{var n,r,i,a,o,s,c,l;let u=e==null?void 0:e.session;if(!u)return null;let d=u.gameplay,f=u.puzzle,p=(n=e==null?void 0:e.hostContext)==null?[]:n,m=p.find(e=>(e==null?void 0:e.type)===`embed`);return{gameSlug:(e==null||(r=e.game)==null?void 0:r.slug)||`unknown`,puzzleID:f.id,gameplayOwnerID:d.ownerID||(e==null||(i=e.userState)==null?void 0:i.id)||`unknown`,apiRoot:t,userType:h(e==null||(a=e.currentUser)==null?void 0:a.type),runtimeType:v(p),userID:e==null||(o=e.currentUser)==null?void 0:o.id,teamSlug:((s=f.team)==null?void 0:s.slug)||void 0,partnerSlug:(m==null||(c=m.partner)==null?void 0:c.slug)||(e==null?void 0:e.partnerSlug)||void 0,dailyDateKey:(l=f.mostRecentDaily)==null||(l=l.daily)==null?void 0:l.dateKey,embedID:(m==null?void 0:m.embedID)||void 0}};var h=e=>!e||e===`Unverified`?`anon`:e===`Paid`?`paid`:`user`,g=512,_=e=>{var t,n;return(((t=e==null||(n=e.game)==null?void 0:n.version.flagsArr[0])==null?0:t)&g)===g},v=e=>{let t=e.find(e=>(e==null?void 0:e.type)===`embed`);if(t)return t.host===`msn`?`msn`:`iframe`;let n=e.find(e=>(e==null?void 0:e.type)===`app`);return(n==null?void 0:n.host)===`__embed`?`simple_embed`:(n==null?void 0:n.host)===`app-embed`?`app_embed`:(n==null?void 0:n.host)===`ios-app`?`ios_native`:`puzzmo_com`},y=[`inputString`];function b(e){let t=e>=3600*1e3;return new Date(e).toISOString().slice(t?11:14,-1).split(`.`)[0]}function x(e=0,t=0){let n=e,r=t,i=0,a,o,s,c=()=>{var e;if(o===void 0)return n+r;if(a!==void 0)return a;let t=((e=s)==null?performance.now():e)-o-i;return n+r+t};return{_init:()=>{o===void 0&&(o=performance.now(),s=void 0)},_pause:()=>{s!==void 0||o===void 0||(s=performance.now())},_resume:()=>{s!==void 0&&(i+=performance.now()-s,s=void 0)},_reset:(e=0,t=0)=>{n=e,r=t,i=0,a=void 0,o=void 0,s=void 0},_conclude:()=>{if(s!==void 0){a=c();return}if(o===void 0){a=n+r;return}a=c()},timeMs:()=>c(),timeSecs:()=>c()/1e3,addedTimeMs:()=>r,addedTimeSecs:()=>r/1e3,timeWithoutPenaltySecs:()=>(c()-r)/1e3,addPenalty:e=>{r+=e},setPenalty:e=>{r=e},isPaused:()=>s!==void 0||o===void 0,isRunning:()=>o!==void 0&&s===void 0,display:()=>{let e=c()-r;return[b(Math.max(0,e)),r===0?``:b(r)]}}}function S(){let e=new Map;return typeof window<`u`&&window.addEventListener(`message`,t=>{var n;if(!(!(t==null||(n=t.data)==null)&&n.type))return;let r=t.data.type,i=e.get(r);if(i){var a,o;let e=(a=(o=t.data.data)==null?t.data.json:o)==null?{}:a;r!==`TIMER_TICK`&&r!==`TIMER_SYNC`&&console.log(`[Puzzmo SDK] received:`,r,e),i.forEach(t=>t(e))}}),{sendMessage:(e,t)=>{var n,r;let i={type:e,json:t,_:`p`,__:`mp`,private:!0};`parent`in window&&window.parent!==window&&window.parent.postMessage(i,`*`),window.postMessage(i,`*`),`webkit`in window&&!((n=window.webkit)==null||(n=n.messageHandlers)==null)&&n.app&&window.webkit.messageHandlers.app.postMessage(i),`puzzmoMessageString`in window&&window.puzzmoMessageString(JSON.stringify(i)),`ReactNativeWebView`in window&&(r=window.ReactNativeWebView)!=null&&r.postMessage&&window.ReactNativeWebView.postMessage(JSON.stringify(i)),e!==`TIMER_TICK`&&e!==`TIMER_SYNC`&&console.log(`[Puzzmo SDK] sent:`,e,t)},onMessage:(t,n)=>(e.has(t)||e.set(t,new Set),e.get(t).add(n),()=>{var r;(r=e.get(t))==null||r.delete(n)})}}var C=`1.0`,w=S();const T=(r={})=>{var i;let a=null,s=null,c=()=>{var e;return a==null||(e=a.session)==null?void 0:e.gameplay},l=()=>{var e,t;return(e=(t=c())==null?void 0:t.id)==null?null:e},u=()=>{var e,t;return(e=a==null||(t=a.session)==null?void 0:t.puzzle.puzzle)==null?null:e},p=()=>{var e,t;return(e=(t=c())==null?void 0:t.boardState)==null?null:e},m=()=>{var e;return(e=a==null?void 0:a.theme)==null?null:e},h=()=>{var e,t;return(e=(t=c())==null?void 0:t.completed)==null?!1:e},g=new Map,_=null,v=null,b=!1,S=(e,t)=>{b||v==null||v.trackEvent(e,t)},T=x(),D=null,O=null,k=()=>{D||(D=setInterval(()=>{if(T.isPaused())return;let[e,t]=T.display();w.sendMessage(`TIMER_TICK`,{display:[e,t]})},500),O=setInterval(()=>{T.isPaused()||w.sendMessage(`TIMER_SYNC`,Math.floor(T.timeWithoutPenaltySecs()))},1e4))},A=()=>{D&&(clearInterval(D),D=null),O&&(clearInterval(O),O=null)},j=(e,t)=>{let n=g.get(e);n&&n.forEach(e=>e(t))};w.onMessage(`START_GAME`,()=>{T._init(),k(),j(`start`)});let M=()=>{let e=T.isPaused();T._pause(),T.isPaused()!==e&&j(`pause`)},N=()=>{let e=T.isPaused();T._resume(),T.isPaused()!==e&&j(`resume`)};w.onMessage(`PAUSE_GAME`,M),w.onMessage(`RESUME_GAME`,N),w.onMessage(`SETTINGS_UPDATE`,e=>{_=t.t(t.t({},_),e),j(`settingsUpdate`,_)}),w.onMessage(`KEYBOARD_KEY_PRESS`,e=>j(`keyboardKeyPress`,e)),w.onMessage(`KEYBOARD_CURSOR_CHANGE`,e=>j(`keyboardCursorChange`,e)),w.onMessage(`KEYBOARD_CURSOR_END`,()=>j(`keyboardCursorEnd`)),w.onMessage(`RETRY_PUZZLE`,()=>{T._reset(),A(),j(`retry`)}),w.onMessage(`READY_DATA`,e=>{var t;let n=o(e);a=n;let r=(t=n.session)==null?void 0:t.gameplay;if(_===null){var i,c;let e=n.game.slug,t=e?(i=n.userState)==null||(i=i.gameSettings)==null?void 0:i[e]:null;if(typeof t==`string`)try{t=JSON.parse(t)}catch(e){t=null}_=(c=t)==null?{}:c}if(r){var l,u;let e=((l=r.elapsedTimeSecs)==null?0:l)*1e3,t=((u=r.additionalTimeAddedSecs)==null?0:u)*1e3;T._reset(e,t)}if(!v){var p;v=d(n),b=(p=r==null?void 0:r.completed)==null?!1:p,v&&f(e=>v.trackLinkClick(e))}s&&(s(n),s=null)});let P={timeMs:()=>T.timeMs(),timeSecs:()=>T.timeSecs(),addedTimeMs:()=>T.addedTimeMs(),addedTimeSecs:()=>T.addedTimeSecs(),timeWithoutPenaltySecs:()=>T.timeWithoutPenaltySecs(),display:()=>T.display(),addPenalty:e=>T.addPenalty(e),setPenalty:e=>T.setPenalty(e),isPaused:()=>T.isPaused(),isRunning:()=>T.isRunning(),pause:M,resume:N},F={send:(e,t)=>w.sendMessage(e,t),on:(e,t)=>w.onMessage(e,t),timer:P,bootstrap:()=>a},I={};for(let e of(i=r.plugins)==null?[]:i)I[e.name]=e.setup(F);return{timer:P,plugins:I,gameReady:function(){var e=n.t(function*(){var e;if(w.sendMessage(`READY`,{runtimeContract:C}),u()){let e=p();return{puzzleString:u(),inputString:e,boardState:e,theme:m(),completed:h(),readyData:a}}let t=(e=r.timeout)==null?5e3:e;yield new Promise((e,n)=>{s=e,setTimeout(()=>{s&&(s=null,n(Error(`Timeout waiting for READY_DATA after ${t}ms`)))},t)});let n=u();if(!n)throw Error(`READY_DATA received but no puzzle data found`);let i=p();return{puzzleString:n,inputString:i,boardState:i,theme:m(),completed:h(),readyData:a}});return function(){return e.apply(this,arguments)}}(),gameLoaded:(e={})=>{w.sendMessage(`READY_GAME_LOADED`,{state:e,gameRuntimeContract:C,embedRuntimeContract:`1.0`}),S(`READY_GAME_LOADED`)},on:(e,t)=>(g.has(e)||g.set(e,new Set),g.get(e).add(t),()=>{var n;(n=g.get(e))==null||n.delete(t)}),off:(e,t)=>{var n;(n=g.get(e))==null||n.delete(t)},updateGameState:(e,t)=>{var n,r;let i=l();i&&(w.sendMessage(`UPLOAD_NEW_GAME_STATE`,{id:i,input:{boardState:e,elapsedTimeSecs:(n=t==null?void 0:t.elapsedTimeSecs)==null?T.timeWithoutPenaltySecs():n,additionalTimeAddedSecs:(r=t==null?void 0:t.additionalTimeAddedSecs)==null?T.addedTimeSecs():r,collabUserReferences:[]}}),S(`UPLOAD_NEW_GAME_STATE`))},gameCompleted:(n,r)=>{var i,a,o,s,c;T._conclude(),A();let{inputString:u}=n,d=t.t(t.t({},e.t(n,y)),{},{boardState:u==null?n.boardState:u,elapsedTimeSecs:(i=n.elapsedTimeSecs)==null?T.timeWithoutPenaltySecs():i,additionalTimeAddedSecs:(a=n.additionalTimeAddedSecs)==null?T.addedTimeSecs():a}),f=(o=r==null?void 0:r.deeds)==null?[]:o;f.push({id:`points`,value:n.pointsAwarded}),f.push({id:`time`,value:Math.round((s=d.elapsedTimeSecs)==null?0:s)+Math.round((c=d.additionalTimeAddedSecs)==null?0:c)});let p=l();p&&(w.sendMessage(`GAME_COMPLETED`,{id:p,input:d,config:r}),S(`GAME_COMPLETED`,{input:d}))},showCompletionScreen:e=>{w.sendMessage(`SHOW_GAME_COMPLETE_SCREEN`,{results:e,showRetry:!0})},hitCheckpoint:(e,t,n)=>{var r;if(!l())return;let i=(r=p())==null?``:r,a={elapsedTimeSecs:T.timeWithoutPenaltySecs(),additionalTimeAddedSecs:T.addedTimeSecs()};w.sendMessage(`HIT_CHECKPOINT`,{checkpointName:e,gameplay:{inputStr:i,play:a},checkpointConfig:t,augConfig:n==null?{}:n})},settings:{initialize:e=>(_=t.t(t.t({},E(e)),_),w.sendMessage(`INITIALIZE_SETTINGS`,{components:e,settings:_}),_),get:()=>{var e;return(e=_)==null?{}:e},update:e=>(_=t.t(t.t({},_),e),w.sendMessage(`UPDATE_SETTINGS_FROM_EMBED`,{settings:_}),_)},keyboard:{show:e=>{w.sendMessage(`KEYBOARD_UPDATE_CONFIG`,e)},hide:()=>{w.sendMessage(`KEYBOARD_UPDATE_CONFIG`,{layout:[],symbols:{},highlight:[],disabled:[],xl:[],l:[],supportsDragCursor:!1})}},haptics:{play:(e,t)=>{var n;w.sendMessage(`SENSORY_EVENT`,{id:(n=t==null?void 0:t.id)==null?e:n,haptic:e})}},_hostAPI:w}};function E(e){let t={};for(let n of e)n.type===`split`?Object.assign(t,E(n.content)):`name`in n&&(t[n.name]=n.defaultValue);return t}const D={layout:[`qwertyuiop`,`asdfghjkl`,`↵zxcvbnm⌫`,void 0],symbols:{"↵":`enter`,"⌫":`bsp`},highlight:[`↵`,`⌫`],disabled:[],xl:[],l:[`↵`,`⌫`],supportsDragCursor:!1},O=e=>{let n={};for(let a of e)for(let e of a.keys){var r,i;let o={},s=t.t(t.t({},(r=n[e])==null?void 0:r.text),a.text),c=t.t(t.t({},(i=n[e])==null?void 0:i.background),a.background);Object.keys(s).length&&(o.text=s),Object.keys(c).length&&(o.background=c),n[e]=o}return n};var k=class extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name=`EditorImportError`}};exports.EditorImportError=k,exports.createPuzzmoSDK=T,exports.defaultKeyboardConfig=D,exports.keyStylesFromRules=O;
|
|
1
|
+
Object.defineProperty(exports,Symbol.toStringTag,{value:`Module`});const e=require(`./objectWithoutProperties-CL_8JSCP.cjs`),t=require(`./objectSpread2-BU9HzoRm.cjs`),n=require(`./asyncToGenerator-Tjg_Hpik.cjs`);var r=[`startOrFindGameplay`],i=[`puzzle`],a=[`game`,`viewerMetadata`];const o=n=>{var o,c,l;let{startOrFindGameplay:u}=n,d=e.t(n,r);if(d.game)return d;let f=u==null?void 0:u.gamePlayed,p=s((o=f==null||(c=f.puzzle)==null?void 0:c.game)==null?{}:o);if(!f)return t.t(t.t({},d),{},{game:p});let{puzzle:m}=f,h=e.t(f,i),{game:g,viewerMetadata:_}=m,v=e.t(m,a);return t.t(t.t({},d),{},{game:p,session:{gameplay:h,puzzle:v},viewerMetadata:(l=d.viewerMetadata)==null?_:l})};var s=e=>{var t,n,r,i,a,o,s,c;let l=e.flagsArr;return{id:(t=e.id)==null?``:t,slug:(n=e.slug)==null?``:n,stableSlug:(r=(i=e.stableSlug)==null?e.slug:i)==null?``:r,displayName:(a=e.displayName)==null?``:a,version:{id:``,label:null,featuresArr:(o=e.featuresArr)==null?[0]:o,flagsArr:Array.isArray(l)?l:typeof l==`number`?[l]:[0],runtime:{id:``,version:e.assetsSha||e.assetsBaseURL?{id:``,assetsSha:(s=e.assetsSha)==null?``:s,assetsBaseURL:(c=e.assetsBaseURL)==null?``:c}:null}}}},c=function(){var e=n.t(function*(e,n,r,i){try{let a=t.t(t.t({},e),{},{eventType:n,elapsedTimeOnComplete:i,metadata:r}),o=yield fetch(`${e.apiRoot}events`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(a),keepalive:!0});o.ok||console.warn(`Analytics event failed: ${n} - ${o.status} ${o.statusText}`)}catch(e){console.warn(`Analytics event error: ${n}`,e)}});return function(t,n,r,i){return e.apply(this,arguments)}}();const l=e=>{var n;let r={context:t.t(t.t({},e),{},{deviceType:(n=e.deviceType)==null?u():n}),updateCount:0,startTime:new Date,tracked:{pageView:!1,gameplayActive:!1,active30s:!1,completed:!1}};return{trackEvent:(e,t)=>{let n=(new Date().getTime()-r.startTime.getTime())/1e3;switch(e){case`READY_GAME_LOADED`:r.tracked.pageView||(c(r.context,`page_view`),r.tracked.pageView=!0);break;case`UPLOAD_NEW_GAME_STATE`:r.updateCount++,r.updateCount>2&&!r.tracked.gameplayActive&&(c(r.context,`gameplay_active`),r.tracked.gameplayActive=!0),n>30&&(r.tracked.gameplayActive||(c(r.context,`gameplay_active`),r.tracked.gameplayActive=!0),r.tracked.active30s||(c(r.context,`active_30s`),r.tracked.active30s=!0));break;case`GAME_COMPLETED`:!r.tracked.completed&&t!=null&&t.input&&(c(r.context,`completed`,{},t.input.elapsedTimeSecs),r.tracked.completed=!0);break}},trackLinkClick:e=>{c(r.context,`link_click`,e)}}};var u=()=>{var e,t,n;if(typeof navigator>`u`||typeof window>`u`)return`unknown`;let r=navigator.userAgent;if(/iPad/.test(r)||/Macintosh/.test(r)&&navigator.maxTouchPoints>1)return`tablet`;let i=(e=navigator.userAgentData)==null?void 0:e.mobile;return/iPhone|iPod/.test(r)||i?`mobile`:/Android/.test(r)?/Mobile/.test(r)?`mobile`:`tablet`:/Mobile|Windows Phone/.test(r)?`mobile`:(t=(n=window).matchMedia)!=null&&t.call(n,`(pointer: coarse)`).matches?Math.min(screen.width,screen.height)<600?`mobile`:`tablet`:`desktop`};const d=e=>{if(!_(e))return null;let t=p();if(!t.enabled)return null;let n=m(e,t.apiRoot);return n?l(n):null},f=e=>{if(typeof document>`u`)return()=>{};let t=t=>{var n,r;let i=t.target;if(!(i instanceof Element))return;let a=i.closest(`a[href]`);a instanceof HTMLAnchorElement&&e({href:a.href,text:(n=(r=a.textContent)==null?void 0:r.trim())==null?``:n,target:a.target})};return document.addEventListener(`click`,t),()=>document.removeEventListener(`click`,t)};var p=()=>{if(typeof window>`u`||!window.location)return{apiRoot:``,enabled:!1};let e=window.location.hostname;return e===`localhost`||e===`127.0.0.1`||e===`0.0.0.0`||e===`[::1]`||e.endsWith(`.localhost`)?{apiRoot:``,enabled:!1}:{apiRoot:e.includes(`staging`)?`https://api-staging.puzzmo.com/`:`https://api.puzzmo.com/`,enabled:!0}};const m=(e,t)=>{var n,r,i,a,o,s,c,l;let u=e==null?void 0:e.session;if(!u)return null;let d=u.gameplay,f=u.puzzle,p=(n=e==null?void 0:e.hostContext)==null?[]:n,m=p.find(e=>(e==null?void 0:e.type)===`embed`);return{gameSlug:(e==null||(r=e.game)==null?void 0:r.slug)||`unknown`,puzzleID:f.id,gameplayOwnerID:d.ownerID||(e==null||(i=e.userState)==null?void 0:i.id)||`unknown`,apiRoot:t,userType:h(e==null||(a=e.currentUser)==null?void 0:a.type),runtimeType:v(p),userID:e==null||(o=e.currentUser)==null?void 0:o.id,teamSlug:((s=f.team)==null?void 0:s.slug)||void 0,partnerSlug:(m==null||(c=m.partner)==null?void 0:c.slug)||(e==null?void 0:e.partnerSlug)||void 0,dailyDateKey:(l=f.mostRecentDaily)==null||(l=l.daily)==null?void 0:l.dateKey,embedID:(m==null?void 0:m.embedID)||void 0}};var h=e=>!e||e===`Unverified`?`anon`:e===`Paid`?`paid`:`user`,g=512,_=e=>{var t,n;return(((t=e==null||(n=e.game)==null?void 0:n.version.flagsArr[0])==null?0:t)&g)===g},v=e=>{let t=e.find(e=>(e==null?void 0:e.type)===`embed`);if(t)return t.host===`msn`?`msn`:`iframe`;let n=e.find(e=>(e==null?void 0:e.type)===`app`);return(n==null?void 0:n.host)===`__embed`?`simple_embed`:(n==null?void 0:n.host)===`app-embed`?`app_embed`:(n==null?void 0:n.host)===`ios-app`?`ios_native`:`puzzmo_com`},y=[`inputString`];function b(e){let t=e>=3600*1e3;return new Date(e).toISOString().slice(t?11:14,-1).split(`.`)[0]}function x(e=0,t=0){let n=e,r=t,i=0,a,o,s,c=()=>{var e;if(o===void 0)return n+r;if(a!==void 0)return a;let t=((e=s)==null?performance.now():e)-o-i;return n+r+t};return{_init:()=>{o===void 0&&(o=performance.now(),s=void 0)},_pause:()=>{s!==void 0||o===void 0||(s=performance.now())},_resume:()=>{s!==void 0&&(i+=performance.now()-s,s=void 0)},_reset:(e=0,t=0)=>{n=e,r=t,i=0,a=void 0,o=void 0,s=void 0},_conclude:()=>{if(s!==void 0){a=c();return}if(o===void 0){a=n+r;return}a=c()},timeMs:()=>c(),timeSecs:()=>c()/1e3,addedTimeMs:()=>r,addedTimeSecs:()=>r/1e3,timeWithoutPenaltySecs:()=>(c()-r)/1e3,addPenalty:e=>{r+=e},setPenalty:e=>{r=e},isPaused:()=>s!==void 0||o===void 0,isRunning:()=>o!==void 0&&s===void 0,display:()=>{let e=c()-r;return[b(Math.max(0,e)),r===0?``:b(r)]}}}function S(){let e=new Map;return typeof window<`u`&&window.addEventListener(`message`,t=>{var n;if(!(!(t==null||(n=t.data)==null)&&n.type))return;let r=t.data.type,i=e.get(r);if(i){var a,o;let e=(a=(o=t.data.data)==null?t.data.json:o)==null?{}:a;r!==`TIMER_TICK`&&r!==`TIMER_SYNC`&&console.log(`[Puzzmo SDK] received:`,r,e),i.forEach(t=>t(e))}}),{sendMessage:(e,t)=>{var n,r;let i={type:e,json:t,_:`p`,__:`mp`,private:!0};`parent`in window&&window.parent!==window&&window.parent.postMessage(i,`*`),window.postMessage(i,`*`),`webkit`in window&&!((n=window.webkit)==null||(n=n.messageHandlers)==null)&&n.app&&window.webkit.messageHandlers.app.postMessage(i),`puzzmoMessageString`in window&&window.puzzmoMessageString(JSON.stringify(i)),`ReactNativeWebView`in window&&(r=window.ReactNativeWebView)!=null&&r.postMessage&&window.ReactNativeWebView.postMessage(JSON.stringify(i)),e!==`TIMER_TICK`&&e!==`TIMER_SYNC`&&console.log(`[Puzzmo SDK] sent:`,e,t)},onMessage:(t,n)=>(e.has(t)||e.set(t,new Set),e.get(t).add(n),()=>{var r;(r=e.get(t))==null||r.delete(n)})}}var C=`1.1`,w=S();const T=(r={})=>{var i;let a=null,s=null,c=()=>{var e;return a==null||(e=a.session)==null?void 0:e.gameplay},l=()=>{var e,t;return(e=(t=c())==null?void 0:t.id)==null?null:e},u=()=>{var e,t;return(e=a==null||(t=a.session)==null?void 0:t.puzzle.puzzle)==null?null:e},p=()=>{var e,t;return(e=(t=c())==null?void 0:t.boardState)==null?null:e},m=()=>{var e;return(e=a==null?void 0:a.theme)==null?null:e},h=()=>{var e,t;return(e=(t=c())==null?void 0:t.completed)==null?!1:e},g=!1,_=e=>{if(g)return;g=!0;let t=a?`the host sent no play session, so there is no gameplay to save to`:`it was called before gameReady() resolved`;console.warn(`[Puzzmo SDK] ${e}() was ignored: ${t}`)},v=new Map,b=null,S=null,T=!1,D=(e,t)=>{T||S==null||S.trackEvent(e,t)},O=x(),k=null,A=null,j=()=>{k||(k=setInterval(()=>{if(O.isPaused())return;let[e,t]=O.display();w.sendMessage(`TIMER_TICK`,{display:[e,t]})},500),A=setInterval(()=>{O.isPaused()||w.sendMessage(`TIMER_SYNC`,Math.floor(O.timeWithoutPenaltySecs()))},1e4))},M=()=>{k&&(clearInterval(k),k=null),A&&(clearInterval(A),A=null)},N=(e,t)=>{let n=v.get(e);n&&n.forEach(e=>e(t))};w.onMessage(`START_GAME`,()=>{O._init(),j(),N(`start`)});let P=()=>{let e=O.isPaused();O._pause(),O.isPaused()!==e&&N(`pause`)},F=()=>{let e=O.isPaused();O._resume(),O.isPaused()!==e&&N(`resume`)};w.onMessage(`PAUSE_GAME`,P),w.onMessage(`RESUME_GAME`,F),w.onMessage(`SETTINGS_UPDATE`,e=>{b=t.t(t.t({},b),e),N(`settingsUpdate`,b)}),w.onMessage(`KEYBOARD_KEY_PRESS`,e=>N(`keyboardKeyPress`,e)),w.onMessage(`KEYBOARD_CURSOR_CHANGE`,e=>N(`keyboardCursorChange`,e)),w.onMessage(`KEYBOARD_CURSOR_END`,()=>N(`keyboardCursorEnd`)),w.onMessage(`RETRY_PUZZLE`,()=>{O._reset(),M(),N(`retry`)}),w.onMessage(`READY_DATA`,e=>{var t;let n=o(e);a=n;let r=(t=n.session)==null?void 0:t.gameplay;if(b===null){var i,c;let e=n.game.slug,t=e?(i=n.userState)==null||(i=i.gameSettings)==null?void 0:i[e]:null;if(typeof t==`string`)try{t=JSON.parse(t)}catch(e){t=null}b=(c=t)==null?{}:c}if(r){var l,u;let e=((l=r.elapsedTimeSecs)==null?0:l)*1e3,t=((u=r.additionalTimeAddedSecs)==null?0:u)*1e3;O._reset(e,t)}if(!S){var p;S=d(n),T=(p=r==null?void 0:r.completed)==null?!1:p,S&&f(e=>S.trackLinkClick(e))}s&&(s(n),s=null)});let I={timeMs:()=>O.timeMs(),timeSecs:()=>O.timeSecs(),addedTimeMs:()=>O.addedTimeMs(),addedTimeSecs:()=>O.addedTimeSecs(),timeWithoutPenaltySecs:()=>O.timeWithoutPenaltySecs(),display:()=>O.display(),addPenalty:e=>O.addPenalty(e),setPenalty:e=>O.setPenalty(e),isPaused:()=>O.isPaused(),isRunning:()=>O.isRunning(),pause:P,resume:F},L={send:(e,t)=>w.sendMessage(e,t),on:(e,t)=>w.onMessage(e,t),timer:I,bootstrap:()=>a},R={};for(let e of(i=r.plugins)==null?[]:i)R[e.name]=e.setup(L);return{timer:I,plugins:R,gameReady:function(){var e=n.t(function*(){if(w.sendMessage(`READY`,{runtimeContract:C}),!a){var e;let t=(e=r.timeout)==null?5e3:e;yield new Promise((e,n)=>{s=e,setTimeout(()=>{s&&(s=null,n(Error(`Timeout waiting for READY_DATA after ${t}ms`)))},t)})}let n=p();return t.t(t.t({},{puzzleString:u(),inputString:n,theme:m(),completed:h(),readyData:a}),{},{boardState:n})});return function(){return e.apply(this,arguments)}}(),gameLoaded:(e={})=>{w.sendMessage(`READY_GAME_LOADED`,{state:e,gameRuntimeContract:C,embedRuntimeContract:`1.0`}),D(`READY_GAME_LOADED`)},on:(e,t)=>(v.has(e)||v.set(e,new Set),v.get(e).add(t),()=>{var n;(n=v.get(e))==null||n.delete(t)}),off:(e,t)=>{var n;(n=v.get(e))==null||n.delete(t)},updateGameState:(e,t)=>{var n,r;let i=l();if(!i)return _(`updateGameState`);w.sendMessage(`UPLOAD_NEW_GAME_STATE`,{id:i,input:{boardState:e,elapsedTimeSecs:(n=t==null?void 0:t.elapsedTimeSecs)==null?O.timeWithoutPenaltySecs():n,additionalTimeAddedSecs:(r=t==null?void 0:t.additionalTimeAddedSecs)==null?O.addedTimeSecs():r,collabUserReferences:[]}}),D(`UPLOAD_NEW_GAME_STATE`)},gameCompleted:(n,r)=>{var i,o,s,c,u;O._conclude(),M();let{inputString:d}=n,f=t.t(t.t({},e.t(n,y)),{},{boardState:d==null?n.boardState:d,elapsedTimeSecs:(i=n.elapsedTimeSecs)==null?O.timeWithoutPenaltySecs():i,additionalTimeAddedSecs:(o=n.additionalTimeAddedSecs)==null?O.addedTimeSecs():o}),p=(s=r==null?void 0:r.deeds)==null?[]:s;p.push({id:`points`,value:n.pointsAwarded}),p.push({id:`time`,value:Math.round((c=f.elapsedTimeSecs)==null?0:c)+Math.round((u=f.additionalTimeAddedSecs)==null?0:u)});let m=l(),h=a&&!a.session&&a.appRuntimeContract===`1.1`;m||h?(w.sendMessage(`GAME_COMPLETED`,{id:m==null?void 0:m,input:f,config:r}),D(`GAME_COMPLETED`,{input:f})):_(`gameCompleted`)},showCompletionScreen:e=>{w.sendMessage(`SHOW_GAME_COMPLETE_SCREEN`,{results:e,showRetry:!0})},hitCheckpoint:(e,t,n)=>{var r;if(!l())return _(`hitCheckpoint`);let i=(r=p())==null?``:r,a={elapsedTimeSecs:O.timeWithoutPenaltySecs(),additionalTimeAddedSecs:O.addedTimeSecs()};w.sendMessage(`HIT_CHECKPOINT`,{checkpointName:e,gameplay:{inputStr:i,play:a},checkpointConfig:t,augConfig:n==null?{}:n})},settings:{initialize:e=>(b=t.t(t.t({},E(e)),b),w.sendMessage(`INITIALIZE_SETTINGS`,{components:e,settings:b}),b),get:()=>{var e;return(e=b)==null?{}:e},update:e=>(b=t.t(t.t({},b),e),w.sendMessage(`UPDATE_SETTINGS_FROM_EMBED`,{settings:b}),b)},keyboard:{show:e=>{w.sendMessage(`KEYBOARD_UPDATE_CONFIG`,e)},hide:()=>{w.sendMessage(`KEYBOARD_UPDATE_CONFIG`,{layout:[],symbols:{},highlight:[],disabled:[],xl:[],l:[],supportsDragCursor:!1})}},haptics:{play:(e,t)=>{var n;w.sendMessage(`SENSORY_EVENT`,{id:(n=t==null?void 0:t.id)==null?e:n,haptic:e})}},_hostAPI:w}};function E(e){let t={};for(let n of e)n.type===`split`?Object.assign(t,E(n.content)):`name`in n&&(t[n.name]=n.defaultValue);return t}const D={layout:[`qwertyuiop`,`asdfghjkl`,`↵zxcvbnm⌫`,void 0],symbols:{"↵":`enter`,"⌫":`bsp`},highlight:[`↵`,`⌫`],disabled:[],xl:[],l:[`↵`,`⌫`],supportsDragCursor:!1},O=e=>{let n={};for(let a of e)for(let e of a.keys){var r,i;let o={},s=t.t(t.t({},(r=n[e])==null?void 0:r.text),a.text),c=t.t(t.t({},(i=n[e])==null?void 0:i.background),a.background);Object.keys(s).length&&(o.text=s),Object.keys(c).length&&(o.background=c),n[e]=o}return n};var k=class extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name=`EditorImportError`}};exports.EditorImportError=k,exports.createPuzzmoSDK=T,exports.defaultKeyboardConfig=D,exports.keyStylesFromRules=O;
|
|
2
2
|
//# sourceMappingURL=index.cjs.map
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.cjs","names":[],"sources":["../src/bootstrapPayload.ts","../src/gameTracker.ts","../src/analytics.ts","../src/sdk.ts","../src/keyboard.ts","../src/editor.ts"],"sourcesContent":["import type { BootstrapGame, BootstrapGameData, BootstrapSession } from \"./types\"\n\n/**\n * READY_DATA as hosts from before the payload split send it: the gameplay with the puzzle nested\n * inside it, and a flattened game inside that. Deliberately not part of the SDK's public types.\n */\ntype LegacyReadyData = Omit<BootstrapGameData, \"game\" | \"session\"> & {\n game?: BootstrapGame\n session?: BootstrapSession\n startOrFindGameplay?: {\n gamePlayed?: BootstrapSession[\"gameplay\"] & { puzzle: BootstrapSession[\"puzzle\"] & { game?: any; viewerMetadata?: unknown } }\n }\n}\n\n/**\n * Fills in `game` and `session` when READY_DATA comes from a host which only sends the older\n * `startOrFindGameplay` nesting, so the SDK and games only ever see the new shape. A copy of\n * upgradeBootstrapGameData in @puzzmo-com/shared, which the SDK can't depend on.\n */\nexport const normalizeReadyData = (received: unknown): BootstrapGameData => {\n const { startOrFindGameplay, ...data } = received as LegacyReadyData\n if (data.game) return data as BootstrapGameData\n\n const gamePlayed = startOrFindGameplay?.gamePlayed\n const game = gameFromLegacy(gamePlayed?.puzzle?.game ?? {})\n if (!gamePlayed) return { ...data, game }\n\n const { puzzle, ...gameplay } = gamePlayed\n const { game: _game, viewerMetadata, ...puzzleFields } = puzzle\n return { ...data, game, session: { gameplay, puzzle: puzzleFields }, viewerMetadata: data.viewerMetadata ?? viewerMetadata }\n}\n\n/** Builds the game from the flattened fields older hosts put on `puzzle.game`, with no version IDs */\nconst gameFromLegacy = (game: any): BootstrapGame => {\n const flags = game.flagsArr\n return {\n id: game.id ?? \"\",\n slug: game.slug ?? \"\",\n stableSlug: game.stableSlug ?? game.slug ?? \"\",\n displayName: game.displayName ?? \"\",\n version: {\n id: \"\",\n label: null,\n featuresArr: game.featuresArr ?? [0],\n flagsArr: Array.isArray(flags) ? flags : typeof flags === \"number\" ? [flags] : [0],\n runtime: {\n id: \"\",\n version:\n game.assetsSha || game.assetsBaseURL\n ? { id: \"\", assetsSha: game.assetsSha ?? \"\", assetsBaseURL: game.assetsBaseURL ?? \"\" }\n : null,\n },\n },\n }\n}\n","import type { DeviceType, GameAnalyticsContext, LinkClickedInfo } from \"./analytics\"\n\n/**\n * Game analytics event-firing logic for the SDK.\n *\n * This mirrors the runtime's tracker (and the canonical copy in @puzzmo-com/clickhouse/gameTracker\n * used server-side): which host messages map to which events, the engagement thresholds, the\n * payload shape, and the /events endpoint. It is kept here, dependency-free, so the published SDK\n * pulls in none of the clickhouse package's server deps (kysely / @clickhouse/client) and so the\n * public OSS mirror can build it without the private workspace packages present.\n */\n\nexport type GameAnalyticsEventType = \"page_view\" | \"gameplay_active\" | \"active_30s\" | \"completed\" | \"link_click\"\n\ntype GameAnalyticsState = {\n context: GameAnalyticsContext\n updateCount: number\n startTime: Date\n tracked: {\n pageView: boolean\n gameplayActive: boolean\n active30s: boolean\n completed: boolean\n }\n}\n\ntype MessagesSent =\n | \"READY_GAME_LOADED\"\n | \"UPLOAD_NEW_GAME_STATE\"\n | \"GAME_COMPLETED\"\n | \"SHOW_GAME_COMPLETE_SCREEN\"\n | \"UPDATE_GAME_STATE\"\n | string\n\nconst sendGameAnalyticsEvent = async (\n context: GameAnalyticsContext,\n eventType: GameAnalyticsEventType,\n metadata?: Record<string, string | number | boolean>,\n elapsedTimeOnComplete?: number,\n) => {\n try {\n const body = {\n ...context,\n eventType,\n elapsedTimeOnComplete,\n metadata,\n }\n\n const response = await fetch(`${context.apiRoot}events`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n // Ensures the event still fires if the user navigates away (e.g. clicking a _blank link)\n keepalive: true,\n })\n\n if (!response.ok) {\n console.warn(`Analytics event failed: ${eventType} - ${response.status} ${response.statusText}`)\n }\n } catch (error) {\n console.warn(`Analytics event error: ${eventType}`, error)\n }\n}\n\nexport const createGameAnalyticsTracker = (context: GameAnalyticsContext) => {\n const state: GameAnalyticsState = {\n context: { ...context, deviceType: context.deviceType ?? detectDeviceType() },\n updateCount: 0,\n startTime: new Date(),\n tracked: {\n pageView: false,\n gameplayActive: false,\n active30s: false,\n completed: false,\n },\n }\n\n const trackEvent = (type: MessagesSent, json?: any) => {\n const now = new Date()\n const timeDiff = now.getTime() - state.startTime.getTime()\n const seconds = timeDiff / 1000\n\n switch (type) {\n case \"READY_GAME_LOADED\": {\n if (!state.tracked.pageView) {\n sendGameAnalyticsEvent(state.context, \"page_view\")\n state.tracked.pageView = true\n }\n break\n }\n\n case \"UPLOAD_NEW_GAME_STATE\": {\n state.updateCount++\n\n // Fire gameplay_active early (after 2 state changes) to indicate user engagement\n if (state.updateCount > 2 && !state.tracked.gameplayActive) {\n sendGameAnalyticsEvent(state.context, \"gameplay_active\")\n state.tracked.gameplayActive = true\n }\n\n // Fire active_30s for sustained engagement\n if (seconds > 30) {\n if (!state.tracked.gameplayActive) {\n sendGameAnalyticsEvent(state.context, \"gameplay_active\")\n state.tracked.gameplayActive = true\n }\n if (!state.tracked.active30s) {\n sendGameAnalyticsEvent(state.context, \"active_30s\")\n state.tracked.active30s = true\n }\n }\n break\n }\n\n case \"GAME_COMPLETED\": {\n if (!state.tracked.completed && json?.input) {\n sendGameAnalyticsEvent(state.context, \"completed\", {}, json.input.elapsedTimeSecs)\n state.tracked.completed = true\n }\n break\n }\n }\n }\n\n const trackLinkClick = (info: LinkClickedInfo) => {\n sendGameAnalyticsEvent(state.context, \"link_click\", info)\n }\n\n return {\n trackEvent,\n trackLinkClick,\n }\n}\n\n/**\n * The kind of device the game runs on, judged by the whole device rather than the game's frame. A copy of\n * detectDeviceType in @puzzmo-com/clickhouse/deviceType, kept dependency-free for the published SDK.\n */\nconst detectDeviceType = (): DeviceType => {\n if (typeof navigator === \"undefined\" || typeof window === \"undefined\") return \"unknown\"\n const userAgent = navigator.userAgent\n\n // iPadOS Safari reports itself as a Mac, so only a touchscreen gives it away\n if (/iPad/.test(userAgent) || (/Macintosh/.test(userAgent) && navigator.maxTouchPoints > 1)) return \"tablet\"\n const mobileHint = (navigator as Navigator & { userAgentData?: { mobile?: boolean } }).userAgentData?.mobile\n if (/iPhone|iPod/.test(userAgent) || mobileHint) return \"mobile\"\n // Android phones carry \"Mobile\", Android tablets leave it out\n if (/Android/.test(userAgent)) return /Mobile/.test(userAgent) ? \"mobile\" : \"tablet\"\n if (/Mobile|Windows Phone/.test(userAgent)) return \"mobile\"\n\n // Anything else whose main input is touch, sized by the screen's short side\n if (window.matchMedia?.(\"(pointer: coarse)\").matches) return Math.min(screen.width, screen.height) < 600 ? \"mobile\" : \"tablet\"\n return \"desktop\"\n}\n","import { createGameAnalyticsTracker } from \"./gameTracker\"\n\nimport type { BootstrapGameData } from \"./types\"\n\n/**\n * Game analytics for the SDK.\n *\n * The event-firing logic — which host messages map to which ClickHouse events, the\n * engagement thresholds, the payload, and the /events endpoint — lives in ./gameTracker,\n * a self-contained mirror of the runtime's tracker. It is kept local (rather than imported\n * from @puzzmo-com/clickhouse) so the published SDK pulls in none of the clickhouse package's\n * server deps, and so the public OSS mirror can build the SDK without the private workspace\n * packages present.\n *\n * This file only adds the SDK-specific glue: deciding whether analytics should run,\n * building the context from bootstrap data, and watching for link clicks. Events are\n * never sent from localhost (dev + the SDK simulator).\n */\n\nexport type LinkClickedInfo = {\n href: string\n text: string\n target: string\n}\n\ntype UserType = \"anon\" | \"user\" | \"paid\"\ntype RuntimeType = \"puzzmo_com\" | \"iframe\" | \"simple_embed\" | \"app_embed\" | \"ios_native\" | \"msn\"\n\n/** Everything the events endpoint needs to attribute an event, mirrors the runtime's context. */\nexport type GameAnalyticsContext = {\n gameSlug: string\n puzzleID: string\n gameplayOwnerID: string\n apiRoot: string\n userType: UserType\n runtimeType: RuntimeType\n userID?: string\n teamSlug?: string\n partnerSlug?: string\n dailyDateKey?: string\n embedID?: string\n /** Defaults to the device the game is running on, see detectDeviceType in ./gameTracker */\n deviceType?: DeviceType\n}\n\n/** Matches the device_type column in ClickHouse, the API classifies events which leave it out */\nexport type DeviceType = \"unknown\" | \"mobile\" | \"tablet\" | \"desktop\"\n\nexport type GameAnalyticsTracker = {\n /** Map an outgoing host message to its analytics event(s), if any. */\n trackEvent: (type: string, json?: any) => void\n /** Report an anchor click inside the game. */\n trackLinkClick: (info: LinkClickedInfo) => void\n}\n\n/**\n * Build the analytics tracker for a game, or null when analytics shouldn't run\n * (the game doesn't bring its own runtime, no browser, running on localhost, or\n * missing bootstrap data).\n */\nexport const createGameAnalytics = (readyData: BootstrapGameData | null): GameAnalyticsTracker | null => {\n // Only games that bring their own runtime track via the SDK — see gameBringsOwnRuntime.\n if (!gameBringsOwnRuntime(readyData)) return null\n\n const endpoint = resolveAnalyticsEndpoint()\n if (!endpoint.enabled) return null\n\n const context = buildAnalyticsContext(readyData, endpoint.apiRoot)\n if (!context) return null\n\n return createGameAnalyticsTracker(context)\n}\n\n/** Delegates document clicks to report anchor navigations. Returns a cleanup function. */\nexport const setupLinkTracking = (onLinkClicked: (info: LinkClickedInfo) => void): (() => void) => {\n if (typeof document === \"undefined\") return () => {}\n\n const handler = (event: MouseEvent) => {\n const node = event.target\n if (!(node instanceof Element)) return\n const anchor = node.closest(\"a[href]\")\n if (!(anchor instanceof HTMLAnchorElement)) return\n\n onLinkClicked({\n href: anchor.href,\n text: anchor.textContent?.trim() ?? \"\",\n target: anchor.target,\n })\n }\n\n document.addEventListener(\"click\", handler)\n return () => document.removeEventListener(\"click\", handler)\n}\n\n/** Picks the events endpoint, and disables analytics entirely on localhost (dev + simulator). */\nconst resolveAnalyticsEndpoint = (): { apiRoot: string; enabled: boolean } => {\n if (typeof window === \"undefined\" || !window.location) return { apiRoot: \"\", enabled: false }\n\n const hostname = window.location.hostname\n const isLocalhost =\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"0.0.0.0\" ||\n hostname === \"[::1]\" ||\n hostname.endsWith(\".localhost\")\n\n if (isLocalhost) return { apiRoot: \"\", enabled: false }\n\n const isStaging = hostname.includes(\"staging\")\n return { apiRoot: isStaging ? \"https://api-staging.puzzmo.com/\" : \"https://api.puzzmo.com/\", enabled: true }\n}\n\n/** Derive the analytics context from the host's bootstrap data, or null if a game isn't present. */\nexport const buildAnalyticsContext = (readyData: BootstrapGameData | null, apiRoot: string): GameAnalyticsContext | null => {\n const session = readyData?.session\n if (!session) return null\n\n const gameplay = session.gameplay\n const puzzle: any = session.puzzle\n const hostContext: any[] = (readyData?.hostContext as any[]) ?? []\n const embedContext = hostContext.find((hc) => hc?.type === \"embed\")\n\n return {\n gameSlug: readyData?.game?.slug || \"unknown\",\n puzzleID: puzzle.id,\n gameplayOwnerID: gameplay.ownerID || readyData?.userState?.id || \"unknown\",\n apiRoot,\n userType: mapUserType(readyData?.currentUser?.type),\n runtimeType: getRuntimeType(hostContext),\n userID: readyData?.currentUser?.id,\n teamSlug: puzzle.team?.slug || undefined,\n // Embeds carry their partner in the embed context; partner pages on puzzmo.com send it top-level\n partnerSlug: embedContext?.partner?.slug || readyData?.partnerSlug || undefined,\n dailyDateKey: puzzle.mostRecentDaily?.daily?.dateKey,\n embedID: embedContext?.embedID || undefined,\n }\n}\n\n/** Map the user's subscription tier to the analytics user bucket. */\nconst mapUserType = (type: string | null | undefined): UserType => {\n if (!type || type === \"Unverified\") return \"anon\"\n if (type === \"Paid\") return \"paid\"\n return \"user\"\n}\n\n// GameFlags1.bringsOwnRuntime — see packages/shared/flags/gameFlags.ts. Inlined to keep the SDK\n// free of the @puzzmo-com/shared workspace dep (the OSS mirror doesn't have that package).\nconst bringsOwnRuntimeFlag = 1 << 9\n\n/**\n * Whether the bootstrapped game has the \"brings own runtime\" flag set. SDK analytics only\n * run for these games; the standard Puzzmo runtime tracks the same events itself, so gating\n * here avoids double-counting for games that don't bring their own runtime.\n */\nconst gameBringsOwnRuntime = (readyData: BootstrapGameData | null): boolean => {\n const flagValue = readyData?.game?.version.flagsArr[0] ?? 0\n return (flagValue & bringsOwnRuntimeFlag) === bringsOwnRuntimeFlag\n}\n\n/** Derive the runtime bucket from host context, mirroring the runtime's getRuntimeType. */\nconst getRuntimeType = (hostContext: any[]): RuntimeType => {\n const embed = hostContext.find((hc) => hc?.type === \"embed\")\n if (embed) return embed.host === \"msn\" ? \"msn\" : \"iframe\"\n\n const app = hostContext.find((hc) => hc?.type === \"app\")\n if (app?.host === \"__embed\") return \"simple_embed\"\n if (app?.host === \"app-embed\") return \"app_embed\"\n if (app?.host === \"ios-app\") return \"ios_native\"\n\n return \"puzzmo_com\"\n}\n","import { normalizeReadyData } from \"./bootstrapPayload\"\nimport { createGameAnalytics, setupLinkTracking, type GameAnalyticsTracker } from \"./analytics\"\nimport type { PluginAPIs, SDKPlugin, SDKPluginContext } from \"./plugins\"\nimport type {\n MessagesSentFromEmbed,\n MessagesReceived,\n GamePlay,\n GameCompletedPlay,\n AugmentationConfig,\n CheckpointConfig,\n Theme,\n Deed,\n GameOverMessageUIComponent,\n KeyboardConfig,\n GameSettingsUIComponents,\n AvailableHaptics,\n} from \"./types\"\n\nexport type SDK = PuzzmoSDK\n\nexport interface PuzzmoSDKOptions<Plugins extends readonly SDKPlugin[] = []> {\n /** Optional timeout in ms to wait for READY_DATA (default: 5000) */\n timeout?: number\n /** Plugins to extend the SDK with; each contributes a namespaced API at `sdk.plugins[name]`. */\n plugins?: Plugins\n}\n\n/** The bootstrap info a game needs to set up its board, returned by `sdk.gameReady()`. */\nexport type GameReadyResult = {\n /** The serialized puzzle for this gameplay, in the game's own format. */\n puzzleString: string\n /** The player's saved in-progress board state from a previous session, or null when starting fresh. */\n inputString: string | null\n /** The host's current display theme, so the game can match the surrounding page. */\n theme: Theme | null\n /** True when the player has already finished this puzzle (e.g. re-opening a completed daily). */\n completed: boolean\n /** The raw bootstrap payload from the host: user state, the gameplay record, host context, etc. */\n readyData: MessagesReceived[\"READY_DATA\"] | null\n}\n\n/** Player-facing game settings, rendered by the host's settings panel and persisted per-user, per-game. */\nexport interface SDKSettings {\n /**\n * Register the game's settings UI with the host. Component `defaultValue`s are merged\n * underneath the player's saved values, the host shows the components in its settings panel,\n * and the resolved settings object is returned. Listen for the `settingsUpdate` event to\n * react to the player changing values. Call after `gameReady()`.\n */\n initialize: (components: GameSettingsUIComponents[]) => any\n /** Get the current resolved settings object. */\n get: () => any\n /** Merge changes into the current settings and persist them to the host. Returns the updated settings. */\n update: (changes: any) => any\n}\n\n/** The host-rendered on-screen keyboard, for games that take text or symbol input on touch devices. */\nexport interface SDKKeyboard {\n /** Show the on-screen keyboard with the given config. Call again to update state (e.g. to change disabled keys). */\n show: (config: KeyboardConfig) => void\n /** Hide the on-screen keyboard. */\n hide: () => void\n}\n\n/** Device haptics. The host owns the player's setting and the device bridge; a game only asks. */\nexport interface SDKHaptics {\n /**\n * Ask the host to fire a haptic. Fire-and-forget: it is never awaited, never reports back, and\n * is a no-op wherever the host can't deliver one, so a game can call it freely.\n *\n * Where it actually fires:\n *\n * - **Puzzmo's iOS app** — real UIKit haptics, via the native bridge.\n * - **puzzmo.com on Android/desktop** — approximated with `navigator.vibrate` by the page, which is why this goes to the host rather than\n * vibrating from the game. Chrome blocks `navigator.vibrate` outright in cross-origin iframes (since Chrome 55), and games run in one,\n * so a game calling it directly is silently ignored with no way to opt in — there is no Permissions-Policy feature for it.\n * - **Embeds** — no haptic. Our frame is cross-origin to the host page, so the block above applies to the host too, and there is no native\n * bridge. The cue is still forwarded to the host page on the private message stream, so a partner can action it themselves.\n *\n * Haptics are also off entirely when the player has turned them off, and the OS may drop them\n * in silent/DND or on hardware without a motor.\n *\n * @param haptic Which feel to ask for. Named after the iOS generators; other hosts approximate.\n * @param options `id` names the cue this haptic belongs to, for host logs and the simulator.\n */\n play: (haptic: AvailableHaptics, options?: { id?: string }) => void\n}\n\n/**\n * The SDK instance returned by `createPuzzmoSDK` — a game's API surface for talking to whichever\n * host is embedding it (puzzmo.com, a partner embed, or the native apps): bootstrapping the\n * puzzle, syncing progress, reporting completion, and driving host UI like settings and the\n * on-screen keyboard.\n *\n * The expected lifecycle is: `gameReady()` → build your board from the result → `gameLoaded()` →\n * play, persisting via `updateGameState()` → `gameCompleted()` → `showCompletionScreen()`.\n */\nexport interface PuzzmoSDK<Plugins extends readonly SDKPlugin[] = []> {\n /**\n * The play clock. The SDK manages it for you: it starts when the host starts the game, pauses\n * and resumes with the host UI, and its display is mirrored into the host chrome twice a\n * second. Most games only need `addPenalty()` for hint or mistake costs.\n */\n timer: SDKTimer\n\n /** APIs contributed by the plugins passed to `createPuzzmoSDK`, keyed by plugin name. */\n plugins: PluginAPIs<Plugins>\n\n /**\n * Announce that the game is ready to receive data. Sends `READY` to the host and resolves with\n * the bootstrap info once the host replies: the puzzle to load, any saved in-progress state,\n * and the host theme. Call this first — every other API assumes it has resolved. Rejects when\n * the host doesn't reply within `PuzzmoSDKOptions.timeout` (default 5s).\n */\n gameReady: () => Promise<GameReadyResult>\n\n /**\n * Tell the host the game has parsed the puzzle, rendered, and is ready to be revealed. The\n * host dismisses its loading UI and replies with a start signal — listen via `on(\"start\")` to\n * begin play; the timer starts then too.\n */\n gameLoaded: (state?: any) => void\n\n /**\n * Subscribe to a host lifecycle event: `start`, `pause`, `resume`, `retry`, `settingsUpdate`,\n * or the on-screen `keyboard*` events. Returns an unsubscribe function.\n */\n on: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void) => () => void\n\n /** Remove an event listener previously registered with `on`. */\n off: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void) => void\n\n /**\n * Save the player's in-progress state to the server so play can resume later, on any\n * device. `inputString` is the game's own serialized format — it comes back as `inputString`\n * from `gameReady()`. Call whenever the player makes a meaningful move; elapsed time is filled\n * in from the SDK timer unless provided in `play`.\n */\n updateGameState: (inputString: string, play?: Partial<GamePlay>) => void\n\n /**\n * Report the game as finished. Concludes the timer, fills in elapsed/penalty time when not\n * provided, and uploads the final play plus its deeds — the host uses these for scoring,\n * leaderboards, stats, and other augmentations. Pass progress as `inputString` (the same\n * string `updateGameState()` takes). Follow with `showCompletionScreen()`.\n */\n gameCompleted: (play: GameCompletedPlay, config?: AugmentationConfig) => void\n\n /**\n * Ask the host to show its post-game completion UI. `results` render in the completion\n * sidebar: markdown congratulations, the player's streak stats, and custom stat rows. Call\n * after `gameCompleted()`, typically once your own victory animation has finished.\n */\n showCompletionScreen: (results: GameOverMessageUIComponent[]) => void\n\n /**\n * Record a named mid-game checkpoint. Uploads the current board state and play time, and can\n * run parts of the completion pipeline early (e.g. posting to leaderboards) via\n * `checkpointConfig.process`. A checkpoint is also the host's opportunity to show an ad when\n * `checkpointConfig.interruptible` is true.\n */\n hitCheckpoint: (checkpointName: string, checkpointConfig: CheckpointConfig, config?: AugmentationConfig) => void\n\n /** Player-facing game settings, rendered in the host's settings panel and persisted per-user, per-game. */\n settings: SDKSettings\n\n /** The host-rendered on-screen keyboard, for games that take text or symbol input on touch devices. */\n keyboard: SDKKeyboard\n\n /** Device haptics, where the host can deliver them. See `SDKHaptics.play` for where that is. */\n haptics: SDKHaptics\n\n /**\n * The raw postMessage transport to the host — an escape hatch for protocol messages the SDK\n * doesn't wrap.\n *\n * @internal\n */\n _hostAPI: {\n sendMessage: <T extends keyof SupportedOutgoingMessages>(type: T, json: SupportedOutgoingMessages[T]) => void\n onMessage: <T extends keyof SupportedIncomingMessages>(type: T, handler: (data: SupportedIncomingMessages[T]) => void) => () => void\n }\n}\n\nexport type SupportedOutgoingMessages = Pick<\n MessagesSentFromEmbed,\n | \"READY\"\n | \"READY_GAME_LOADED\"\n | \"GAME_COMPLETED\"\n | \"SHOW_GAME_COMPLETE_SCREEN\"\n | \"TIMER_TICK\"\n | \"TIMER_SYNC\"\n | \"UPLOAD_NEW_GAME_STATE\"\n | \"HIT_CHECKPOINT\"\n | \"KEYBOARD_UPDATE_CONFIG\"\n | \"INITIALIZE_SETTINGS\"\n | \"UPDATE_SETTINGS_FROM_EMBED\"\n | \"SENSORY_EVENT\"\n>\n\nexport type SupportedIncomingMessages = Pick<\n MessagesReceived,\n | \"READY_DATA\"\n | \"START_GAME\"\n | \"PAUSE_GAME\"\n | \"RESUME_GAME\"\n | \"SETTINGS_UPDATE\"\n | \"RETRY_PUZZLE\"\n | \"KEYBOARD_KEY_PRESS\"\n | \"KEYBOARD_CURSOR_CHANGE\"\n | \"KEYBOARD_CURSOR_END\"\n>\n\ntype MessageHandler<T extends keyof SupportedIncomingMessages> = (data: SupportedIncomingMessages[T]) => void\n\nexport type SDKEventMap = {\n start: void\n pause: void\n resume: void\n retry: void\n /** The player changed a setting in the host UI. The payload is the full resolved settings object. */\n settingsUpdate: any\n /** A key on the on-screen keyboard was tapped. */\n keyboardKeyPress: { key: string }\n /** The drag cursor moved across the keyboard. Only fires when `supportsDragCursor` is true. */\n keyboardCursorChange: { position: [number, number] }\n /** The drag cursor was released. Only fires when `supportsDragCursor` is true. */\n keyboardCursorEnd: void\n}\n\nexport type SDKEventType = keyof SDKEventMap\n\nexport interface SDKTimer {\n /** Get elapsed time in milliseconds */\n timeMs: () => number\n /** Get elapsed time in seconds */\n timeSecs: () => number\n /** Get added/penalty time in milliseconds */\n addedTimeMs: () => number\n /** Get added/penalty time in seconds */\n addedTimeSecs: () => number\n /** Get elapsed time without penalties in seconds */\n timeWithoutPenaltySecs: () => number\n /** Get formatted display strings [elapsed, added] */\n display: () => [string, string]\n /** Add penalty time in milliseconds */\n addPenalty: (ms: number) => void\n /** Set the total penalty time in milliseconds, for games which derive it from their state */\n setPenalty: (ms: number) => void\n /** Check if timer is paused */\n isPaused: () => boolean\n /** Check if timer has been started */\n isRunning: () => boolean\n /** Pause the timer (same as a host-sent PAUSE_GAME); emits \"pause\" on an actual transition. */\n pause: () => void\n /** Resume the timer (same as a host-sent RESUME_GAME); emits \"resume\" on an actual transition. */\n resume: () => void\n}\n\nfunction formatTime(timeMs: number): string {\n const isAnHourOrMore = timeMs >= 60 * 60 * 1000\n return new Date(timeMs)\n .toISOString()\n .slice(isAnHourOrMore ? 11 : 14, -1)\n .split(\".\")[0]\n}\n\nfunction createTimer(\n initialTimeMs = 0,\n initialAddedTimeMs = 0,\n): Omit<SDKTimer, \"pause\" | \"resume\"> & {\n _init: () => void\n _pause: () => void\n _resume: () => void\n _reset: (initialTimeMs?: number, initialAddedTimeMs?: number) => void\n _conclude: () => void\n} {\n let baseTime = initialTimeMs\n let addedTime = initialAddedTimeMs\n let pausedTime = 0\n let concludeTime: number | undefined\n\n let startDate: number | undefined = undefined\n let pausedDate: number | undefined = undefined\n\n const getTime = (): number => {\n if (startDate === undefined) return baseTime + addedTime\n if (concludeTime !== undefined) return concludeTime\n const now = pausedDate ?? performance.now()\n const elapsed = now - startDate - pausedTime\n return baseTime + addedTime + elapsed\n }\n\n return {\n _init: () => {\n if (startDate === undefined) {\n startDate = performance.now()\n pausedDate = undefined\n }\n },\n _pause: () => {\n if (pausedDate !== undefined || startDate === undefined) return\n pausedDate = performance.now()\n },\n _resume: () => {\n if (pausedDate === undefined) return\n pausedTime += performance.now() - pausedDate\n pausedDate = undefined\n },\n _reset: (newInitialTimeMs = 0, newInitialAddedTimeMs = 0) => {\n baseTime = newInitialTimeMs\n addedTime = newInitialAddedTimeMs\n pausedTime = 0\n concludeTime = undefined\n startDate = undefined\n pausedDate = undefined\n },\n _conclude: () => {\n if (pausedDate !== undefined) {\n concludeTime = getTime()\n return\n }\n if (startDate === undefined) {\n concludeTime = baseTime + addedTime\n return\n }\n concludeTime = getTime()\n },\n timeMs: () => getTime(),\n timeSecs: () => getTime() / 1000,\n addedTimeMs: () => addedTime,\n addedTimeSecs: () => addedTime / 1000,\n timeWithoutPenaltySecs: () => (getTime() - addedTime) / 1000,\n addPenalty: (ms: number) => {\n addedTime += ms\n },\n setPenalty: (ms: number) => {\n addedTime = ms\n },\n isPaused: () => pausedDate !== undefined || startDate === undefined,\n isRunning: () => startDate !== undefined && pausedDate === undefined,\n display: () => {\n const elapsed = getTime() - addedTime\n const elapsedStr = formatTime(Math.max(0, elapsed))\n const addedStr = addedTime === 0 ? \"\" : formatTime(addedTime)\n return [elapsedStr, addedStr]\n },\n }\n}\n\nfunction createHostAPI() {\n const messageHandlers = new Map<string, Set<(data: any) => void>>()\n\n const sendMessage = <T extends keyof SupportedOutgoingMessages>(type: T, json: SupportedOutgoingMessages[T]) => {\n const message = { type, json, _: \"p\", __: \"mp\", private: true }\n\n if (\"parent\" in window && window.parent !== window) window.parent.postMessage(message, \"*\")\n\n window.postMessage(message, \"*\")\n\n if (\"webkit\" in window && (window as any).webkit?.messageHandlers?.app) (window as any).webkit.messageHandlers.app.postMessage(message)\n\n if (\"puzzmoMessageString\" in window) (window as any).puzzmoMessageString(JSON.stringify(message))\n\n if (\"ReactNativeWebView\" in window && (window as any).ReactNativeWebView?.postMessage)\n (window as any).ReactNativeWebView.postMessage(JSON.stringify(message))\n\n if (type !== \"TIMER_TICK\" && type !== \"TIMER_SYNC\") console.log(\"[Puzzmo SDK] sent:\", type, json)\n }\n\n const onMessage = <T extends keyof SupportedIncomingMessages>(type: T, handler: MessageHandler<T>) => {\n if (!messageHandlers.has(type)) messageHandlers.set(type, new Set())\n messageHandlers.get(type)!.add(handler)\n\n return () => {\n messageHandlers.get(type)?.delete(handler)\n }\n }\n\n if (typeof window !== \"undefined\") {\n window.addEventListener(\"message\", (event) => {\n if (!event?.data?.type) return\n const msgType = event.data.type as string\n const handlers = messageHandlers.get(msgType)\n if (handlers) {\n const msgData = event.data.data ?? event.data.json ?? {}\n if (msgType !== \"TIMER_TICK\" && msgType !== \"TIMER_SYNC\") console.log(\"[Puzzmo SDK] received:\", msgType, msgData)\n handlers.forEach((handler) => handler(msgData))\n }\n })\n }\n\n return { sendMessage, onMessage }\n}\n\n/**\n * The host<->game contract this SDK is built against, declared in READY and READY_GAME_LOADED.\n * Stays \"1.0\" until every host supporting \"1.1\" is deployed: an older puzzmo.com reloads when it\n * sees a contract it doesn't know.\n */\nconst sdkRuntimeContract = \"1.0\"\n\nconst hostAPI = createHostAPI()\n\n/** Creates a Puzzmo SDK instance for communicating with the Puzzmo host */\nexport const createPuzzmoSDK = <const Plugins extends readonly SDKPlugin[] = []>(\n options: PuzzmoSDKOptions<Plugins> = {},\n): PuzzmoSDK<Plugins> => {\n let readyData: MessagesReceived[\"READY_DATA\"] | null = null\n let readyDataResolve: ((data: MessagesReceived[\"READY_DATA\"]) => void) | null = null\n\n const getGameplay = () => readyData?.session?.gameplay\n const getGameplayID = () => getGameplay()?.id ?? null\n const getPuzzleString = () => readyData?.session?.puzzle.puzzle ?? null\n const getBoardState = () => getGameplay()?.boardState ?? null\n const getTheme = () => readyData?.theme ?? null\n const getCompleted = () => getGameplay()?.completed ?? false\n\n const eventListeners = new Map<SDKEventType, Set<(data?: any) => void>>()\n\n // The resolved settings object — seeded from READY_DATA's saved values, then component\n // defaults are merged underneath when the game calls settings.initialize\n let currentSettings: any | null = null\n\n // ClickHouse game analytics — sends the same lifecycle events the runtime tracks\n // (page_view, gameplay_active, active_30s, completed, link_click). Disabled on localhost.\n let analytics: GameAnalyticsTracker | null = null\n let analyticsCompletedAtStart = false\n\n const trackAnalyticsEvent = (type: string, json?: any) => {\n // Don't re-send progression events for a game that was already completed when loaded\n if (analyticsCompletedAtStart) return\n analytics?.trackEvent(type, json)\n }\n\n const internalTimer = createTimer()\n let timerTickInterval: ReturnType<typeof setInterval> | null = null\n let timerSyncInterval: ReturnType<typeof setInterval> | null = null\n\n const startTimerIntervals = () => {\n if (timerTickInterval) return\n\n timerTickInterval = setInterval(() => {\n if (internalTimer.isPaused()) return\n const [elapsed, added] = internalTimer.display()\n hostAPI.sendMessage(\"TIMER_TICK\", { display: [elapsed, added] })\n }, 500)\n\n timerSyncInterval = setInterval(() => {\n if (internalTimer.isPaused()) return\n hostAPI.sendMessage(\"TIMER_SYNC\", Math.floor(internalTimer.timeWithoutPenaltySecs()))\n }, 10000)\n }\n\n const stopTimerIntervals = () => {\n if (timerTickInterval) {\n clearInterval(timerTickInterval)\n timerTickInterval = null\n }\n if (timerSyncInterval) {\n clearInterval(timerSyncInterval)\n timerSyncInterval = null\n }\n }\n\n const emit = <T extends SDKEventType>(event: T, data?: SDKEventMap[T]) => {\n const listeners = eventListeners.get(event)\n if (listeners) listeners.forEach((listener) => listener(data))\n }\n\n hostAPI.onMessage(\"START_GAME\", () => {\n internalTimer._init()\n startTimerIntervals()\n emit(\"start\")\n })\n\n // Shared by the host-sent PAUSE_GAME/RESUME_GAME messages and the game-initiated\n // sdk.timer.pause()/resume() below, so both paths stop/start the same timer identically.\n const pauseTimer = () => {\n const wasPaused = internalTimer.isPaused()\n internalTimer._pause()\n if (internalTimer.isPaused() !== wasPaused) emit(\"pause\")\n }\n const resumeTimer = () => {\n const wasPaused = internalTimer.isPaused()\n internalTimer._resume()\n if (internalTimer.isPaused() !== wasPaused) emit(\"resume\")\n }\n\n hostAPI.onMessage(\"PAUSE_GAME\", pauseTimer)\n hostAPI.onMessage(\"RESUME_GAME\", resumeTimer)\n\n hostAPI.onMessage(\"SETTINGS_UPDATE\", (data) => {\n currentSettings = { ...currentSettings, ...data }\n emit(\"settingsUpdate\", currentSettings)\n })\n\n hostAPI.onMessage(\"KEYBOARD_KEY_PRESS\", (data) => emit(\"keyboardKeyPress\", data))\n hostAPI.onMessage(\"KEYBOARD_CURSOR_CHANGE\", (data) => emit(\"keyboardCursorChange\", data))\n hostAPI.onMessage(\"KEYBOARD_CURSOR_END\", () => emit(\"keyboardCursorEnd\"))\n\n hostAPI.onMessage(\"RETRY_PUZZLE\", () => {\n internalTimer._reset()\n stopTimerIntervals()\n emit(\"retry\")\n })\n\n hostAPI.onMessage(\"READY_DATA\", (data) => {\n const bootstrapData = normalizeReadyData(data as MessagesReceived[\"READY_DATA\"])\n readyData = bootstrapData\n\n const gamePlayed = bootstrapData.session?.gameplay\n\n // userState.gameSettings is a map keyed by game slug; older records can hold the\n // value as a JSON string rather than an object\n if (currentSettings === null) {\n const gameSlug = bootstrapData.game.slug\n let saved = gameSlug ? bootstrapData.userState?.gameSettings?.[gameSlug] : null\n if (typeof saved === \"string\") {\n try {\n saved = JSON.parse(saved)\n } catch {\n saved = null\n }\n }\n currentSettings = saved ?? {}\n }\n if (gamePlayed) {\n const existingTime = (gamePlayed.elapsedTimeSecs ?? 0) * 1000\n const existingAddedTime = (gamePlayed.additionalTimeAddedSecs ?? 0) * 1000\n internalTimer._reset(existingTime, existingAddedTime)\n }\n\n // Wire up analytics once, from the first bootstrap payload\n if (!analytics) {\n analytics = createGameAnalytics(bootstrapData)\n analyticsCompletedAtStart = gamePlayed?.completed ?? false\n // Link clicks are tracked even for already-completed games, matching the runtime\n if (analytics) setupLinkTracking((info) => analytics!.trackLinkClick(info))\n }\n\n if (readyDataResolve) {\n readyDataResolve(bootstrapData)\n readyDataResolve = null\n }\n })\n\n const timer: SDKTimer = {\n timeMs: () => internalTimer.timeMs(),\n timeSecs: () => internalTimer.timeSecs(),\n addedTimeMs: () => internalTimer.addedTimeMs(),\n addedTimeSecs: () => internalTimer.addedTimeSecs(),\n timeWithoutPenaltySecs: () => internalTimer.timeWithoutPenaltySecs(),\n display: () => internalTimer.display(),\n addPenalty: (ms: number) => internalTimer.addPenalty(ms),\n setPenalty: (ms: number) => internalTimer.setPenalty(ms),\n isPaused: () => internalTimer.isPaused(),\n isRunning: () => internalTimer.isRunning(),\n pause: pauseTimer,\n resume: resumeTimer,\n }\n\n // Wire up plugins. Each gets the host transport (open to the full protocol), the timer, and\n // the bootstrap payload, and contributes a namespaced API onto `sdk.plugins[name]`.\n const pluginContext: SDKPluginContext = {\n send: (type, json) => hostAPI.sendMessage(type as keyof SupportedOutgoingMessages, json as never),\n on: (type, handler) => hostAPI.onMessage(type as keyof SupportedIncomingMessages, handler),\n timer,\n bootstrap: () => readyData,\n }\n const pluginAPIs: Record<string, unknown> = {}\n for (const plugin of options.plugins ?? []) pluginAPIs[plugin.name] = plugin.setup(pluginContext)\n\n return {\n timer,\n\n plugins: pluginAPIs as PluginAPIs<Plugins>,\n\n gameReady: async (): Promise<GameReadyResult> => {\n hostAPI.sendMessage(\"READY\", { runtimeContract: sdkRuntimeContract })\n\n if (getPuzzleString()) {\n const inputString = getBoardState()\n return {\n puzzleString: getPuzzleString()!,\n inputString,\n // @ts-expect-error - this is backwards compat\n boardState: inputString,\n theme: getTheme(),\n completed: getCompleted(),\n readyData,\n }\n }\n\n const timeout = options.timeout ?? 5000\n const readyDataPromise = new Promise<MessagesReceived[\"READY_DATA\"]>((resolve, reject) => {\n readyDataResolve = resolve\n setTimeout(() => {\n if (readyDataResolve) {\n readyDataResolve = null\n reject(new Error(`Timeout waiting for READY_DATA after ${timeout}ms`))\n }\n }, timeout)\n })\n\n await readyDataPromise\n\n const puzzleString = getPuzzleString()\n if (!puzzleString) throw new Error(\"READY_DATA received but no puzzle data found\")\n\n const inputString = getBoardState()\n return {\n puzzleString,\n inputString,\n // @ts-expect-error - this is backwards compat\n boardState: inputString,\n theme: getTheme(),\n completed: getCompleted(),\n readyData,\n }\n },\n\n gameLoaded: (state: any = {}) => {\n hostAPI.sendMessage(\"READY_GAME_LOADED\", {\n state,\n gameRuntimeContract: sdkRuntimeContract,\n embedRuntimeContract: \"1.0\",\n })\n trackAnalyticsEvent(\"READY_GAME_LOADED\")\n },\n\n on: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void): (() => void) => {\n if (!eventListeners.has(event)) eventListeners.set(event, new Set())\n eventListeners.get(event)!.add(listener)\n return () => {\n eventListeners.get(event)?.delete(listener)\n }\n },\n\n off: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void) => {\n eventListeners.get(event)?.delete(listener)\n },\n\n updateGameState: (inputString: string, play?: Partial<GamePlay>) => {\n const gameplayID = getGameplayID()\n if (!gameplayID) return\n\n hostAPI.sendMessage(\"UPLOAD_NEW_GAME_STATE\", {\n id: gameplayID,\n input: {\n boardState: inputString,\n elapsedTimeSecs: play?.elapsedTimeSecs ?? internalTimer.timeWithoutPenaltySecs(),\n additionalTimeAddedSecs: play?.additionalTimeAddedSecs ?? internalTimer.addedTimeSecs(),\n collabUserReferences: [],\n },\n })\n trackAnalyticsEvent(\"UPLOAD_NEW_GAME_STATE\")\n },\n\n gameCompleted: (play: GameCompletedPlay, config?: AugmentationConfig) => {\n internalTimer._conclude()\n stopTimerIntervals()\n\n // Games say inputString; the wire and database say boardState. Untyped callers\n // may still send the old boardState spelling, so keep accepting it at runtime.\n const { inputString, ...rest } = play\n const finalPlay: Partial<GamePlay> = {\n ...rest,\n boardState: inputString ?? (play as { boardState?: string }).boardState,\n elapsedTimeSecs: play.elapsedTimeSecs ?? internalTimer.timeWithoutPenaltySecs(),\n additionalTimeAddedSecs: play.additionalTimeAddedSecs ?? internalTimer.addedTimeSecs(),\n }\n\n const deeds: Deed[] = (config?.deeds as any) ?? []\n deeds.push({ id: \"points\", value: play.pointsAwarded })\n deeds.push({\n id: \"time\",\n value: Math.round(finalPlay.elapsedTimeSecs ?? 0) + Math.round(finalPlay.additionalTimeAddedSecs ?? 0),\n })\n\n const gameplayID = getGameplayID()\n if (gameplayID) {\n hostAPI.sendMessage(\"GAME_COMPLETED\", {\n id: gameplayID,\n input: finalPlay,\n config,\n })\n trackAnalyticsEvent(\"GAME_COMPLETED\", { input: finalPlay })\n }\n },\n\n showCompletionScreen: (results: GameOverMessageUIComponent[]) => {\n // showRetry stays in the message contract for a future host play-again button; no host renders one yet\n hostAPI.sendMessage(\"SHOW_GAME_COMPLETE_SCREEN\", { results, showRetry: true })\n },\n\n hitCheckpoint: (checkpointName: string, checkpointConfig: CheckpointConfig, config?: AugmentationConfig) => {\n const gameplayID = getGameplayID()\n if (!gameplayID) return\n\n const inputStr = getBoardState() ?? \"\"\n const play: Partial<GamePlay> = {\n elapsedTimeSecs: internalTimer.timeWithoutPenaltySecs(),\n additionalTimeAddedSecs: internalTimer.addedTimeSecs(),\n }\n\n hostAPI.sendMessage(\"HIT_CHECKPOINT\", {\n checkpointName,\n gameplay: { inputStr, play },\n checkpointConfig,\n augConfig: config ?? {},\n })\n },\n\n settings: {\n initialize: (components: GameSettingsUIComponents[]) => {\n currentSettings = { ...settingsDefaultsFromComponents(components), ...currentSettings }\n hostAPI.sendMessage(\"INITIALIZE_SETTINGS\", { components, settings: currentSettings })\n return currentSettings\n },\n get: () => currentSettings ?? {},\n update: (changes: any) => {\n currentSettings = { ...currentSettings, ...changes }\n hostAPI.sendMessage(\"UPDATE_SETTINGS_FROM_EMBED\", { settings: currentSettings })\n return currentSettings\n },\n },\n\n keyboard: {\n show: (config: KeyboardConfig) => {\n hostAPI.sendMessage(\"KEYBOARD_UPDATE_CONFIG\", config)\n },\n hide: () => {\n hostAPI.sendMessage(\"KEYBOARD_UPDATE_CONFIG\", {\n layout: [],\n symbols: {},\n highlight: [],\n disabled: [],\n xl: [],\n l: [],\n supportsDragCursor: false,\n })\n },\n },\n\n haptics: {\n play: (haptic, options) => {\n hostAPI.sendMessage(\"SENSORY_EVENT\", { id: options?.id ?? haptic, haptic })\n },\n },\n\n _hostAPI: hostAPI,\n }\n}\n\n/** Walks settings UI components (recursing into split groups) collecting name → defaultValue pairs */\nfunction settingsDefaultsFromComponents(components: GameSettingsUIComponents[]): Record<string, unknown> {\n const defaults: Record<string, unknown> = {}\n for (const component of components) {\n if (component.type === \"split\") Object.assign(defaults, settingsDefaultsFromComponents(component.content))\n else if (\"name\" in component) defaults[component.name] = component.defaultValue\n }\n return defaults\n}\n","import type { KeyboardConfig, KeyStyleRule, KeyStyles } from \"./types\"\n\n/**\n * A standard QWERTY layout with Enter and Backspace — a reasonable default for\n * any game that needs text input. Customize from here by spreading and overriding.\n *\n * @example\n * // Use as-is\n * sdk.keyboard.show(defaultKeyboardConfig)\n *\n * @example\n * // Extend with dynamic disabled letters\n * sdk.keyboard.show({ ...defaultKeyboardConfig, disabled: usedLetters })\n */\nexport const defaultKeyboardConfig: KeyboardConfig = {\n layout: [\"qwertyuiop\", \"asdfghjkl\", \"↵zxcvbnm⌫\", undefined],\n symbols: { \"↵\": \"enter\", \"⌫\": \"bsp\" },\n highlight: [\"↵\", \"⌫\"],\n disabled: [],\n xl: [],\n l: [\"↵\", \"⌫\"],\n supportsDragCursor: false,\n}\n\n/**\n * Expands per-key-set styling rules into the `individualKeyStyles` map a `KeyboardConfig` carries,\n * so a game can style a group of keys in one go. Later rules win where two name the same key.\n *\n * @example\n * sdk.keyboard.show({\n * ...defaultKeyboardConfig,\n * individualKeyStyles: keyStylesFromRules([{ keys: usedLetters, text: { opacity: \"0.4\" } }]),\n * })\n */\nexport const keyStylesFromRules = (rules: KeyStyleRule[]): Record<string, KeyStyles> => {\n const styles: Record<string, KeyStyles> = {}\n for (const rule of rules) {\n for (const key of rule.keys) {\n const merged: KeyStyles = {}\n const text = { ...styles[key]?.text, ...rule.text }\n const background = { ...styles[key]?.background, ...rule.background }\n // Only the groups a rule actually set, so a text-only rule doesn't carry an empty background\n // for every key it names.\n if (Object.keys(text).length) merged.text = text\n if (Object.keys(background).length) merged.background = background\n styles[key] = merged\n }\n }\n return styles\n}\n","// For now, we will keep these types in here but not mark them as something which should appear in the public SDK docs\n\nimport type { Theme } from \"./types\"\n\n/**\n * The theme passed to an editor bundle. The host sends its full {@link Theme} so editors derive\n * their colors from it rather than making their own theme decisions. Use `theme.type` for\n * light/dark bucketing.\n *\n * The bare `\"light\" | \"dark\"` string form is deprecated and will be removed in a future SDK\n * release — editors should handle the full `Theme` object.\n */\nexport type EditorTheme = Theme | \"light\" | \"dark\"\n\n/** Severity level for validation issues */\nexport type ValidationLevel = \"error\" | \"warning\" | \"info\"\n\n/** Represents a single validation issue found during puzzle validation */\nexport interface ValidationIssue {\n level: ValidationLevel\n message: string\n line?: number\n col?: number\n length?: number\n}\n\n/** Complete validation report for a puzzle */\nexport interface ValidationReport {\n success: boolean\n issues: ValidationIssue[]\n}\n\nexport type ImportErrorType = \"invalid_format\" | \"parsing_error\" | \"unknown\"\n\n/** Custom error class for workshop import failures */\nexport class EditorImportError extends Error {\n constructor(\n public type: ImportErrorType,\n message: string,\n public originalError?: unknown,\n ) {\n super(message)\n this.name = \"EditorImportError\"\n }\n}\n\n/** Result of a successful puzzle import operation */\nexport interface ImportResult {\n data: string\n warnings?: ValidationIssue[]\n title?: string\n authors?: string[]\n editors?: string[]\n}\n\n/** Settings UI descriptor returned by an editor bundle */\nexport interface EditorBundleSettings<TComponent = unknown> {\n components: TComponent[]\n defaults: Record<string, unknown>\n}\n\n/** A preceding/following phrase for a word, returned by the getRelatedWords editor callback */\nexport interface RelatedWord {\n word: string\n frequency: number\n position: \"preceding\" | \"following\"\n}\n\n/** Result of fetching a URL from within the editor */\nexport interface EditorFetchURLResult {\n status: number\n body: string\n}\n\n/** Config passed to an editor bundle's mount() */\nexport interface EditorMountConfig {\n puzzleString: string\n onChange: (puzzleString: string) => void\n theme: EditorTheme\n width: number\n height: number\n /**\n * Optional function for making chat completions from the editor (e.g. for AI-assisted puzzle\n * editing). This needs to be enabled for a team explicitly.\n */\n chatCompletion?: (prompt: string) => Promise<string>\n /**\n * Optional function for fetching URLs from the editor (e.g. for fetching article content).\n * This needs to be enabled for a team explicitly.\n */\n fetchURL?: (url: string) => Promise<EditorFetchURLResult>\n /** Optional function for looking up a word's preceding/following phrases from wordvault. */\n getRelatedWords?: (word: string, limit?: number) => Promise<RelatedWord[]>\n /** Pre-configured editor settings values from the queue's editorSettings. */\n settings?: Record<string, unknown>\n}\n\n/** Handle returned by an editor bundle's mount() */\nexport interface EditorMountHandle {\n unmount: () => void\n /**\n * Called whenever the puzzle string is updated in the editor from the outside, or when the theme\n * or dimensions update. Workshop will rely on the validator to reject / accept updates.\n */\n update: (config: { puzzleString?: string; theme?: EditorTheme; width?: number; height?: number }) => void\n}\n\n/** Main interface for a Workshop editor bundle */\nexport interface EditorBundle<TSettingsComponent = unknown> {\n /** Required validator for puzzle data validation */\n validator: {\n validate(data: string): Promise<ValidationReport> | ValidationReport\n }\n /** Optional importer for converting external puzzle file formats */\n importer?: {\n onImport(filename: string, contents: string | ArrayBuffer): Promise<ImportResult> | ImportResult\n }\n /** Embed-level settings UI, populated from the bundle's declared settings */\n settings?: EditorBundleSettings<TSettingsComponent>\n /** Editor-level settings UI, populated from the bundle's declared editor settings */\n editorSettings?: EditorBundleSettings<TSettingsComponent>\n /** Custom puzzle editor, if provided by the bundle */\n editor?: {\n /** Called when first visiting a puzzle page. */\n mount(element: HTMLElement, config: EditorMountConfig): Promise<EditorMountHandle>\n }\n}\n"],"mappings":"2NAoBU,sBAAA,CAAA,EAAA,CAOA,SAAA,CAAA,EAAA,CACA,OAAa,iBAAA,CATvB,MAAa,EAAsB,GAAyC,WAC1E,GAAM,CAAE,uBAAA,EAAwB,EAAA,EAAA,EAAS,EAAA,EAAA,CACzC,GAAI,EAAK,KAAM,OAAO,EAEtB,IAAM,EAAA,GAAA,KAAA,IAAA,GAAa,EAAqB,WAClC,EAAO,GAAA,EAAA,GAAA,OAAA,EAAe,EAAY,SAAA,KAAA,IAAA,GAAA,EAAQ,OAAA,KAAQ,EAAE,CAAV,EAAW,CAC3D,GAAI,CAAC,EAAY,OAAA,EAAA,EAAA,EAAA,EAAA,EAAA,CAAY,EAAA,CAAA,EAAA,CAAA,CAAM,OAAA,CAAM,CAEzC,GAAM,CAAE,UAAA,EAAW,EAAA,EAAA,EAAa,EAAA,EAAA,CAC1B,CAAE,KAAM,EAAO,kBAAA,EAAmB,EAAA,EAAA,EAAiB,EAAA,EAAA,CACzD,OAAA,EAAA,EAAA,EAAA,EAAA,EAAA,CAAY,EAAA,CAAA,EAAA,CAAA,CAAM,OAAM,QAAS,CAAE,WAAU,OAAQ,EAAc,CAAE,gBAAA,EAAgB,EAAK,iBAAA,KAAkB,EAAlB,GAAkC,EAI9H,IAAM,EAA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,QAAS,CAAE,IAAK,QAAS,IAAK,MAAO,CACrC,UAAW,CAAC,IAAK,IAAI,CACrB,SAAU,EAAE,CACZ,GAAI,EAAE,CACN,EAAG,CAAC,IAAK,IAAI,CACb,mBAAoB,GACrB,CAYY,EAAsB,GAAqD,CACtF,IAAM,EAAoC,EAAE,CAC5C,IAAK,IAAM,KAAQ,EACjB,IAAK,IAAM,KAAO,EAAK,KAAM,SAC3B,IAAM,EAAoB,EAAE,CACtB,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAY,EAAO,KAAA,KAAA,IAAA,GAAA,EAAM,KAAA,CAAS,EAAK,KAAM,CAC7C,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAkB,EAAO,KAAA,KAAA,IAAA,GAAA,EAAM,WAAA,CAAe,EAAK,WAAY,CAGjE,OAAO,KAAK,EAAK,CAAC,SAAQ,EAAO,KAAO,GACxC,OAAO,KAAK,EAAW,CAAC,SAAQ,EAAO,WAAa,GACxD,EAAO,GAAO,EAGlB,OAAO,GCbT,IAAa,EAAb,cAAuC,KAAM,CAC3C,YACE,EACA,EACA,EACA,CACA,MAAM,EAAQ,CAJP,KAAA,KAAA,EAEA,KAAA,cAAA,EAGP,KAAK,KAAO"}
|
|
1
|
+
{"version":3,"file":"index.cjs","names":[],"sources":["../src/bootstrapPayload.ts","../src/gameTracker.ts","../src/analytics.ts","../src/sdk.ts","../src/keyboard.ts","../src/editor.ts"],"sourcesContent":["import type { BootstrapGame, BootstrapGameData, BootstrapSession } from \"./types\"\n\n/**\n * READY_DATA as hosts from before the payload split send it: the gameplay with the puzzle nested\n * inside it, and a flattened game inside that. Deliberately not part of the SDK's public types.\n */\ntype LegacyReadyData = Omit<BootstrapGameData, \"game\" | \"session\"> & {\n game?: BootstrapGame\n session?: BootstrapSession\n startOrFindGameplay?: {\n gamePlayed?: BootstrapSession[\"gameplay\"] & { puzzle: BootstrapSession[\"puzzle\"] & { game?: any; viewerMetadata?: unknown } }\n }\n}\n\n/**\n * Fills in `game` and `session` when READY_DATA comes from a host which only sends the older\n * `startOrFindGameplay` nesting, so the SDK and games only ever see the new shape. A copy of\n * upgradeBootstrapGameData in @puzzmo-com/shared, which the SDK can't depend on.\n */\nexport const normalizeReadyData = (received: unknown): BootstrapGameData => {\n const { startOrFindGameplay, ...data } = received as LegacyReadyData\n if (data.game) return data as BootstrapGameData\n\n const gamePlayed = startOrFindGameplay?.gamePlayed\n const game = gameFromLegacy(gamePlayed?.puzzle?.game ?? {})\n if (!gamePlayed) return { ...data, game }\n\n const { puzzle, ...gameplay } = gamePlayed\n const { game: _game, viewerMetadata, ...puzzleFields } = puzzle\n return { ...data, game, session: { gameplay, puzzle: puzzleFields }, viewerMetadata: data.viewerMetadata ?? viewerMetadata }\n}\n\n/** Builds the game from the flattened fields older hosts put on `puzzle.game`, with no version IDs */\nconst gameFromLegacy = (game: any): BootstrapGame => {\n const flags = game.flagsArr\n return {\n id: game.id ?? \"\",\n slug: game.slug ?? \"\",\n stableSlug: game.stableSlug ?? game.slug ?? \"\",\n displayName: game.displayName ?? \"\",\n version: {\n id: \"\",\n label: null,\n featuresArr: game.featuresArr ?? [0],\n flagsArr: Array.isArray(flags) ? flags : typeof flags === \"number\" ? [flags] : [0],\n runtime: {\n id: \"\",\n version:\n game.assetsSha || game.assetsBaseURL\n ? { id: \"\", assetsSha: game.assetsSha ?? \"\", assetsBaseURL: game.assetsBaseURL ?? \"\" }\n : null,\n },\n },\n }\n}\n","import type { DeviceType, GameAnalyticsContext, LinkClickedInfo } from \"./analytics\"\n\n/**\n * Game analytics event-firing logic for the SDK.\n *\n * This mirrors the runtime's tracker (and the canonical copy in @puzzmo-com/clickhouse/gameTracker\n * used server-side): which host messages map to which events, the engagement thresholds, the\n * payload shape, and the /events endpoint. It is kept here, dependency-free, so the published SDK\n * pulls in none of the clickhouse package's server deps (kysely / @clickhouse/client) and so the\n * public OSS mirror can build it without the private workspace packages present.\n */\n\nexport type GameAnalyticsEventType = \"page_view\" | \"gameplay_active\" | \"active_30s\" | \"completed\" | \"link_click\"\n\ntype GameAnalyticsState = {\n context: GameAnalyticsContext\n updateCount: number\n startTime: Date\n tracked: {\n pageView: boolean\n gameplayActive: boolean\n active30s: boolean\n completed: boolean\n }\n}\n\ntype MessagesSent =\n | \"READY_GAME_LOADED\"\n | \"UPLOAD_NEW_GAME_STATE\"\n | \"GAME_COMPLETED\"\n | \"SHOW_GAME_COMPLETE_SCREEN\"\n | \"UPDATE_GAME_STATE\"\n | string\n\nconst sendGameAnalyticsEvent = async (\n context: GameAnalyticsContext,\n eventType: GameAnalyticsEventType,\n metadata?: Record<string, string | number | boolean>,\n elapsedTimeOnComplete?: number,\n) => {\n try {\n const body = {\n ...context,\n eventType,\n elapsedTimeOnComplete,\n metadata,\n }\n\n const response = await fetch(`${context.apiRoot}events`, {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n // Ensures the event still fires if the user navigates away (e.g. clicking a _blank link)\n keepalive: true,\n })\n\n if (!response.ok) {\n console.warn(`Analytics event failed: ${eventType} - ${response.status} ${response.statusText}`)\n }\n } catch (error) {\n console.warn(`Analytics event error: ${eventType}`, error)\n }\n}\n\nexport const createGameAnalyticsTracker = (context: GameAnalyticsContext) => {\n const state: GameAnalyticsState = {\n context: { ...context, deviceType: context.deviceType ?? detectDeviceType() },\n updateCount: 0,\n startTime: new Date(),\n tracked: {\n pageView: false,\n gameplayActive: false,\n active30s: false,\n completed: false,\n },\n }\n\n const trackEvent = (type: MessagesSent, json?: any) => {\n const now = new Date()\n const timeDiff = now.getTime() - state.startTime.getTime()\n const seconds = timeDiff / 1000\n\n switch (type) {\n case \"READY_GAME_LOADED\": {\n if (!state.tracked.pageView) {\n sendGameAnalyticsEvent(state.context, \"page_view\")\n state.tracked.pageView = true\n }\n break\n }\n\n case \"UPLOAD_NEW_GAME_STATE\": {\n state.updateCount++\n\n // Fire gameplay_active early (after 2 state changes) to indicate user engagement\n if (state.updateCount > 2 && !state.tracked.gameplayActive) {\n sendGameAnalyticsEvent(state.context, \"gameplay_active\")\n state.tracked.gameplayActive = true\n }\n\n // Fire active_30s for sustained engagement\n if (seconds > 30) {\n if (!state.tracked.gameplayActive) {\n sendGameAnalyticsEvent(state.context, \"gameplay_active\")\n state.tracked.gameplayActive = true\n }\n if (!state.tracked.active30s) {\n sendGameAnalyticsEvent(state.context, \"active_30s\")\n state.tracked.active30s = true\n }\n }\n break\n }\n\n case \"GAME_COMPLETED\": {\n if (!state.tracked.completed && json?.input) {\n sendGameAnalyticsEvent(state.context, \"completed\", {}, json.input.elapsedTimeSecs)\n state.tracked.completed = true\n }\n break\n }\n }\n }\n\n const trackLinkClick = (info: LinkClickedInfo) => {\n sendGameAnalyticsEvent(state.context, \"link_click\", info)\n }\n\n return {\n trackEvent,\n trackLinkClick,\n }\n}\n\n/**\n * The kind of device the game runs on, judged by the whole device rather than the game's frame. A copy of\n * detectDeviceType in @puzzmo-com/clickhouse/deviceType, kept dependency-free for the published SDK.\n */\nconst detectDeviceType = (): DeviceType => {\n if (typeof navigator === \"undefined\" || typeof window === \"undefined\") return \"unknown\"\n const userAgent = navigator.userAgent\n\n // iPadOS Safari reports itself as a Mac, so only a touchscreen gives it away\n if (/iPad/.test(userAgent) || (/Macintosh/.test(userAgent) && navigator.maxTouchPoints > 1)) return \"tablet\"\n const mobileHint = (navigator as Navigator & { userAgentData?: { mobile?: boolean } }).userAgentData?.mobile\n if (/iPhone|iPod/.test(userAgent) || mobileHint) return \"mobile\"\n // Android phones carry \"Mobile\", Android tablets leave it out\n if (/Android/.test(userAgent)) return /Mobile/.test(userAgent) ? \"mobile\" : \"tablet\"\n if (/Mobile|Windows Phone/.test(userAgent)) return \"mobile\"\n\n // Anything else whose main input is touch, sized by the screen's short side\n if (window.matchMedia?.(\"(pointer: coarse)\").matches) return Math.min(screen.width, screen.height) < 600 ? \"mobile\" : \"tablet\"\n return \"desktop\"\n}\n","import { createGameAnalyticsTracker } from \"./gameTracker\"\n\nimport type { BootstrapGameData } from \"./types\"\n\n/**\n * Game analytics for the SDK.\n *\n * The event-firing logic — which host messages map to which ClickHouse events, the\n * engagement thresholds, the payload, and the /events endpoint — lives in ./gameTracker,\n * a self-contained mirror of the runtime's tracker. It is kept local (rather than imported\n * from @puzzmo-com/clickhouse) so the published SDK pulls in none of the clickhouse package's\n * server deps, and so the public OSS mirror can build the SDK without the private workspace\n * packages present.\n *\n * This file only adds the SDK-specific glue: deciding whether analytics should run,\n * building the context from bootstrap data, and watching for link clicks. Events are\n * never sent from localhost (dev + the SDK simulator).\n */\n\nexport type LinkClickedInfo = {\n href: string\n text: string\n target: string\n}\n\ntype UserType = \"anon\" | \"user\" | \"paid\"\ntype RuntimeType = \"puzzmo_com\" | \"iframe\" | \"simple_embed\" | \"app_embed\" | \"ios_native\" | \"msn\"\n\n/** Everything the events endpoint needs to attribute an event, mirrors the runtime's context. */\nexport type GameAnalyticsContext = {\n gameSlug: string\n puzzleID: string\n gameplayOwnerID: string\n apiRoot: string\n userType: UserType\n runtimeType: RuntimeType\n userID?: string\n teamSlug?: string\n partnerSlug?: string\n dailyDateKey?: string\n embedID?: string\n /** Defaults to the device the game is running on, see detectDeviceType in ./gameTracker */\n deviceType?: DeviceType\n}\n\n/** Matches the device_type column in ClickHouse, the API classifies events which leave it out */\nexport type DeviceType = \"unknown\" | \"mobile\" | \"tablet\" | \"desktop\"\n\nexport type GameAnalyticsTracker = {\n /** Map an outgoing host message to its analytics event(s), if any. */\n trackEvent: (type: string, json?: any) => void\n /** Report an anchor click inside the game. */\n trackLinkClick: (info: LinkClickedInfo) => void\n}\n\n/**\n * Build the analytics tracker for a game, or null when analytics shouldn't run\n * (the game doesn't bring its own runtime, no browser, running on localhost, or\n * missing bootstrap data).\n */\nexport const createGameAnalytics = (readyData: BootstrapGameData | null): GameAnalyticsTracker | null => {\n // Only games that bring their own runtime track via the SDK — see gameBringsOwnRuntime.\n if (!gameBringsOwnRuntime(readyData)) return null\n\n const endpoint = resolveAnalyticsEndpoint()\n if (!endpoint.enabled) return null\n\n const context = buildAnalyticsContext(readyData, endpoint.apiRoot)\n if (!context) return null\n\n return createGameAnalyticsTracker(context)\n}\n\n/** Delegates document clicks to report anchor navigations. Returns a cleanup function. */\nexport const setupLinkTracking = (onLinkClicked: (info: LinkClickedInfo) => void): (() => void) => {\n if (typeof document === \"undefined\") return () => {}\n\n const handler = (event: MouseEvent) => {\n const node = event.target\n if (!(node instanceof Element)) return\n const anchor = node.closest(\"a[href]\")\n if (!(anchor instanceof HTMLAnchorElement)) return\n\n onLinkClicked({\n href: anchor.href,\n text: anchor.textContent?.trim() ?? \"\",\n target: anchor.target,\n })\n }\n\n document.addEventListener(\"click\", handler)\n return () => document.removeEventListener(\"click\", handler)\n}\n\n/** Picks the events endpoint, and disables analytics entirely on localhost (dev + simulator). */\nconst resolveAnalyticsEndpoint = (): { apiRoot: string; enabled: boolean } => {\n if (typeof window === \"undefined\" || !window.location) return { apiRoot: \"\", enabled: false }\n\n const hostname = window.location.hostname\n const isLocalhost =\n hostname === \"localhost\" ||\n hostname === \"127.0.0.1\" ||\n hostname === \"0.0.0.0\" ||\n hostname === \"[::1]\" ||\n hostname.endsWith(\".localhost\")\n\n if (isLocalhost) return { apiRoot: \"\", enabled: false }\n\n const isStaging = hostname.includes(\"staging\")\n return { apiRoot: isStaging ? \"https://api-staging.puzzmo.com/\" : \"https://api.puzzmo.com/\", enabled: true }\n}\n\n/** Derive the analytics context from the host's bootstrap data, or null if a game isn't present. */\nexport const buildAnalyticsContext = (readyData: BootstrapGameData | null, apiRoot: string): GameAnalyticsContext | null => {\n const session = readyData?.session\n if (!session) return null\n\n const gameplay = session.gameplay\n const puzzle: any = session.puzzle\n const hostContext: any[] = (readyData?.hostContext as any[]) ?? []\n const embedContext = hostContext.find((hc) => hc?.type === \"embed\")\n\n return {\n gameSlug: readyData?.game?.slug || \"unknown\",\n puzzleID: puzzle.id,\n gameplayOwnerID: gameplay.ownerID || readyData?.userState?.id || \"unknown\",\n apiRoot,\n userType: mapUserType(readyData?.currentUser?.type),\n runtimeType: getRuntimeType(hostContext),\n userID: readyData?.currentUser?.id,\n teamSlug: puzzle.team?.slug || undefined,\n // Embeds carry their partner in the embed context; partner pages on puzzmo.com send it top-level\n partnerSlug: embedContext?.partner?.slug || readyData?.partnerSlug || undefined,\n dailyDateKey: puzzle.mostRecentDaily?.daily?.dateKey,\n embedID: embedContext?.embedID || undefined,\n }\n}\n\n/** Map the user's subscription tier to the analytics user bucket. */\nconst mapUserType = (type: string | null | undefined): UserType => {\n if (!type || type === \"Unverified\") return \"anon\"\n if (type === \"Paid\") return \"paid\"\n return \"user\"\n}\n\n// GameFlags1.bringsOwnRuntime — see packages/shared/flags/gameFlags.ts. Inlined to keep the SDK\n// free of the @puzzmo-com/shared workspace dep (the OSS mirror doesn't have that package).\nconst bringsOwnRuntimeFlag = 1 << 9\n\n/**\n * Whether the bootstrapped game has the \"brings own runtime\" flag set. SDK analytics only\n * run for these games; the standard Puzzmo runtime tracks the same events itself, so gating\n * here avoids double-counting for games that don't bring their own runtime.\n */\nconst gameBringsOwnRuntime = (readyData: BootstrapGameData | null): boolean => {\n const flagValue = readyData?.game?.version.flagsArr[0] ?? 0\n return (flagValue & bringsOwnRuntimeFlag) === bringsOwnRuntimeFlag\n}\n\n/** Derive the runtime bucket from host context, mirroring the runtime's getRuntimeType. */\nconst getRuntimeType = (hostContext: any[]): RuntimeType => {\n const embed = hostContext.find((hc) => hc?.type === \"embed\")\n if (embed) return embed.host === \"msn\" ? \"msn\" : \"iframe\"\n\n const app = hostContext.find((hc) => hc?.type === \"app\")\n if (app?.host === \"__embed\") return \"simple_embed\"\n if (app?.host === \"app-embed\") return \"app_embed\"\n if (app?.host === \"ios-app\") return \"ios_native\"\n\n return \"puzzmo_com\"\n}\n","import { normalizeReadyData } from \"./bootstrapPayload\"\nimport { createGameAnalytics, setupLinkTracking, type GameAnalyticsTracker } from \"./analytics\"\nimport type { PluginAPIs, SDKPlugin, SDKPluginContext } from \"./plugins\"\nimport type {\n MessagesSentFromEmbed,\n MessagesReceived,\n GamePlay,\n GameCompletedPlay,\n AugmentationConfig,\n CheckpointConfig,\n Theme,\n Deed,\n GameOverMessageUIComponent,\n KeyboardConfig,\n GameSettingsUIComponents,\n AvailableHaptics,\n} from \"./types\"\n\nexport type SDK = PuzzmoSDK\n\nexport interface PuzzmoSDKOptions<Plugins extends readonly SDKPlugin[] = []> {\n /** Optional timeout in ms to wait for READY_DATA (default: 5000) */\n timeout?: number\n /** Plugins to extend the SDK with; each contributes a namespaced API at `sdk.plugins[name]`. */\n plugins?: Plugins\n}\n\n/** The bootstrap info a game needs to set up its board, returned by `sdk.gameReady()`. */\nexport type GameReadyResult = {\n /**\n * The serialized puzzle for this gameplay, in the game's own format. Null when the host sent no\n * play session, e.g. for a mode with no puzzle.\n */\n puzzleString: string | null\n /** The player's saved in-progress board state from a previous session, or null when starting fresh. */\n inputString: string | null\n /** The host's current display theme, so the game can match the surrounding page. */\n theme: Theme | null\n /** True when the player has already finished this puzzle (e.g. re-opening a completed daily). False without a session. */\n completed: boolean\n /** The raw bootstrap payload from the host: user state, the gameplay record, host context, etc. */\n readyData: MessagesReceived[\"READY_DATA\"] | null\n}\n\n/** Player-facing game settings, rendered by the host's settings panel and persisted per-user, per-game. */\nexport interface SDKSettings {\n /**\n * Register the game's settings UI with the host. Component `defaultValue`s are merged\n * underneath the player's saved values, the host shows the components in its settings panel,\n * and the resolved settings object is returned. Listen for the `settingsUpdate` event to\n * react to the player changing values. Call after `gameReady()`.\n */\n initialize: (components: GameSettingsUIComponents[]) => any\n /** Get the current resolved settings object. */\n get: () => any\n /** Merge changes into the current settings and persist them to the host. Returns the updated settings. */\n update: (changes: any) => any\n}\n\n/** The host-rendered on-screen keyboard, for games that take text or symbol input on touch devices. */\nexport interface SDKKeyboard {\n /** Show the on-screen keyboard with the given config. Call again to update state (e.g. to change disabled keys). */\n show: (config: KeyboardConfig) => void\n /** Hide the on-screen keyboard. */\n hide: () => void\n}\n\n/** Device haptics. The host owns the player's setting and the device bridge; a game only asks. */\nexport interface SDKHaptics {\n /**\n * Ask the host to fire a haptic. Fire-and-forget: it is never awaited, never reports back, and\n * is a no-op wherever the host can't deliver one, so a game can call it freely.\n *\n * Where it actually fires:\n *\n * - **Puzzmo's iOS app** — real UIKit haptics, via the native bridge.\n * - **puzzmo.com on Android/desktop** — approximated with `navigator.vibrate` by the page, which is why this goes to the host rather than\n * vibrating from the game. Chrome blocks `navigator.vibrate` outright in cross-origin iframes (since Chrome 55), and games run in one,\n * so a game calling it directly is silently ignored with no way to opt in — there is no Permissions-Policy feature for it.\n * - **Embeds** — no haptic. Our frame is cross-origin to the host page, so the block above applies to the host too, and there is no native\n * bridge. The cue is still forwarded to the host page on the private message stream, so a partner can action it themselves.\n *\n * Haptics are also off entirely when the player has turned them off, and the OS may drop them\n * in silent/DND or on hardware without a motor.\n *\n * @param haptic Which feel to ask for. Named after the iOS generators; other hosts approximate.\n * @param options `id` names the cue this haptic belongs to, for host logs and the simulator.\n */\n play: (haptic: AvailableHaptics, options?: { id?: string }) => void\n}\n\n/**\n * The SDK instance returned by `createPuzzmoSDK` — a game's API surface for talking to whichever\n * host is embedding it (puzzmo.com, a partner embed, or the native apps): bootstrapping the\n * puzzle, syncing progress, reporting completion, and driving host UI like settings and the\n * on-screen keyboard.\n *\n * The expected lifecycle is: `gameReady()` → build your board from the result → `gameLoaded()` →\n * play, persisting via `updateGameState()` → `gameCompleted()` → `showCompletionScreen()`.\n */\nexport interface PuzzmoSDK<Plugins extends readonly SDKPlugin[] = []> {\n /**\n * The play clock. The SDK manages it for you: it starts when the host starts the game, pauses\n * and resumes with the host UI, and its display is mirrored into the host chrome twice a\n * second. Most games only need `addPenalty()` for hint or mistake costs.\n */\n timer: SDKTimer\n\n /** APIs contributed by the plugins passed to `createPuzzmoSDK`, keyed by plugin name. */\n plugins: PluginAPIs<Plugins>\n\n /**\n * Announce that the game is ready to receive data. Sends `READY` to the host and resolves with\n * the bootstrap info once the host replies: the puzzle to load, any saved in-progress state,\n * and the host theme. Call this first — every other API assumes it has resolved. Rejects when\n * the host doesn't reply within `PuzzmoSDKOptions.timeout` (default 5s).\n */\n gameReady: () => Promise<GameReadyResult>\n\n /**\n * Tell the host the game has parsed the puzzle, rendered, and is ready to be revealed. The\n * host dismisses its loading UI and replies with a start signal — listen via `on(\"start\")` to\n * begin play; the timer starts then too.\n */\n gameLoaded: (state?: any) => void\n\n /**\n * Subscribe to a host lifecycle event: `start`, `pause`, `resume`, `retry`, `settingsUpdate`,\n * or the on-screen `keyboard*` events. Returns an unsubscribe function.\n */\n on: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void) => () => void\n\n /** Remove an event listener previously registered with `on`. */\n off: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void) => void\n\n /**\n * Save the player's in-progress state to the server so play can resume later, on any\n * device. `inputString` is the game's own serialized format — it comes back as `inputString`\n * from `gameReady()`. Call whenever the player makes a meaningful move; elapsed time is filled\n * in from the SDK timer unless provided in `play`. Ignored, with a console warning, when there is\n * no gameplay to save to: the host sent no play session, or `gameReady()` hasn't resolved yet.\n */\n updateGameState: (inputString: string, play?: Partial<GamePlay>) => void\n\n /**\n * Report the game as finished. Concludes the timer, fills in elapsed/penalty time when not\n * provided, and uploads the final play plus its deeds — the host uses these for scoring,\n * leaderboards, stats, and other augmentations. Pass progress as `inputString` (the same\n * string `updateGameState()` takes). Follow with `showCompletionScreen()`. Without a play session\n * the result is still reported, with no gameplay ID, when the host negotiated contract \"1.1\" —\n * older hosts can't record one, so the message is dropped with a console warning.\n */\n gameCompleted: (play: GameCompletedPlay, config?: AugmentationConfig) => void\n\n /**\n * Ask the host to show its post-game completion UI. `results` render in the completion\n * sidebar: markdown congratulations, the player's streak stats, and custom stat rows. Call\n * after `gameCompleted()`, typically once your own victory animation has finished.\n */\n showCompletionScreen: (results: GameOverMessageUIComponent[]) => void\n\n /**\n * Record a named mid-game checkpoint. Uploads the current board state and play time, and can\n * run parts of the completion pipeline early (e.g. posting to leaderboards) via\n * `checkpointConfig.process`. A checkpoint is also the host's opportunity to show an ad when\n * `checkpointConfig.interruptible` is true. Ignored, with a console warning, when there is no\n * gameplay to save to: the host sent no play session, or `gameReady()` hasn't resolved yet.\n */\n hitCheckpoint: (checkpointName: string, checkpointConfig: CheckpointConfig, config?: AugmentationConfig) => void\n\n /** Player-facing game settings, rendered in the host's settings panel and persisted per-user, per-game. */\n settings: SDKSettings\n\n /** The host-rendered on-screen keyboard, for games that take text or symbol input on touch devices. */\n keyboard: SDKKeyboard\n\n /** Device haptics, where the host can deliver them. See `SDKHaptics.play` for where that is. */\n haptics: SDKHaptics\n\n /**\n * The raw postMessage transport to the host — an escape hatch for protocol messages the SDK\n * doesn't wrap.\n *\n * @internal\n */\n _hostAPI: {\n sendMessage: <T extends keyof SupportedOutgoingMessages>(type: T, json: SupportedOutgoingMessages[T]) => void\n onMessage: <T extends keyof SupportedIncomingMessages>(type: T, handler: (data: SupportedIncomingMessages[T]) => void) => () => void\n }\n}\n\nexport type SupportedOutgoingMessages = Pick<\n MessagesSentFromEmbed,\n | \"READY\"\n | \"READY_GAME_LOADED\"\n | \"GAME_COMPLETED\"\n | \"SHOW_GAME_COMPLETE_SCREEN\"\n | \"TIMER_TICK\"\n | \"TIMER_SYNC\"\n | \"UPLOAD_NEW_GAME_STATE\"\n | \"HIT_CHECKPOINT\"\n | \"KEYBOARD_UPDATE_CONFIG\"\n | \"INITIALIZE_SETTINGS\"\n | \"UPDATE_SETTINGS_FROM_EMBED\"\n | \"SENSORY_EVENT\"\n>\n\nexport type SupportedIncomingMessages = Pick<\n MessagesReceived,\n | \"READY_DATA\"\n | \"START_GAME\"\n | \"PAUSE_GAME\"\n | \"RESUME_GAME\"\n | \"SETTINGS_UPDATE\"\n | \"RETRY_PUZZLE\"\n | \"KEYBOARD_KEY_PRESS\"\n | \"KEYBOARD_CURSOR_CHANGE\"\n | \"KEYBOARD_CURSOR_END\"\n>\n\ntype MessageHandler<T extends keyof SupportedIncomingMessages> = (data: SupportedIncomingMessages[T]) => void\n\nexport type SDKEventMap = {\n start: void\n pause: void\n resume: void\n retry: void\n /** The player changed a setting in the host UI. The payload is the full resolved settings object. */\n settingsUpdate: any\n /** A key on the on-screen keyboard was tapped. */\n keyboardKeyPress: { key: string }\n /** The drag cursor moved across the keyboard. Only fires when `supportsDragCursor` is true. */\n keyboardCursorChange: { position: [number, number] }\n /** The drag cursor was released. Only fires when `supportsDragCursor` is true. */\n keyboardCursorEnd: void\n}\n\nexport type SDKEventType = keyof SDKEventMap\n\nexport interface SDKTimer {\n /** Get elapsed time in milliseconds */\n timeMs: () => number\n /** Get elapsed time in seconds */\n timeSecs: () => number\n /** Get added/penalty time in milliseconds */\n addedTimeMs: () => number\n /** Get added/penalty time in seconds */\n addedTimeSecs: () => number\n /** Get elapsed time without penalties in seconds */\n timeWithoutPenaltySecs: () => number\n /** Get formatted display strings [elapsed, added] */\n display: () => [string, string]\n /** Add penalty time in milliseconds */\n addPenalty: (ms: number) => void\n /** Set the total penalty time in milliseconds, for games which derive it from their state */\n setPenalty: (ms: number) => void\n /** Check if timer is paused */\n isPaused: () => boolean\n /** Check if timer has been started */\n isRunning: () => boolean\n /** Pause the timer (same as a host-sent PAUSE_GAME); emits \"pause\" on an actual transition. */\n pause: () => void\n /** Resume the timer (same as a host-sent RESUME_GAME); emits \"resume\" on an actual transition. */\n resume: () => void\n}\n\nfunction formatTime(timeMs: number): string {\n const isAnHourOrMore = timeMs >= 60 * 60 * 1000\n return new Date(timeMs)\n .toISOString()\n .slice(isAnHourOrMore ? 11 : 14, -1)\n .split(\".\")[0]\n}\n\nfunction createTimer(\n initialTimeMs = 0,\n initialAddedTimeMs = 0,\n): Omit<SDKTimer, \"pause\" | \"resume\"> & {\n _init: () => void\n _pause: () => void\n _resume: () => void\n _reset: (initialTimeMs?: number, initialAddedTimeMs?: number) => void\n _conclude: () => void\n} {\n let baseTime = initialTimeMs\n let addedTime = initialAddedTimeMs\n let pausedTime = 0\n let concludeTime: number | undefined\n\n let startDate: number | undefined = undefined\n let pausedDate: number | undefined = undefined\n\n const getTime = (): number => {\n if (startDate === undefined) return baseTime + addedTime\n if (concludeTime !== undefined) return concludeTime\n const now = pausedDate ?? performance.now()\n const elapsed = now - startDate - pausedTime\n return baseTime + addedTime + elapsed\n }\n\n return {\n _init: () => {\n if (startDate === undefined) {\n startDate = performance.now()\n pausedDate = undefined\n }\n },\n _pause: () => {\n if (pausedDate !== undefined || startDate === undefined) return\n pausedDate = performance.now()\n },\n _resume: () => {\n if (pausedDate === undefined) return\n pausedTime += performance.now() - pausedDate\n pausedDate = undefined\n },\n _reset: (newInitialTimeMs = 0, newInitialAddedTimeMs = 0) => {\n baseTime = newInitialTimeMs\n addedTime = newInitialAddedTimeMs\n pausedTime = 0\n concludeTime = undefined\n startDate = undefined\n pausedDate = undefined\n },\n _conclude: () => {\n if (pausedDate !== undefined) {\n concludeTime = getTime()\n return\n }\n if (startDate === undefined) {\n concludeTime = baseTime + addedTime\n return\n }\n concludeTime = getTime()\n },\n timeMs: () => getTime(),\n timeSecs: () => getTime() / 1000,\n addedTimeMs: () => addedTime,\n addedTimeSecs: () => addedTime / 1000,\n timeWithoutPenaltySecs: () => (getTime() - addedTime) / 1000,\n addPenalty: (ms: number) => {\n addedTime += ms\n },\n setPenalty: (ms: number) => {\n addedTime = ms\n },\n isPaused: () => pausedDate !== undefined || startDate === undefined,\n isRunning: () => startDate !== undefined && pausedDate === undefined,\n display: () => {\n const elapsed = getTime() - addedTime\n const elapsedStr = formatTime(Math.max(0, elapsed))\n const addedStr = addedTime === 0 ? \"\" : formatTime(addedTime)\n return [elapsedStr, addedStr]\n },\n }\n}\n\nfunction createHostAPI() {\n const messageHandlers = new Map<string, Set<(data: any) => void>>()\n\n const sendMessage = <T extends keyof SupportedOutgoingMessages>(type: T, json: SupportedOutgoingMessages[T]) => {\n const message = { type, json, _: \"p\", __: \"mp\", private: true }\n\n if (\"parent\" in window && window.parent !== window) window.parent.postMessage(message, \"*\")\n\n window.postMessage(message, \"*\")\n\n if (\"webkit\" in window && (window as any).webkit?.messageHandlers?.app) (window as any).webkit.messageHandlers.app.postMessage(message)\n\n if (\"puzzmoMessageString\" in window) (window as any).puzzmoMessageString(JSON.stringify(message))\n\n if (\"ReactNativeWebView\" in window && (window as any).ReactNativeWebView?.postMessage)\n (window as any).ReactNativeWebView.postMessage(JSON.stringify(message))\n\n if (type !== \"TIMER_TICK\" && type !== \"TIMER_SYNC\") console.log(\"[Puzzmo SDK] sent:\", type, json)\n }\n\n const onMessage = <T extends keyof SupportedIncomingMessages>(type: T, handler: MessageHandler<T>) => {\n if (!messageHandlers.has(type)) messageHandlers.set(type, new Set())\n messageHandlers.get(type)!.add(handler)\n\n return () => {\n messageHandlers.get(type)?.delete(handler)\n }\n }\n\n if (typeof window !== \"undefined\") {\n window.addEventListener(\"message\", (event) => {\n if (!event?.data?.type) return\n const msgType = event.data.type as string\n const handlers = messageHandlers.get(msgType)\n if (handlers) {\n const msgData = event.data.data ?? event.data.json ?? {}\n if (msgType !== \"TIMER_TICK\" && msgType !== \"TIMER_SYNC\") console.log(\"[Puzzmo SDK] received:\", msgType, msgData)\n handlers.forEach((handler) => handler(msgData))\n }\n })\n }\n\n return { sendMessage, onMessage }\n}\n\n/**\n * The host<->game contract this SDK speaks, declared in READY and READY_GAME_LOADED: games read\n * `game` and `session`, and handle `session` being absent. Hosts on \"1.0\" always send a session.\n */\nconst sdkRuntimeContract = \"1.1\"\n\nconst hostAPI = createHostAPI()\n\n/** Creates a Puzzmo SDK instance for communicating with the Puzzmo host */\nexport const createPuzzmoSDK = <const Plugins extends readonly SDKPlugin[] = []>(\n options: PuzzmoSDKOptions<Plugins> = {},\n): PuzzmoSDK<Plugins> => {\n let readyData: MessagesReceived[\"READY_DATA\"] | null = null\n let readyDataResolve: ((data: MessagesReceived[\"READY_DATA\"]) => void) | null = null\n\n const getGameplay = () => readyData?.session?.gameplay\n const getGameplayID = () => getGameplay()?.id ?? null\n const getPuzzleString = () => readyData?.session?.puzzle.puzzle ?? null\n const getBoardState = () => getGameplay()?.boardState ?? null\n const getTheme = () => readyData?.theme ?? null\n const getCompleted = () => getGameplay()?.completed ?? false\n\n let warnedNoSession = false\n /** Warns once that a call was dropped: before READY_DATA arrived, or the host sent no play session */\n const warnNoSession = (method: string) => {\n if (warnedNoSession) return\n warnedNoSession = true\n const reason = readyData\n ? \"the host sent no play session, so there is no gameplay to save to\"\n : \"it was called before gameReady() resolved\"\n console.warn(`[Puzzmo SDK] ${method}() was ignored: ${reason}`)\n }\n\n const eventListeners = new Map<SDKEventType, Set<(data?: any) => void>>()\n\n // The resolved settings object — seeded from READY_DATA's saved values, then component\n // defaults are merged underneath when the game calls settings.initialize\n let currentSettings: any | null = null\n\n // ClickHouse game analytics — sends the same lifecycle events the runtime tracks\n // (page_view, gameplay_active, active_30s, completed, link_click). Disabled on localhost.\n let analytics: GameAnalyticsTracker | null = null\n let analyticsCompletedAtStart = false\n\n const trackAnalyticsEvent = (type: string, json?: any) => {\n // Don't re-send progression events for a game that was already completed when loaded\n if (analyticsCompletedAtStart) return\n analytics?.trackEvent(type, json)\n }\n\n const internalTimer = createTimer()\n let timerTickInterval: ReturnType<typeof setInterval> | null = null\n let timerSyncInterval: ReturnType<typeof setInterval> | null = null\n\n const startTimerIntervals = () => {\n if (timerTickInterval) return\n\n timerTickInterval = setInterval(() => {\n if (internalTimer.isPaused()) return\n const [elapsed, added] = internalTimer.display()\n hostAPI.sendMessage(\"TIMER_TICK\", { display: [elapsed, added] })\n }, 500)\n\n timerSyncInterval = setInterval(() => {\n if (internalTimer.isPaused()) return\n hostAPI.sendMessage(\"TIMER_SYNC\", Math.floor(internalTimer.timeWithoutPenaltySecs()))\n }, 10000)\n }\n\n const stopTimerIntervals = () => {\n if (timerTickInterval) {\n clearInterval(timerTickInterval)\n timerTickInterval = null\n }\n if (timerSyncInterval) {\n clearInterval(timerSyncInterval)\n timerSyncInterval = null\n }\n }\n\n const emit = <T extends SDKEventType>(event: T, data?: SDKEventMap[T]) => {\n const listeners = eventListeners.get(event)\n if (listeners) listeners.forEach((listener) => listener(data))\n }\n\n hostAPI.onMessage(\"START_GAME\", () => {\n internalTimer._init()\n startTimerIntervals()\n emit(\"start\")\n })\n\n // Shared by the host-sent PAUSE_GAME/RESUME_GAME messages and the game-initiated\n // sdk.timer.pause()/resume() below, so both paths stop/start the same timer identically.\n const pauseTimer = () => {\n const wasPaused = internalTimer.isPaused()\n internalTimer._pause()\n if (internalTimer.isPaused() !== wasPaused) emit(\"pause\")\n }\n const resumeTimer = () => {\n const wasPaused = internalTimer.isPaused()\n internalTimer._resume()\n if (internalTimer.isPaused() !== wasPaused) emit(\"resume\")\n }\n\n hostAPI.onMessage(\"PAUSE_GAME\", pauseTimer)\n hostAPI.onMessage(\"RESUME_GAME\", resumeTimer)\n\n hostAPI.onMessage(\"SETTINGS_UPDATE\", (data) => {\n currentSettings = { ...currentSettings, ...data }\n emit(\"settingsUpdate\", currentSettings)\n })\n\n hostAPI.onMessage(\"KEYBOARD_KEY_PRESS\", (data) => emit(\"keyboardKeyPress\", data))\n hostAPI.onMessage(\"KEYBOARD_CURSOR_CHANGE\", (data) => emit(\"keyboardCursorChange\", data))\n hostAPI.onMessage(\"KEYBOARD_CURSOR_END\", () => emit(\"keyboardCursorEnd\"))\n\n hostAPI.onMessage(\"RETRY_PUZZLE\", () => {\n internalTimer._reset()\n stopTimerIntervals()\n emit(\"retry\")\n })\n\n hostAPI.onMessage(\"READY_DATA\", (data) => {\n const bootstrapData = normalizeReadyData(data as MessagesReceived[\"READY_DATA\"])\n readyData = bootstrapData\n\n const gamePlayed = bootstrapData.session?.gameplay\n\n // userState.gameSettings is a map keyed by game slug; older records can hold the\n // value as a JSON string rather than an object\n if (currentSettings === null) {\n const gameSlug = bootstrapData.game.slug\n let saved = gameSlug ? bootstrapData.userState?.gameSettings?.[gameSlug] : null\n if (typeof saved === \"string\") {\n try {\n saved = JSON.parse(saved)\n } catch {\n saved = null\n }\n }\n currentSettings = saved ?? {}\n }\n if (gamePlayed) {\n const existingTime = (gamePlayed.elapsedTimeSecs ?? 0) * 1000\n const existingAddedTime = (gamePlayed.additionalTimeAddedSecs ?? 0) * 1000\n internalTimer._reset(existingTime, existingAddedTime)\n }\n\n // Wire up analytics once, from the first bootstrap payload\n if (!analytics) {\n analytics = createGameAnalytics(bootstrapData)\n analyticsCompletedAtStart = gamePlayed?.completed ?? false\n // Link clicks are tracked even for already-completed games, matching the runtime\n if (analytics) setupLinkTracking((info) => analytics!.trackLinkClick(info))\n }\n\n if (readyDataResolve) {\n readyDataResolve(bootstrapData)\n readyDataResolve = null\n }\n })\n\n const timer: SDKTimer = {\n timeMs: () => internalTimer.timeMs(),\n timeSecs: () => internalTimer.timeSecs(),\n addedTimeMs: () => internalTimer.addedTimeMs(),\n addedTimeSecs: () => internalTimer.addedTimeSecs(),\n timeWithoutPenaltySecs: () => internalTimer.timeWithoutPenaltySecs(),\n display: () => internalTimer.display(),\n addPenalty: (ms: number) => internalTimer.addPenalty(ms),\n setPenalty: (ms: number) => internalTimer.setPenalty(ms),\n isPaused: () => internalTimer.isPaused(),\n isRunning: () => internalTimer.isRunning(),\n pause: pauseTimer,\n resume: resumeTimer,\n }\n\n // Wire up plugins. Each gets the host transport (open to the full protocol), the timer, and\n // the bootstrap payload, and contributes a namespaced API onto `sdk.plugins[name]`.\n const pluginContext: SDKPluginContext = {\n send: (type, json) => hostAPI.sendMessage(type as keyof SupportedOutgoingMessages, json as never),\n on: (type, handler) => hostAPI.onMessage(type as keyof SupportedIncomingMessages, handler),\n timer,\n bootstrap: () => readyData,\n }\n const pluginAPIs: Record<string, unknown> = {}\n for (const plugin of options.plugins ?? []) pluginAPIs[plugin.name] = plugin.setup(pluginContext)\n\n return {\n timer,\n\n plugins: pluginAPIs as PluginAPIs<Plugins>,\n\n gameReady: async () => {\n hostAPI.sendMessage(\"READY\", { runtimeContract: sdkRuntimeContract })\n\n // READY_DATA may already be here, answering an earlier READY\n if (!readyData) {\n const timeout = options.timeout ?? 5000\n await new Promise<MessagesReceived[\"READY_DATA\"]>((resolve, reject) => {\n readyDataResolve = resolve\n setTimeout(() => {\n if (readyDataResolve) {\n readyDataResolve = null\n reject(new Error(`Timeout waiting for READY_DATA after ${timeout}ms`))\n }\n }, timeout)\n })\n }\n\n const inputString = getBoardState()\n const result: GameReadyResult = {\n puzzleString: getPuzzleString(),\n inputString,\n theme: getTheme(),\n completed: getCompleted(),\n readyData,\n }\n // boardState is the pre-rename spelling of inputString, kept for untyped callers\n return { ...result, boardState: inputString } as GameReadyResult\n },\n\n gameLoaded: (state: any = {}) => {\n hostAPI.sendMessage(\"READY_GAME_LOADED\", {\n state,\n gameRuntimeContract: sdkRuntimeContract,\n embedRuntimeContract: \"1.0\",\n })\n trackAnalyticsEvent(\"READY_GAME_LOADED\")\n },\n\n on: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void): (() => void) => {\n if (!eventListeners.has(event)) eventListeners.set(event, new Set())\n eventListeners.get(event)!.add(listener)\n return () => {\n eventListeners.get(event)?.delete(listener)\n }\n },\n\n off: <T extends SDKEventType>(event: T, listener: (data?: SDKEventMap[T]) => void) => {\n eventListeners.get(event)?.delete(listener)\n },\n\n updateGameState: (inputString: string, play?: Partial<GamePlay>) => {\n const gameplayID = getGameplayID()\n if (!gameplayID) return warnNoSession(\"updateGameState\")\n\n hostAPI.sendMessage(\"UPLOAD_NEW_GAME_STATE\", {\n id: gameplayID,\n input: {\n boardState: inputString,\n elapsedTimeSecs: play?.elapsedTimeSecs ?? internalTimer.timeWithoutPenaltySecs(),\n additionalTimeAddedSecs: play?.additionalTimeAddedSecs ?? internalTimer.addedTimeSecs(),\n collabUserReferences: [],\n },\n })\n trackAnalyticsEvent(\"UPLOAD_NEW_GAME_STATE\")\n },\n\n gameCompleted: (play: GameCompletedPlay, config?: AugmentationConfig) => {\n internalTimer._conclude()\n stopTimerIntervals()\n\n // Games say inputString; the wire and database say boardState. Untyped callers\n // may still send the old boardState spelling, so keep accepting it at runtime.\n const { inputString, ...rest } = play\n const finalPlay: Partial<GamePlay> = {\n ...rest,\n boardState: inputString ?? (play as { boardState?: string }).boardState,\n elapsedTimeSecs: play.elapsedTimeSecs ?? internalTimer.timeWithoutPenaltySecs(),\n additionalTimeAddedSecs: play.additionalTimeAddedSecs ?? internalTimer.addedTimeSecs(),\n }\n\n const deeds: Deed[] = (config?.deeds as any) ?? []\n deeds.push({ id: \"points\", value: play.pointsAwarded })\n deeds.push({\n id: \"time\",\n value: Math.round(finalPlay.elapsedTimeSecs ?? 0) + Math.round(finalPlay.additionalTimeAddedSecs ?? 0),\n })\n\n const gameplayID = getGameplayID()\n // Without a session there's no gameplay ID; only hosts which negotiated \"1.1\" know to record\n // an id-less completion. A pre-1.1 host sending no gameplay is a host bug, not sessionless play.\n const sessionlessHost = readyData && !readyData.session && readyData.appRuntimeContract === \"1.1\"\n if (gameplayID || sessionlessHost) {\n hostAPI.sendMessage(\"GAME_COMPLETED\", {\n id: gameplayID ?? undefined,\n input: finalPlay,\n config,\n })\n trackAnalyticsEvent(\"GAME_COMPLETED\", { input: finalPlay })\n } else {\n warnNoSession(\"gameCompleted\")\n }\n },\n\n showCompletionScreen: (results: GameOverMessageUIComponent[]) => {\n // showRetry stays in the message contract for a future host play-again button; no host renders one yet\n hostAPI.sendMessage(\"SHOW_GAME_COMPLETE_SCREEN\", { results, showRetry: true })\n },\n\n hitCheckpoint: (checkpointName: string, checkpointConfig: CheckpointConfig, config?: AugmentationConfig) => {\n const gameplayID = getGameplayID()\n if (!gameplayID) return warnNoSession(\"hitCheckpoint\")\n\n const inputStr = getBoardState() ?? \"\"\n const play: Partial<GamePlay> = {\n elapsedTimeSecs: internalTimer.timeWithoutPenaltySecs(),\n additionalTimeAddedSecs: internalTimer.addedTimeSecs(),\n }\n\n hostAPI.sendMessage(\"HIT_CHECKPOINT\", {\n checkpointName,\n gameplay: { inputStr, play },\n checkpointConfig,\n augConfig: config ?? {},\n })\n },\n\n settings: {\n initialize: (components: GameSettingsUIComponents[]) => {\n currentSettings = { ...settingsDefaultsFromComponents(components), ...currentSettings }\n hostAPI.sendMessage(\"INITIALIZE_SETTINGS\", { components, settings: currentSettings })\n return currentSettings\n },\n get: () => currentSettings ?? {},\n update: (changes: any) => {\n currentSettings = { ...currentSettings, ...changes }\n hostAPI.sendMessage(\"UPDATE_SETTINGS_FROM_EMBED\", { settings: currentSettings })\n return currentSettings\n },\n },\n\n keyboard: {\n show: (config: KeyboardConfig) => {\n hostAPI.sendMessage(\"KEYBOARD_UPDATE_CONFIG\", config)\n },\n hide: () => {\n hostAPI.sendMessage(\"KEYBOARD_UPDATE_CONFIG\", {\n layout: [],\n symbols: {},\n highlight: [],\n disabled: [],\n xl: [],\n l: [],\n supportsDragCursor: false,\n })\n },\n },\n\n haptics: {\n play: (haptic, options) => {\n hostAPI.sendMessage(\"SENSORY_EVENT\", { id: options?.id ?? haptic, haptic })\n },\n },\n\n _hostAPI: hostAPI,\n }\n}\n\n/** Walks settings UI components (recursing into split groups) collecting name → defaultValue pairs */\nfunction settingsDefaultsFromComponents(components: GameSettingsUIComponents[]): Record<string, unknown> {\n const defaults: Record<string, unknown> = {}\n for (const component of components) {\n if (component.type === \"split\") Object.assign(defaults, settingsDefaultsFromComponents(component.content))\n else if (\"name\" in component) defaults[component.name] = component.defaultValue\n }\n return defaults\n}\n","import type { KeyboardConfig, KeyStyleRule, KeyStyles } from \"./types\"\n\n/**\n * A standard QWERTY layout with Enter and Backspace — a reasonable default for\n * any game that needs text input. Customize from here by spreading and overriding.\n *\n * @example\n * // Use as-is\n * sdk.keyboard.show(defaultKeyboardConfig)\n *\n * @example\n * // Extend with dynamic disabled letters\n * sdk.keyboard.show({ ...defaultKeyboardConfig, disabled: usedLetters })\n */\nexport const defaultKeyboardConfig: KeyboardConfig = {\n layout: [\"qwertyuiop\", \"asdfghjkl\", \"↵zxcvbnm⌫\", undefined],\n symbols: { \"↵\": \"enter\", \"⌫\": \"bsp\" },\n highlight: [\"↵\", \"⌫\"],\n disabled: [],\n xl: [],\n l: [\"↵\", \"⌫\"],\n supportsDragCursor: false,\n}\n\n/**\n * Expands per-key-set styling rules into the `individualKeyStyles` map a `KeyboardConfig` carries,\n * so a game can style a group of keys in one go. Later rules win where two name the same key.\n *\n * @example\n * sdk.keyboard.show({\n * ...defaultKeyboardConfig,\n * individualKeyStyles: keyStylesFromRules([{ keys: usedLetters, text: { opacity: \"0.4\" } }]),\n * })\n */\nexport const keyStylesFromRules = (rules: KeyStyleRule[]): Record<string, KeyStyles> => {\n const styles: Record<string, KeyStyles> = {}\n for (const rule of rules) {\n for (const key of rule.keys) {\n const merged: KeyStyles = {}\n const text = { ...styles[key]?.text, ...rule.text }\n const background = { ...styles[key]?.background, ...rule.background }\n // Only the groups a rule actually set, so a text-only rule doesn't carry an empty background\n // for every key it names.\n if (Object.keys(text).length) merged.text = text\n if (Object.keys(background).length) merged.background = background\n styles[key] = merged\n }\n }\n return styles\n}\n","// For now, we will keep these types in here but not mark them as something which should appear in the public SDK docs\n\nimport type { Theme } from \"./types\"\n\n/**\n * The theme passed to an editor bundle. The host sends its full {@link Theme} so editors derive\n * their colors from it rather than making their own theme decisions. Use `theme.type` for\n * light/dark bucketing.\n *\n * The bare `\"light\" | \"dark\"` string form is deprecated and will be removed in a future SDK\n * release — editors should handle the full `Theme` object.\n */\nexport type EditorTheme = Theme | \"light\" | \"dark\"\n\n/** Severity level for validation issues */\nexport type ValidationLevel = \"error\" | \"warning\" | \"info\"\n\n/** Represents a single validation issue found during puzzle validation */\nexport interface ValidationIssue {\n level: ValidationLevel\n message: string\n line?: number\n col?: number\n length?: number\n}\n\n/** Complete validation report for a puzzle */\nexport interface ValidationReport {\n success: boolean\n issues: ValidationIssue[]\n}\n\nexport type ImportErrorType = \"invalid_format\" | \"parsing_error\" | \"unknown\"\n\n/** Custom error class for workshop import failures */\nexport class EditorImportError extends Error {\n constructor(\n public type: ImportErrorType,\n message: string,\n public originalError?: unknown,\n ) {\n super(message)\n this.name = \"EditorImportError\"\n }\n}\n\n/** Result of a successful puzzle import operation */\nexport interface ImportResult {\n data: string\n warnings?: ValidationIssue[]\n title?: string\n authors?: string[]\n editors?: string[]\n}\n\n/** Settings UI descriptor returned by an editor bundle */\nexport interface EditorBundleSettings<TComponent = unknown> {\n components: TComponent[]\n defaults: Record<string, unknown>\n}\n\n/** A preceding/following phrase for a word, returned by the getRelatedWords editor callback */\nexport interface RelatedWord {\n word: string\n frequency: number\n position: \"preceding\" | \"following\"\n}\n\n/** Result of fetching a URL from within the editor */\nexport interface EditorFetchURLResult {\n status: number\n body: string\n}\n\n/** Config passed to an editor bundle's mount() */\nexport interface EditorMountConfig {\n puzzleString: string\n onChange: (puzzleString: string) => void\n theme: EditorTheme\n width: number\n height: number\n /**\n * Optional function for making chat completions from the editor (e.g. for AI-assisted puzzle\n * editing). This needs to be enabled for a team explicitly.\n */\n chatCompletion?: (prompt: string) => Promise<string>\n /**\n * Optional function for fetching URLs from the editor (e.g. for fetching article content).\n * This needs to be enabled for a team explicitly.\n */\n fetchURL?: (url: string) => Promise<EditorFetchURLResult>\n /** Optional function for looking up a word's preceding/following phrases from wordvault. */\n getRelatedWords?: (word: string, limit?: number) => Promise<RelatedWord[]>\n /** Pre-configured editor settings values from the queue's editorSettings. */\n settings?: Record<string, unknown>\n}\n\n/** Handle returned by an editor bundle's mount() */\nexport interface EditorMountHandle {\n unmount: () => void\n /**\n * Called whenever the puzzle string is updated in the editor from the outside, or when the theme\n * or dimensions update. Workshop will rely on the validator to reject / accept updates.\n */\n update: (config: { puzzleString?: string; theme?: EditorTheme; width?: number; height?: number }) => void\n}\n\n/** Main interface for a Workshop editor bundle */\nexport interface EditorBundle<TSettingsComponent = unknown> {\n /** Required validator for puzzle data validation */\n validator: {\n validate(data: string): Promise<ValidationReport> | ValidationReport\n }\n /** Optional importer for converting external puzzle file formats */\n importer?: {\n onImport(filename: string, contents: string | ArrayBuffer): Promise<ImportResult> | ImportResult\n }\n /** Embed-level settings UI, populated from the bundle's declared settings */\n settings?: EditorBundleSettings<TSettingsComponent>\n /** Editor-level settings UI, populated from the bundle's declared editor settings */\n editorSettings?: EditorBundleSettings<TSettingsComponent>\n /** Custom puzzle editor, if provided by the bundle */\n editor?: {\n /** Called when first visiting a puzzle page. */\n mount(element: HTMLElement, config: EditorMountConfig): Promise<EditorMountHandle>\n }\n}\n"],"mappings":"2NAoBU,sBAAA,CAAA,EAAA,CAOA,SAAA,CAAA,EAAA,CACA,OAAa,iBAAA,CATvB,MAAa,EAAsB,GAAyC,WAC1E,GAAM,CAAE,uBAAA,EAAwB,EAAA,EAAA,EAAS,EAAA,EAAA,CACzC,GAAI,EAAK,KAAM,OAAO,EAEtB,IAAM,EAAA,GAAA,KAAA,IAAA,GAAa,EAAqB,WAClC,EAAO,GAAA,EAAA,GAAA,OAAA,EAAe,EAAY,SAAA,KAAA,IAAA,GAAA,EAAQ,OAAA,KAAQ,EAAE,CAAV,EAAW,CAC3D,GAAI,CAAC,EAAY,OAAA,EAAA,EAAA,EAAA,EAAA,EAAA,CAAY,EAAA,CAAA,EAAA,CAAA,CAAM,OAAA,CAAM,CAEzC,GAAM,CAAE,UAAA,EAAW,EAAA,EAAA,EAAa,EAAA,EAAA,CAC1B,CAAE,KAAM,EAAO,kBAAA,EAAmB,EAAA,EAAA,EAAiB,EAAA,EAAA,CACzD,OAAA,EAAA,EAAA,EAAA,EAAA,EAAA,CAAY,EAAA,CAAA,EAAA,CAAA,CAAM,OAAM,QAAS,CAAE,WAAU,OAAQ,EAAc,CAAE,gBAAA,EAAgB,EAAK,iBAAA,KAAkB,EAAlB,GAAkC,EAI9H,IAAM,EAAkB,GAA6B,qBACnD,IAAM,EAAQ,EAAK,SACnB,MAAO,CACL,IAAA,EAAI,EAAK,KAAA,KAAM,GAAN,EACT,MAAA,EAAM,EAAK,OAAA,KAAQ,GAAR,EACX,YAAA,GAAA,EAAY,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D,OAAQ,CAAC,aAAc,YAAa,YAAa,IAAA,GAAU,CAC3D,QAAS,CAAE,IAAK,QAAS,IAAK,MAAO,CACrC,UAAW,CAAC,IAAK,IAAI,CACrB,SAAU,EAAE,CACZ,GAAI,EAAE,CACN,EAAG,CAAC,IAAK,IAAI,CACb,mBAAoB,GACrB,CAYY,EAAsB,GAAqD,CACtF,IAAM,EAAoC,EAAE,CAC5C,IAAK,IAAM,KAAQ,EACjB,IAAK,IAAM,KAAO,EAAK,KAAM,SAC3B,IAAM,EAAoB,EAAE,CACtB,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAY,EAAO,KAAA,KAAA,IAAA,GAAA,EAAM,KAAA,CAAS,EAAK,KAAM,CAC7C,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAA,EAAkB,EAAO,KAAA,KAAA,IAAA,GAAA,EAAM,WAAA,CAAe,EAAK,WAAY,CAGjE,OAAO,KAAK,EAAK,CAAC,SAAQ,EAAO,KAAO,GACxC,OAAO,KAAK,EAAW,CAAC,SAAQ,EAAO,WAAa,GACxD,EAAO,GAAO,EAGlB,OAAO,GCbT,IAAa,EAAb,cAAuC,KAAM,CAC3C,YACE,EACA,EACA,EACA,CACA,MAAM,EAAQ,CAJP,KAAA,KAAA,EAEA,KAAA,cAAA,EAGP,KAAK,KAAO"}
|
package/dist/index.global.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
var PuzzmoSDK=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.defineProperty,n=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),r=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r};function i(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.includes(r))continue;n[r]=e[r]}return n}function a(e,t){if(e==null)return{};var n,r,a=i(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.includes(n)||{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function o(e){"@babel/helpers - typeof";return o=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},o(e)}function s(e,t){if(o(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(o(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function c(e){var t=s(e,`string`);return o(t)==`symbol`?t:t+``}function l(e,t,n){return(t=c(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function u(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function d(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?u(Object(n),!0).forEach(function(t){l(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):u(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var f=[`startOrFindGameplay`],p=[`puzzle`],m=[`game`,`viewerMetadata`];let h=e=>{var t,n,r;let{startOrFindGameplay:i}=e,o=a(e,f);if(o.game)return o;let s=i==null?void 0:i.gamePlayed,c=g((t=s==null||(n=s.puzzle)==null?void 0:n.game)==null?{}:t);if(!s)return d(d({},o),{},{game:c});let{puzzle:l}=s,u=a(s,p),{game:h,viewerMetadata:_}=l,v=a(l,m);return d(d({},o),{},{game:c,session:{gameplay:u,puzzle:v},viewerMetadata:(r=o.viewerMetadata)==null?_:r})};var g=e=>{var t,n,r,i,a,o,s,c;let l=e.flagsArr;return{id:(t=e.id)==null?``:t,slug:(n=e.slug)==null?``:n,stableSlug:(r=(i=e.stableSlug)==null?e.slug:i)==null?``:r,displayName:(a=e.displayName)==null?``:a,version:{id:``,label:null,featuresArr:(o=e.featuresArr)==null?[0]:o,flagsArr:Array.isArray(l)?l:typeof l==`number`?[l]:[0],runtime:{id:``,version:e.assetsSha||e.assetsBaseURL?{id:``,assetsSha:(s=e.assetsSha)==null?``:s,assetsBaseURL:(c=e.assetsBaseURL)==null?``:c}:null}}}};function _(e,t,n,r,i,a,o){try{var s=e[a](o),c=s.value}catch(e){n(e);return}s.done?t(c):Promise.resolve(c).then(r,i)}function v(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var a=e.apply(t,n);function o(e){_(a,r,i,o,s,`next`,e)}function s(e){_(a,r,i,o,s,`throw`,e)}o(void 0)})}}var y=function(){var e=v(function*(e,t,n,r){try{let i=d(d({},e),{},{eventType:t,elapsedTimeOnComplete:r,metadata:n}),a=yield fetch(`${e.apiRoot}events`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i),keepalive:!0});a.ok||console.warn(`Analytics event failed: ${t} - ${a.status} ${a.statusText}`)}catch(e){console.warn(`Analytics event error: ${t}`,e)}});return function(t,n,r,i){return e.apply(this,arguments)}}();let b=e=>{var t;let n={context:d(d({},e),{},{deviceType:(t=e.deviceType)==null?x():t}),updateCount:0,startTime:new Date,tracked:{pageView:!1,gameplayActive:!1,active30s:!1,completed:!1}};return{trackEvent:(e,t)=>{let r=(new Date().getTime()-n.startTime.getTime())/1e3;switch(e){case`READY_GAME_LOADED`:n.tracked.pageView||(y(n.context,`page_view`),n.tracked.pageView=!0);break;case`UPLOAD_NEW_GAME_STATE`:n.updateCount++,n.updateCount>2&&!n.tracked.gameplayActive&&(y(n.context,`gameplay_active`),n.tracked.gameplayActive=!0),r>30&&(n.tracked.gameplayActive||(y(n.context,`gameplay_active`),n.tracked.gameplayActive=!0),n.tracked.active30s||(y(n.context,`active_30s`),n.tracked.active30s=!0));break;case`GAME_COMPLETED`:!n.tracked.completed&&t!=null&&t.input&&(y(n.context,`completed`,{},t.input.elapsedTimeSecs),n.tracked.completed=!0);break}},trackLinkClick:e=>{y(n.context,`link_click`,e)}}};var x=()=>{var e,t,n;if(typeof navigator>`u`||typeof window>`u`)return`unknown`;let r=navigator.userAgent;if(/iPad/.test(r)||/Macintosh/.test(r)&&navigator.maxTouchPoints>1)return`tablet`;let i=(e=navigator.userAgentData)==null?void 0:e.mobile;return/iPhone|iPod/.test(r)||i?`mobile`:/Android/.test(r)?/Mobile/.test(r)?`mobile`:`tablet`:/Mobile|Windows Phone/.test(r)?`mobile`:(t=(n=window).matchMedia)!=null&&t.call(n,`(pointer: coarse)`).matches?Math.min(screen.width,screen.height)<600?`mobile`:`tablet`:`desktop`};let S=e=>{if(!O(e))return null;let t=w();if(!t.enabled)return null;let n=T(e,t.apiRoot);return n?b(n):null},C=e=>{if(typeof document>`u`)return()=>{};let t=t=>{var n,r;let i=t.target;if(!(i instanceof Element))return;let a=i.closest(`a[href]`);a instanceof HTMLAnchorElement&&e({href:a.href,text:(n=(r=a.textContent)==null?void 0:r.trim())==null?``:n,target:a.target})};return document.addEventListener(`click`,t),()=>document.removeEventListener(`click`,t)};var w=()=>{if(typeof window>`u`||!window.location)return{apiRoot:``,enabled:!1};let e=window.location.hostname;return e===`localhost`||e===`127.0.0.1`||e===`0.0.0.0`||e===`[::1]`||e.endsWith(`.localhost`)?{apiRoot:``,enabled:!1}:{apiRoot:e.includes(`staging`)?`https://api-staging.puzzmo.com/`:`https://api.puzzmo.com/`,enabled:!0}};let T=(e,t)=>{var n,r,i,a,o,s,c,l;let u=e==null?void 0:e.session;if(!u)return null;let d=u.gameplay,f=u.puzzle,p=(n=e==null?void 0:e.hostContext)==null?[]:n,m=p.find(e=>(e==null?void 0:e.type)===`embed`);return{gameSlug:(e==null||(r=e.game)==null?void 0:r.slug)||`unknown`,puzzleID:f.id,gameplayOwnerID:d.ownerID||(e==null||(i=e.userState)==null?void 0:i.id)||`unknown`,apiRoot:t,userType:E(e==null||(a=e.currentUser)==null?void 0:a.type),runtimeType:k(p),userID:e==null||(o=e.currentUser)==null?void 0:o.id,teamSlug:((s=f.team)==null?void 0:s.slug)||void 0,partnerSlug:(m==null||(c=m.partner)==null?void 0:c.slug)||(e==null?void 0:e.partnerSlug)||void 0,dailyDateKey:(l=f.mostRecentDaily)==null||(l=l.daily)==null?void 0:l.dateKey,embedID:(m==null?void 0:m.embedID)||void 0}};var E=e=>!e||e===`Unverified`?`anon`:e===`Paid`?`paid`:`user`,D=512,O=e=>{var t,n;return(((t=e==null||(n=e.game)==null?void 0:n.version.flagsArr[0])==null?0:t)&D)===D},k=e=>{let t=e.find(e=>(e==null?void 0:e.type)===`embed`);if(t)return t.host===`msn`?`msn`:`iframe`;let n=e.find(e=>(e==null?void 0:e.type)===`app`);return(n==null?void 0:n.host)===`__embed`?`simple_embed`:(n==null?void 0:n.host)===`app-embed`?`app_embed`:(n==null?void 0:n.host)===`ios-app`?`ios_native`:`puzzmo_com`},ee=[`inputString`];function A(e){let t=e>=3600*1e3;return new Date(e).toISOString().slice(t?11:14,-1).split(`.`)[0]}function j(e=0,t=0){let n=e,r=t,i=0,a,o,s,c=()=>{var e;if(o===void 0)return n+r;if(a!==void 0)return a;let t=((e=s)==null?performance.now():e)-o-i;return n+r+t};return{_init:()=>{o===void 0&&(o=performance.now(),s=void 0)},_pause:()=>{s!==void 0||o===void 0||(s=performance.now())},_resume:()=>{s!==void 0&&(i+=performance.now()-s,s=void 0)},_reset:(e=0,t=0)=>{n=e,r=t,i=0,a=void 0,o=void 0,s=void 0},_conclude:()=>{if(s!==void 0){a=c();return}if(o===void 0){a=n+r;return}a=c()},timeMs:()=>c(),timeSecs:()=>c()/1e3,addedTimeMs:()=>r,addedTimeSecs:()=>r/1e3,timeWithoutPenaltySecs:()=>(c()-r)/1e3,addPenalty:e=>{r+=e},setPenalty:e=>{r=e},isPaused:()=>s!==void 0||o===void 0,isRunning:()=>o!==void 0&&s===void 0,display:()=>{let e=c()-r;return[A(Math.max(0,e)),r===0?``:A(r)]}}}function M(){let e=new Map;return typeof window<`u`&&window.addEventListener(`message`,t=>{var n;if(!(!(t==null||(n=t.data)==null)&&n.type))return;let r=t.data.type,i=e.get(r);if(i){var a,o;let e=(a=(o=t.data.data)==null?t.data.json:o)==null?{}:a;r!==`TIMER_TICK`&&r!==`TIMER_SYNC`&&console.log(`[Puzzmo SDK] received:`,r,e),i.forEach(t=>t(e))}}),{sendMessage:(e,t)=>{var n,r;let i={type:e,json:t,_:`p`,__:`mp`,private:!0};`parent`in window&&window.parent!==window&&window.parent.postMessage(i,`*`),window.postMessage(i,`*`),`webkit`in window&&!((n=window.webkit)==null||(n=n.messageHandlers)==null)&&n.app&&window.webkit.messageHandlers.app.postMessage(i),`puzzmoMessageString`in window&&window.puzzmoMessageString(JSON.stringify(i)),`ReactNativeWebView`in window&&(r=window.ReactNativeWebView)!=null&&r.postMessage&&window.ReactNativeWebView.postMessage(JSON.stringify(i)),e!==`TIMER_TICK`&&e!==`TIMER_SYNC`&&console.log(`[Puzzmo SDK] sent:`,e,t)},onMessage:(t,n)=>(e.has(t)||e.set(t,new Set),e.get(t).add(n),()=>{var r;(r=e.get(t))==null||r.delete(n)})}}var N=`1.0`,P=M();let F=(e={})=>{var t;let n=null,r=null,i=()=>{var e;return n==null||(e=n.session)==null?void 0:e.gameplay},o=()=>{var e,t;return(e=(t=i())==null?void 0:t.id)==null?null:e},s=()=>{var e,t;return(e=n==null||(t=n.session)==null?void 0:t.puzzle.puzzle)==null?null:e},c=()=>{var e,t;return(e=(t=i())==null?void 0:t.boardState)==null?null:e},l=()=>{var e;return(e=n==null?void 0:n.theme)==null?null:e},u=()=>{var e,t;return(e=(t=i())==null?void 0:t.completed)==null?!1:e},f=new Map,p=null,m=null,g=!1,_=(e,t)=>{g||m==null||m.trackEvent(e,t)},y=j(),b=null,x=null,w=()=>{b||(b=setInterval(()=>{if(y.isPaused())return;let[e,t]=y.display();P.sendMessage(`TIMER_TICK`,{display:[e,t]})},500),x=setInterval(()=>{y.isPaused()||P.sendMessage(`TIMER_SYNC`,Math.floor(y.timeWithoutPenaltySecs()))},1e4))},T=()=>{b&&(clearInterval(b),b=null),x&&(clearInterval(x),x=null)},E=(e,t)=>{let n=f.get(e);n&&n.forEach(e=>e(t))};P.onMessage(`START_GAME`,()=>{y._init(),w(),E(`start`)});let D=()=>{let e=y.isPaused();y._pause(),y.isPaused()!==e&&E(`pause`)},O=()=>{let e=y.isPaused();y._resume(),y.isPaused()!==e&&E(`resume`)};P.onMessage(`PAUSE_GAME`,D),P.onMessage(`RESUME_GAME`,O),P.onMessage(`SETTINGS_UPDATE`,e=>{p=d(d({},p),e),E(`settingsUpdate`,p)}),P.onMessage(`KEYBOARD_KEY_PRESS`,e=>E(`keyboardKeyPress`,e)),P.onMessage(`KEYBOARD_CURSOR_CHANGE`,e=>E(`keyboardCursorChange`,e)),P.onMessage(`KEYBOARD_CURSOR_END`,()=>E(`keyboardCursorEnd`)),P.onMessage(`RETRY_PUZZLE`,()=>{y._reset(),T(),E(`retry`)}),P.onMessage(`READY_DATA`,e=>{var t;let i=h(e);n=i;let a=(t=i.session)==null?void 0:t.gameplay;if(p===null){var o,s;let e=i.game.slug,t=e?(o=i.userState)==null||(o=o.gameSettings)==null?void 0:o[e]:null;if(typeof t==`string`)try{t=JSON.parse(t)}catch(e){t=null}p=(s=t)==null?{}:s}if(a){var c,l;let e=((c=a.elapsedTimeSecs)==null?0:c)*1e3,t=((l=a.additionalTimeAddedSecs)==null?0:l)*1e3;y._reset(e,t)}if(!m){var u;m=S(i),g=(u=a==null?void 0:a.completed)==null?!1:u,m&&C(e=>m.trackLinkClick(e))}r&&(r(i),r=null)});let k={timeMs:()=>y.timeMs(),timeSecs:()=>y.timeSecs(),addedTimeMs:()=>y.addedTimeMs(),addedTimeSecs:()=>y.addedTimeSecs(),timeWithoutPenaltySecs:()=>y.timeWithoutPenaltySecs(),display:()=>y.display(),addPenalty:e=>y.addPenalty(e),setPenalty:e=>y.setPenalty(e),isPaused:()=>y.isPaused(),isRunning:()=>y.isRunning(),pause:D,resume:O},A={send:(e,t)=>P.sendMessage(e,t),on:(e,t)=>P.onMessage(e,t),timer:k,bootstrap:()=>n},M={};for(let n of(t=e.plugins)==null?[]:t)M[n.name]=n.setup(A);return{timer:k,plugins:M,gameReady:function(){var t=v(function*(){var t;if(P.sendMessage(`READY`,{runtimeContract:N}),s()){let e=c();return{puzzleString:s(),inputString:e,boardState:e,theme:l(),completed:u(),readyData:n}}let i=(t=e.timeout)==null?5e3:t;yield new Promise((e,t)=>{r=e,setTimeout(()=>{r&&(r=null,t(Error(`Timeout waiting for READY_DATA after ${i}ms`)))},i)});let a=s();if(!a)throw Error(`READY_DATA received but no puzzle data found`);let o=c();return{puzzleString:a,inputString:o,boardState:o,theme:l(),completed:u(),readyData:n}});return function(){return t.apply(this,arguments)}}(),gameLoaded:(e={})=>{P.sendMessage(`READY_GAME_LOADED`,{state:e,gameRuntimeContract:N,embedRuntimeContract:`1.0`}),_(`READY_GAME_LOADED`)},on:(e,t)=>(f.has(e)||f.set(e,new Set),f.get(e).add(t),()=>{var n;(n=f.get(e))==null||n.delete(t)}),off:(e,t)=>{var n;(n=f.get(e))==null||n.delete(t)},updateGameState:(e,t)=>{var n,r;let i=o();i&&(P.sendMessage(`UPLOAD_NEW_GAME_STATE`,{id:i,input:{boardState:e,elapsedTimeSecs:(n=t==null?void 0:t.elapsedTimeSecs)==null?y.timeWithoutPenaltySecs():n,additionalTimeAddedSecs:(r=t==null?void 0:t.additionalTimeAddedSecs)==null?y.addedTimeSecs():r,collabUserReferences:[]}}),_(`UPLOAD_NEW_GAME_STATE`))},gameCompleted:(e,t)=>{var n,r,i,s,c;y._conclude(),T();let{inputString:l}=e,u=d(d({},a(e,ee)),{},{boardState:l==null?e.boardState:l,elapsedTimeSecs:(n=e.elapsedTimeSecs)==null?y.timeWithoutPenaltySecs():n,additionalTimeAddedSecs:(r=e.additionalTimeAddedSecs)==null?y.addedTimeSecs():r}),f=(i=t==null?void 0:t.deeds)==null?[]:i;f.push({id:`points`,value:e.pointsAwarded}),f.push({id:`time`,value:Math.round((s=u.elapsedTimeSecs)==null?0:s)+Math.round((c=u.additionalTimeAddedSecs)==null?0:c)});let p=o();p&&(P.sendMessage(`GAME_COMPLETED`,{id:p,input:u,config:t}),_(`GAME_COMPLETED`,{input:u}))},showCompletionScreen:e=>{P.sendMessage(`SHOW_GAME_COMPLETE_SCREEN`,{results:e,showRetry:!0})},hitCheckpoint:(e,t,n)=>{var r;if(!o())return;let i=(r=c())==null?``:r,a={elapsedTimeSecs:y.timeWithoutPenaltySecs(),additionalTimeAddedSecs:y.addedTimeSecs()};P.sendMessage(`HIT_CHECKPOINT`,{checkpointName:e,gameplay:{inputStr:i,play:a},checkpointConfig:t,augConfig:n==null?{}:n})},settings:{initialize:e=>(p=d(d({},I(e)),p),P.sendMessage(`INITIALIZE_SETTINGS`,{components:e,settings:p}),p),get:()=>{var e;return(e=p)==null?{}:e},update:e=>(p=d(d({},p),e),P.sendMessage(`UPDATE_SETTINGS_FROM_EMBED`,{settings:p}),p)},keyboard:{show:e=>{P.sendMessage(`KEYBOARD_UPDATE_CONFIG`,e)},hide:()=>{P.sendMessage(`KEYBOARD_UPDATE_CONFIG`,{layout:[],symbols:{},highlight:[],disabled:[],xl:[],l:[],supportsDragCursor:!1})}},haptics:{play:(e,t)=>{var n;P.sendMessage(`SENSORY_EVENT`,{id:(n=t==null?void 0:t.id)==null?e:n,haptic:e})}},_hostAPI:P}};function I(e){let t={};for(let n of e)n.type===`split`?Object.assign(t,I(n.content)):`name`in n&&(t[n.name]=n.defaultValue);return t}let L={layout:[`qwertyuiop`,`asdfghjkl`,`↵zxcvbnm⌫`,void 0],symbols:{"↵":`enter`,"⌫":`bsp`},highlight:[`↵`,`⌫`],disabled:[],xl:[],l:[`↵`,`⌫`],supportsDragCursor:!1},R=e=>{let t={};for(let i of e)for(let e of i.keys){var n,r;let a={},o=d(d({},(n=t[e])==null?void 0:n.text),i.text),s=d(d({},(r=t[e])==null?void 0:r.background),i.background);Object.keys(o).length&&(a.text=o),Object.keys(s).length&&(a.background=s),t[e]=a}return t};var z=class extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name=`EditorImportError`}},B=n(((e,t)=>{var n=(function(){var e=String.fromCharCode,t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=`,n=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$`,r={};function i(e,t){if(!r[e]){r[e]={};for(var n=0;n<e.length;n++)r[e][e.charAt(n)]=n}return r[e][t]}var a={compressToBase64:function(e){if(e==null)return``;var n=a._compress(e,6,function(e){return t.charAt(e)});switch(n.length%4){default:case 0:return n;case 1:return n+`===`;case 2:return n+`==`;case 3:return n+`=`}},decompressFromBase64:function(e){return e==null?``:e==``?null:a._decompress(e.length,32,function(n){return i(t,e.charAt(n))})},compressToUTF16:function(t){return t==null?``:a._compress(t,15,function(t){return e(t+32)})+` `},decompressFromUTF16:function(e){return e==null?``:e==``?null:a._decompress(e.length,16384,function(t){return e.charCodeAt(t)-32})},compressToUint8Array:function(e){for(var t=a.compress(e),n=new Uint8Array(t.length*2),r=0,i=t.length;r<i;r++){var o=t.charCodeAt(r);n[r*2]=o>>>8,n[r*2+1]=o%256}return n},decompressFromUint8Array:function(t){if(t==null)return a.decompress(t);for(var n=Array(t.length/2),r=0,i=n.length;r<i;r++)n[r]=t[r*2]*256+t[r*2+1];var o=[];return n.forEach(function(t){o.push(e(t))}),a.decompress(o.join(``))},compressToEncodedURIComponent:function(e){return e==null?``:a._compress(e,6,function(e){return n.charAt(e)})},decompressFromEncodedURIComponent:function(e){return e==null?``:e==``?null:(e=e.replace(/ /g,`+`),a._decompress(e.length,32,function(t){return i(n,e.charAt(t))}))},compress:function(t){return a._compress(t,16,function(t){return e(t)})},_compress:function(e,t,n){if(e==null)return``;var r,i,a={},o={},s=``,c=``,l=``,u=2,d=3,f=2,p=[],m=0,h=0,g;for(g=0;g<e.length;g+=1)if(s=e.charAt(g),Object.prototype.hasOwnProperty.call(a,s)||(a[s]=d++,o[s]=!0),c=l+s,Object.prototype.hasOwnProperty.call(a,c))l=c;else{if(Object.prototype.hasOwnProperty.call(o,l)){if(l.charCodeAt(0)<256){for(r=0;r<f;r++)m<<=1,h==t-1?(h=0,p.push(n(m)),m=0):h++;for(i=l.charCodeAt(0),r=0;r<8;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1}else{for(i=1,r=0;r<f;r++)m=m<<1|i,h==t-1?(h=0,p.push(n(m)),m=0):h++,i=0;for(i=l.charCodeAt(0),r=0;r<16;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1}u--,u==0&&(u=Math.pow(2,f),f++),delete o[l]}else for(i=a[l],r=0;r<f;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1;u--,u==0&&(u=Math.pow(2,f),f++),a[c]=d++,l=String(s)}if(l!==``){if(Object.prototype.hasOwnProperty.call(o,l)){if(l.charCodeAt(0)<256){for(r=0;r<f;r++)m<<=1,h==t-1?(h=0,p.push(n(m)),m=0):h++;for(i=l.charCodeAt(0),r=0;r<8;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1}else{for(i=1,r=0;r<f;r++)m=m<<1|i,h==t-1?(h=0,p.push(n(m)),m=0):h++,i=0;for(i=l.charCodeAt(0),r=0;r<16;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1}u--,u==0&&(u=Math.pow(2,f),f++),delete o[l]}else for(i=a[l],r=0;r<f;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1;u--,u==0&&(u=Math.pow(2,f),f++)}for(i=2,r=0;r<f;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1;for(;;)if(m<<=1,h==t-1){p.push(n(m));break}else h++;return p.join(``)},decompress:function(e){return e==null?``:e==``?null:a._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(t,n,r){var i=[],a=4,o=4,s=3,c=``,l=[],u,d,f,p,m,h,g,_={val:r(0),position:n,index:1};for(u=0;u<3;u+=1)i[u]=u;for(f=0,m=Math.pow(2,2),h=1;h!=m;)p=_.val&_.position,_.position>>=1,_.position==0&&(_.position=n,_.val=r(_.index++)),f|=(p>0?1:0)*h,h<<=1;switch(f){case 0:for(f=0,m=Math.pow(2,8),h=1;h!=m;)p=_.val&_.position,_.position>>=1,_.position==0&&(_.position=n,_.val=r(_.index++)),f|=(p>0?1:0)*h,h<<=1;g=e(f);break;case 1:for(f=0,m=Math.pow(2,16),h=1;h!=m;)p=_.val&_.position,_.position>>=1,_.position==0&&(_.position=n,_.val=r(_.index++)),f|=(p>0?1:0)*h,h<<=1;g=e(f);break;case 2:return``}for(i[3]=g,d=g,l.push(g);;){if(_.index>t)return``;for(f=0,m=Math.pow(2,s),h=1;h!=m;)p=_.val&_.position,_.position>>=1,_.position==0&&(_.position=n,_.val=r(_.index++)),f|=(p>0?1:0)*h,h<<=1;switch(g=f){case 0:for(f=0,m=Math.pow(2,8),h=1;h!=m;)p=_.val&_.position,_.position>>=1,_.position==0&&(_.position=n,_.val=r(_.index++)),f|=(p>0?1:0)*h,h<<=1;i[o++]=e(f),g=o-1,a--;break;case 1:for(f=0,m=Math.pow(2,16),h=1;h!=m;)p=_.val&_.position,_.position>>=1,_.position==0&&(_.position=n,_.val=r(_.index++)),f|=(p>0?1:0)*h,h<<=1;i[o++]=e(f),g=o-1,a--;break;case 2:return l.join(``)}if(a==0&&(a=Math.pow(2,s),s++),i[g])c=i[g];else if(g===o)c=d+d.charAt(0);else return null;l.push(c),i[o++]=d+c.charAt(0),a--,d=c,a==0&&(a=Math.pow(2,s),s++)}}};return a})();typeof define==`function`&&define.amd?define(function(){return n}):t!==void 0&&t!=null?t.exports=n:typeof angular<`u`&&angular!=null&&angular.module(`LZString`,[]).factory(`LZString`,function(){return n})}))();function V(e){if(e.length===0)return`0`;let t=``;for(let n=0;n<e.length;n+=4){let r=0;for(let t=0;t<4&&n+t<e.length;t++)e[n+t]&&(r|=1<<t);t+=r.toString(16)}return t||`0`}function H(e,t){let n=[];for(let r=0;r<t;r++){let t=Math.floor(r/4),i=r%4,a=parseInt(e[t]||`0`,16);n.push((a&1<<i)!=0)}return n}function U(e){if(e.length===0)return``;let t=e.map((e,t)=>({val:e,idx:t})).filter(e=>e.val!==0);return t.length===0?``:t.length>e.length/2?e.join(`,`):t.map(e=>`${e.idx}=${e.val}`).join(`,`)}function W(e,t){if(!e)return t?Array.from({length:t},()=>0):[];if(e.includes(`=`)){let n=t?Array.from({length:t},()=>0):[],r=e.split(`,`);for(let e of r){let[t,r]=e.split(`=`),i=Number(t),a=Number(r);!isNaN(i)&&!isNaN(a)&&(n[i]=a)}return n}return e.split(`,`).map(e=>Number(e))}function G(e,t=`,`){return e.join(t)}function K(e,t=`,`){return e?e.split(t):[]}function q(e){return(0,B.compressToEncodedURIComponent)(JSON.stringify(e))}function J(e){if(!e)return;let t=(0,B.decompressFromEncodedURIComponent)(e);return t?JSON.parse(t):void 0}function Y(e,t,n){let r=Object.entries(e).filter(([e,t])=>t!=null);return n?r.map(([e,r])=>{let i=n.indexOf(e);return i===-1?null:`${i}=${t(r)}`}).filter(e=>e!==null).join(`,`):r.map(([e,n])=>`${e}=${t(n)}`).join(`;`)}function X(e,t,n){if(!e)return{};let r={};if(n){let i=e.split(`,`);for(let e of i){if(!e)continue;let[i,a]=e.split(`=`),o=Number(i);!isNaN(o)&&a&&n[o]&&(r[n[o]]=t(a))}}else{let n=e.split(`;`);for(let e of n){if(!e)continue;let[n,i]=e.split(`=`);n&&i&&(r[n]=t(i))}}return r}function Z(e,t,n){switch(t.type){case`bitArray`:return V(e);case`intArray`:return U(e);case`int`:return String(e);case`string`:return String(e);case`stringArray`:return G(e,t.delimiter);case`sparseMap`:return Y(e,t.valueEncoder,n==null?void 0:n.keys);case`json`:return q(e);default:throw Error(`Unknown field type: ${t.type}`)}}function Q(e,t,n){let r=e.delimiter||`:`,i=Object.keys(e.fields).map(r=>{let i=e.fields[r],a=t[r];return Z(a,i,n==null?void 0:n[r])});return`v${e.version}${r}${i.join(r)}`}function te(e,t,n){switch(t.type){case`bitArray`:if(!(n!=null&&n.length))throw Error(`bitArray requires length in context`);return H(e,n.length);case`intArray`:return W(e,n==null?void 0:n.length);case`int`:return Number(e);case`string`:return e;case`stringArray`:return K(e,t.delimiter);case`sparseMap`:return X(e,t.valueDecoder,n==null?void 0:n.keys);case`json`:return J(e);default:throw Error(`Unknown field type: ${t.type}`)}}function $(e,t,n){let r=e.delimiter||`:`,i=t.split(r),a=i[0],o=a.match(/^v(\d+)$/);if(!o)throw Error(`Invalid input string format: ${a}`);let s=Number(o[1]);if(s!==e.version)throw Error(`Version mismatch: expected v${e.version}, got v${s}. Make sure to run migrations first.`);let c=Object.keys(e.fields),l={};for(let t=0;t<c.length;t++){let r=c[t],a=e.fields[r];l[r]=te(i[t+1]||``,a,n==null?void 0:n[r])}return l}function ne(e){return function(t,n){let r=t.match(/^v(\d+)/);if(!r)throw Error(`Invalid input string: no version found`);let i=Number(r[1]);if(i===e.version)return t;if(!e.migrations)throw Error(`No migrations defined for schema. Cannot migrate from v${i} to v${e.version}`);let a=$(d(d({},e),{},{version:i}),t,n);for(let t=i;t<e.version;t++){let n=e.migrations[t];n&&(a=n(a))}return Q(e,a,n)}}function re(e){return e}var ie=r({createEncoder:()=>ae,defineSchema:()=>re});function ae(e,t){let n=ne(e);return{encode:n=>Q(e,n,t),decode:n=>$(e,n,t),migrate:e=>n(e,t)}}return e.EditorImportError=z,e.createPuzzmoSDK=F,e.defaultKeyboardConfig=L,Object.defineProperty(e,`inputs`,{enumerable:!0,get:function(){return ie}}),e.keyStylesFromRules=R,e})({});
|
|
1
|
+
var PuzzmoSDK=(function(e){Object.defineProperty(e,Symbol.toStringTag,{value:`Module`});var t=Object.defineProperty,n=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),r=(e,n)=>{let r={};for(var i in e)t(r,i,{get:e[i],enumerable:!0});return n||t(r,Symbol.toStringTag,{value:`Module`}),r};function i(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.includes(r))continue;n[r]=e[r]}return n}function a(e,t){if(e==null)return{};var n,r,a=i(e,t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(e);for(r=0;r<o.length;r++)n=o[r],t.includes(n)||{}.propertyIsEnumerable.call(e,n)&&(a[n]=e[n])}return a}function o(e){"@babel/helpers - typeof";return o=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},o(e)}function s(e,t){if(o(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(o(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function c(e){var t=s(e,`string`);return o(t)==`symbol`?t:t+``}function l(e,t,n){return(t=c(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function u(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function d(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?u(Object(n),!0).forEach(function(t){l(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):u(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var f=[`startOrFindGameplay`],p=[`puzzle`],m=[`game`,`viewerMetadata`];let h=e=>{var t,n,r;let{startOrFindGameplay:i}=e,o=a(e,f);if(o.game)return o;let s=i==null?void 0:i.gamePlayed,c=g((t=s==null||(n=s.puzzle)==null?void 0:n.game)==null?{}:t);if(!s)return d(d({},o),{},{game:c});let{puzzle:l}=s,u=a(s,p),{game:h,viewerMetadata:_}=l,v=a(l,m);return d(d({},o),{},{game:c,session:{gameplay:u,puzzle:v},viewerMetadata:(r=o.viewerMetadata)==null?_:r})};var g=e=>{var t,n,r,i,a,o,s,c;let l=e.flagsArr;return{id:(t=e.id)==null?``:t,slug:(n=e.slug)==null?``:n,stableSlug:(r=(i=e.stableSlug)==null?e.slug:i)==null?``:r,displayName:(a=e.displayName)==null?``:a,version:{id:``,label:null,featuresArr:(o=e.featuresArr)==null?[0]:o,flagsArr:Array.isArray(l)?l:typeof l==`number`?[l]:[0],runtime:{id:``,version:e.assetsSha||e.assetsBaseURL?{id:``,assetsSha:(s=e.assetsSha)==null?``:s,assetsBaseURL:(c=e.assetsBaseURL)==null?``:c}:null}}}};function _(e,t,n,r,i,a,o){try{var s=e[a](o),c=s.value}catch(e){n(e);return}s.done?t(c):Promise.resolve(c).then(r,i)}function v(e){return function(){var t=this,n=arguments;return new Promise(function(r,i){var a=e.apply(t,n);function o(e){_(a,r,i,o,s,`next`,e)}function s(e){_(a,r,i,o,s,`throw`,e)}o(void 0)})}}var y=function(){var e=v(function*(e,t,n,r){try{let i=d(d({},e),{},{eventType:t,elapsedTimeOnComplete:r,metadata:n}),a=yield fetch(`${e.apiRoot}events`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(i),keepalive:!0});a.ok||console.warn(`Analytics event failed: ${t} - ${a.status} ${a.statusText}`)}catch(e){console.warn(`Analytics event error: ${t}`,e)}});return function(t,n,r,i){return e.apply(this,arguments)}}();let b=e=>{var t;let n={context:d(d({},e),{},{deviceType:(t=e.deviceType)==null?x():t}),updateCount:0,startTime:new Date,tracked:{pageView:!1,gameplayActive:!1,active30s:!1,completed:!1}};return{trackEvent:(e,t)=>{let r=(new Date().getTime()-n.startTime.getTime())/1e3;switch(e){case`READY_GAME_LOADED`:n.tracked.pageView||(y(n.context,`page_view`),n.tracked.pageView=!0);break;case`UPLOAD_NEW_GAME_STATE`:n.updateCount++,n.updateCount>2&&!n.tracked.gameplayActive&&(y(n.context,`gameplay_active`),n.tracked.gameplayActive=!0),r>30&&(n.tracked.gameplayActive||(y(n.context,`gameplay_active`),n.tracked.gameplayActive=!0),n.tracked.active30s||(y(n.context,`active_30s`),n.tracked.active30s=!0));break;case`GAME_COMPLETED`:!n.tracked.completed&&t!=null&&t.input&&(y(n.context,`completed`,{},t.input.elapsedTimeSecs),n.tracked.completed=!0);break}},trackLinkClick:e=>{y(n.context,`link_click`,e)}}};var x=()=>{var e,t,n;if(typeof navigator>`u`||typeof window>`u`)return`unknown`;let r=navigator.userAgent;if(/iPad/.test(r)||/Macintosh/.test(r)&&navigator.maxTouchPoints>1)return`tablet`;let i=(e=navigator.userAgentData)==null?void 0:e.mobile;return/iPhone|iPod/.test(r)||i?`mobile`:/Android/.test(r)?/Mobile/.test(r)?`mobile`:`tablet`:/Mobile|Windows Phone/.test(r)?`mobile`:(t=(n=window).matchMedia)!=null&&t.call(n,`(pointer: coarse)`).matches?Math.min(screen.width,screen.height)<600?`mobile`:`tablet`:`desktop`};let S=e=>{if(!O(e))return null;let t=w();if(!t.enabled)return null;let n=T(e,t.apiRoot);return n?b(n):null},C=e=>{if(typeof document>`u`)return()=>{};let t=t=>{var n,r;let i=t.target;if(!(i instanceof Element))return;let a=i.closest(`a[href]`);a instanceof HTMLAnchorElement&&e({href:a.href,text:(n=(r=a.textContent)==null?void 0:r.trim())==null?``:n,target:a.target})};return document.addEventListener(`click`,t),()=>document.removeEventListener(`click`,t)};var w=()=>{if(typeof window>`u`||!window.location)return{apiRoot:``,enabled:!1};let e=window.location.hostname;return e===`localhost`||e===`127.0.0.1`||e===`0.0.0.0`||e===`[::1]`||e.endsWith(`.localhost`)?{apiRoot:``,enabled:!1}:{apiRoot:e.includes(`staging`)?`https://api-staging.puzzmo.com/`:`https://api.puzzmo.com/`,enabled:!0}};let T=(e,t)=>{var n,r,i,a,o,s,c,l;let u=e==null?void 0:e.session;if(!u)return null;let d=u.gameplay,f=u.puzzle,p=(n=e==null?void 0:e.hostContext)==null?[]:n,m=p.find(e=>(e==null?void 0:e.type)===`embed`);return{gameSlug:(e==null||(r=e.game)==null?void 0:r.slug)||`unknown`,puzzleID:f.id,gameplayOwnerID:d.ownerID||(e==null||(i=e.userState)==null?void 0:i.id)||`unknown`,apiRoot:t,userType:E(e==null||(a=e.currentUser)==null?void 0:a.type),runtimeType:k(p),userID:e==null||(o=e.currentUser)==null?void 0:o.id,teamSlug:((s=f.team)==null?void 0:s.slug)||void 0,partnerSlug:(m==null||(c=m.partner)==null?void 0:c.slug)||(e==null?void 0:e.partnerSlug)||void 0,dailyDateKey:(l=f.mostRecentDaily)==null||(l=l.daily)==null?void 0:l.dateKey,embedID:(m==null?void 0:m.embedID)||void 0}};var E=e=>!e||e===`Unverified`?`anon`:e===`Paid`?`paid`:`user`,D=512,O=e=>{var t,n;return(((t=e==null||(n=e.game)==null?void 0:n.version.flagsArr[0])==null?0:t)&D)===D},k=e=>{let t=e.find(e=>(e==null?void 0:e.type)===`embed`);if(t)return t.host===`msn`?`msn`:`iframe`;let n=e.find(e=>(e==null?void 0:e.type)===`app`);return(n==null?void 0:n.host)===`__embed`?`simple_embed`:(n==null?void 0:n.host)===`app-embed`?`app_embed`:(n==null?void 0:n.host)===`ios-app`?`ios_native`:`puzzmo_com`},A=[`inputString`];function j(e){let t=e>=3600*1e3;return new Date(e).toISOString().slice(t?11:14,-1).split(`.`)[0]}function M(e=0,t=0){let n=e,r=t,i=0,a,o,s,c=()=>{var e;if(o===void 0)return n+r;if(a!==void 0)return a;let t=((e=s)==null?performance.now():e)-o-i;return n+r+t};return{_init:()=>{o===void 0&&(o=performance.now(),s=void 0)},_pause:()=>{s!==void 0||o===void 0||(s=performance.now())},_resume:()=>{s!==void 0&&(i+=performance.now()-s,s=void 0)},_reset:(e=0,t=0)=>{n=e,r=t,i=0,a=void 0,o=void 0,s=void 0},_conclude:()=>{if(s!==void 0){a=c();return}if(o===void 0){a=n+r;return}a=c()},timeMs:()=>c(),timeSecs:()=>c()/1e3,addedTimeMs:()=>r,addedTimeSecs:()=>r/1e3,timeWithoutPenaltySecs:()=>(c()-r)/1e3,addPenalty:e=>{r+=e},setPenalty:e=>{r=e},isPaused:()=>s!==void 0||o===void 0,isRunning:()=>o!==void 0&&s===void 0,display:()=>{let e=c()-r;return[j(Math.max(0,e)),r===0?``:j(r)]}}}function N(){let e=new Map;return typeof window<`u`&&window.addEventListener(`message`,t=>{var n;if(!(!(t==null||(n=t.data)==null)&&n.type))return;let r=t.data.type,i=e.get(r);if(i){var a,o;let e=(a=(o=t.data.data)==null?t.data.json:o)==null?{}:a;r!==`TIMER_TICK`&&r!==`TIMER_SYNC`&&console.log(`[Puzzmo SDK] received:`,r,e),i.forEach(t=>t(e))}}),{sendMessage:(e,t)=>{var n,r;let i={type:e,json:t,_:`p`,__:`mp`,private:!0};`parent`in window&&window.parent!==window&&window.parent.postMessage(i,`*`),window.postMessage(i,`*`),`webkit`in window&&!((n=window.webkit)==null||(n=n.messageHandlers)==null)&&n.app&&window.webkit.messageHandlers.app.postMessage(i),`puzzmoMessageString`in window&&window.puzzmoMessageString(JSON.stringify(i)),`ReactNativeWebView`in window&&(r=window.ReactNativeWebView)!=null&&r.postMessage&&window.ReactNativeWebView.postMessage(JSON.stringify(i)),e!==`TIMER_TICK`&&e!==`TIMER_SYNC`&&console.log(`[Puzzmo SDK] sent:`,e,t)},onMessage:(t,n)=>(e.has(t)||e.set(t,new Set),e.get(t).add(n),()=>{var r;(r=e.get(t))==null||r.delete(n)})}}var P=`1.1`,F=N();let I=(e={})=>{var t;let n=null,r=null,i=()=>{var e;return n==null||(e=n.session)==null?void 0:e.gameplay},o=()=>{var e,t;return(e=(t=i())==null?void 0:t.id)==null?null:e},s=()=>{var e,t;return(e=n==null||(t=n.session)==null?void 0:t.puzzle.puzzle)==null?null:e},c=()=>{var e,t;return(e=(t=i())==null?void 0:t.boardState)==null?null:e},l=()=>{var e;return(e=n==null?void 0:n.theme)==null?null:e},u=()=>{var e,t;return(e=(t=i())==null?void 0:t.completed)==null?!1:e},f=!1,p=e=>{if(f)return;f=!0;let t=n?`the host sent no play session, so there is no gameplay to save to`:`it was called before gameReady() resolved`;console.warn(`[Puzzmo SDK] ${e}() was ignored: ${t}`)},m=new Map,g=null,_=null,y=!1,b=(e,t)=>{y||_==null||_.trackEvent(e,t)},x=M(),w=null,T=null,E=()=>{w||(w=setInterval(()=>{if(x.isPaused())return;let[e,t]=x.display();F.sendMessage(`TIMER_TICK`,{display:[e,t]})},500),T=setInterval(()=>{x.isPaused()||F.sendMessage(`TIMER_SYNC`,Math.floor(x.timeWithoutPenaltySecs()))},1e4))},D=()=>{w&&(clearInterval(w),w=null),T&&(clearInterval(T),T=null)},O=(e,t)=>{let n=m.get(e);n&&n.forEach(e=>e(t))};F.onMessage(`START_GAME`,()=>{x._init(),E(),O(`start`)});let k=()=>{let e=x.isPaused();x._pause(),x.isPaused()!==e&&O(`pause`)},j=()=>{let e=x.isPaused();x._resume(),x.isPaused()!==e&&O(`resume`)};F.onMessage(`PAUSE_GAME`,k),F.onMessage(`RESUME_GAME`,j),F.onMessage(`SETTINGS_UPDATE`,e=>{g=d(d({},g),e),O(`settingsUpdate`,g)}),F.onMessage(`KEYBOARD_KEY_PRESS`,e=>O(`keyboardKeyPress`,e)),F.onMessage(`KEYBOARD_CURSOR_CHANGE`,e=>O(`keyboardCursorChange`,e)),F.onMessage(`KEYBOARD_CURSOR_END`,()=>O(`keyboardCursorEnd`)),F.onMessage(`RETRY_PUZZLE`,()=>{x._reset(),D(),O(`retry`)}),F.onMessage(`READY_DATA`,e=>{var t;let i=h(e);n=i;let a=(t=i.session)==null?void 0:t.gameplay;if(g===null){var o,s;let e=i.game.slug,t=e?(o=i.userState)==null||(o=o.gameSettings)==null?void 0:o[e]:null;if(typeof t==`string`)try{t=JSON.parse(t)}catch(e){t=null}g=(s=t)==null?{}:s}if(a){var c,l;let e=((c=a.elapsedTimeSecs)==null?0:c)*1e3,t=((l=a.additionalTimeAddedSecs)==null?0:l)*1e3;x._reset(e,t)}if(!_){var u;_=S(i),y=(u=a==null?void 0:a.completed)==null?!1:u,_&&C(e=>_.trackLinkClick(e))}r&&(r(i),r=null)});let N={timeMs:()=>x.timeMs(),timeSecs:()=>x.timeSecs(),addedTimeMs:()=>x.addedTimeMs(),addedTimeSecs:()=>x.addedTimeSecs(),timeWithoutPenaltySecs:()=>x.timeWithoutPenaltySecs(),display:()=>x.display(),addPenalty:e=>x.addPenalty(e),setPenalty:e=>x.setPenalty(e),isPaused:()=>x.isPaused(),isRunning:()=>x.isRunning(),pause:k,resume:j},I={send:(e,t)=>F.sendMessage(e,t),on:(e,t)=>F.onMessage(e,t),timer:N,bootstrap:()=>n},R={};for(let n of(t=e.plugins)==null?[]:t)R[n.name]=n.setup(I);return{timer:N,plugins:R,gameReady:function(){var t=v(function*(){if(F.sendMessage(`READY`,{runtimeContract:P}),!n){var t;let n=(t=e.timeout)==null?5e3:t;yield new Promise((e,t)=>{r=e,setTimeout(()=>{r&&(r=null,t(Error(`Timeout waiting for READY_DATA after ${n}ms`)))},n)})}let i=c();return d(d({},{puzzleString:s(),inputString:i,theme:l(),completed:u(),readyData:n}),{},{boardState:i})});return function(){return t.apply(this,arguments)}}(),gameLoaded:(e={})=>{F.sendMessage(`READY_GAME_LOADED`,{state:e,gameRuntimeContract:P,embedRuntimeContract:`1.0`}),b(`READY_GAME_LOADED`)},on:(e,t)=>(m.has(e)||m.set(e,new Set),m.get(e).add(t),()=>{var n;(n=m.get(e))==null||n.delete(t)}),off:(e,t)=>{var n;(n=m.get(e))==null||n.delete(t)},updateGameState:(e,t)=>{var n,r;let i=o();if(!i)return p(`updateGameState`);F.sendMessage(`UPLOAD_NEW_GAME_STATE`,{id:i,input:{boardState:e,elapsedTimeSecs:(n=t==null?void 0:t.elapsedTimeSecs)==null?x.timeWithoutPenaltySecs():n,additionalTimeAddedSecs:(r=t==null?void 0:t.additionalTimeAddedSecs)==null?x.addedTimeSecs():r,collabUserReferences:[]}}),b(`UPLOAD_NEW_GAME_STATE`)},gameCompleted:(e,t)=>{var r,i,s,c,l;x._conclude(),D();let{inputString:u}=e,f=d(d({},a(e,A)),{},{boardState:u==null?e.boardState:u,elapsedTimeSecs:(r=e.elapsedTimeSecs)==null?x.timeWithoutPenaltySecs():r,additionalTimeAddedSecs:(i=e.additionalTimeAddedSecs)==null?x.addedTimeSecs():i}),m=(s=t==null?void 0:t.deeds)==null?[]:s;m.push({id:`points`,value:e.pointsAwarded}),m.push({id:`time`,value:Math.round((c=f.elapsedTimeSecs)==null?0:c)+Math.round((l=f.additionalTimeAddedSecs)==null?0:l)});let h=o(),g=n&&!n.session&&n.appRuntimeContract===`1.1`;h||g?(F.sendMessage(`GAME_COMPLETED`,{id:h==null?void 0:h,input:f,config:t}),b(`GAME_COMPLETED`,{input:f})):p(`gameCompleted`)},showCompletionScreen:e=>{F.sendMessage(`SHOW_GAME_COMPLETE_SCREEN`,{results:e,showRetry:!0})},hitCheckpoint:(e,t,n)=>{var r;if(!o())return p(`hitCheckpoint`);let i=(r=c())==null?``:r,a={elapsedTimeSecs:x.timeWithoutPenaltySecs(),additionalTimeAddedSecs:x.addedTimeSecs()};F.sendMessage(`HIT_CHECKPOINT`,{checkpointName:e,gameplay:{inputStr:i,play:a},checkpointConfig:t,augConfig:n==null?{}:n})},settings:{initialize:e=>(g=d(d({},L(e)),g),F.sendMessage(`INITIALIZE_SETTINGS`,{components:e,settings:g}),g),get:()=>{var e;return(e=g)==null?{}:e},update:e=>(g=d(d({},g),e),F.sendMessage(`UPDATE_SETTINGS_FROM_EMBED`,{settings:g}),g)},keyboard:{show:e=>{F.sendMessage(`KEYBOARD_UPDATE_CONFIG`,e)},hide:()=>{F.sendMessage(`KEYBOARD_UPDATE_CONFIG`,{layout:[],symbols:{},highlight:[],disabled:[],xl:[],l:[],supportsDragCursor:!1})}},haptics:{play:(e,t)=>{var n;F.sendMessage(`SENSORY_EVENT`,{id:(n=t==null?void 0:t.id)==null?e:n,haptic:e})}},_hostAPI:F}};function L(e){let t={};for(let n of e)n.type===`split`?Object.assign(t,L(n.content)):`name`in n&&(t[n.name]=n.defaultValue);return t}let R={layout:[`qwertyuiop`,`asdfghjkl`,`↵zxcvbnm⌫`,void 0],symbols:{"↵":`enter`,"⌫":`bsp`},highlight:[`↵`,`⌫`],disabled:[],xl:[],l:[`↵`,`⌫`],supportsDragCursor:!1},z=e=>{let t={};for(let i of e)for(let e of i.keys){var n,r;let a={},o=d(d({},(n=t[e])==null?void 0:n.text),i.text),s=d(d({},(r=t[e])==null?void 0:r.background),i.background);Object.keys(o).length&&(a.text=o),Object.keys(s).length&&(a.background=s),t[e]=a}return t};var B=class extends Error{constructor(e,t,n){super(t),this.type=e,this.originalError=n,this.name=`EditorImportError`}},V=n(((e,t)=>{var n=(function(){var e=String.fromCharCode,t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=`,n=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+-$`,r={};function i(e,t){if(!r[e]){r[e]={};for(var n=0;n<e.length;n++)r[e][e.charAt(n)]=n}return r[e][t]}var a={compressToBase64:function(e){if(e==null)return``;var n=a._compress(e,6,function(e){return t.charAt(e)});switch(n.length%4){default:case 0:return n;case 1:return n+`===`;case 2:return n+`==`;case 3:return n+`=`}},decompressFromBase64:function(e){return e==null?``:e==``?null:a._decompress(e.length,32,function(n){return i(t,e.charAt(n))})},compressToUTF16:function(t){return t==null?``:a._compress(t,15,function(t){return e(t+32)})+` `},decompressFromUTF16:function(e){return e==null?``:e==``?null:a._decompress(e.length,16384,function(t){return e.charCodeAt(t)-32})},compressToUint8Array:function(e){for(var t=a.compress(e),n=new Uint8Array(t.length*2),r=0,i=t.length;r<i;r++){var o=t.charCodeAt(r);n[r*2]=o>>>8,n[r*2+1]=o%256}return n},decompressFromUint8Array:function(t){if(t==null)return a.decompress(t);for(var n=Array(t.length/2),r=0,i=n.length;r<i;r++)n[r]=t[r*2]*256+t[r*2+1];var o=[];return n.forEach(function(t){o.push(e(t))}),a.decompress(o.join(``))},compressToEncodedURIComponent:function(e){return e==null?``:a._compress(e,6,function(e){return n.charAt(e)})},decompressFromEncodedURIComponent:function(e){return e==null?``:e==``?null:(e=e.replace(/ /g,`+`),a._decompress(e.length,32,function(t){return i(n,e.charAt(t))}))},compress:function(t){return a._compress(t,16,function(t){return e(t)})},_compress:function(e,t,n){if(e==null)return``;var r,i,a={},o={},s=``,c=``,l=``,u=2,d=3,f=2,p=[],m=0,h=0,g;for(g=0;g<e.length;g+=1)if(s=e.charAt(g),Object.prototype.hasOwnProperty.call(a,s)||(a[s]=d++,o[s]=!0),c=l+s,Object.prototype.hasOwnProperty.call(a,c))l=c;else{if(Object.prototype.hasOwnProperty.call(o,l)){if(l.charCodeAt(0)<256){for(r=0;r<f;r++)m<<=1,h==t-1?(h=0,p.push(n(m)),m=0):h++;for(i=l.charCodeAt(0),r=0;r<8;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1}else{for(i=1,r=0;r<f;r++)m=m<<1|i,h==t-1?(h=0,p.push(n(m)),m=0):h++,i=0;for(i=l.charCodeAt(0),r=0;r<16;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1}u--,u==0&&(u=Math.pow(2,f),f++),delete o[l]}else for(i=a[l],r=0;r<f;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1;u--,u==0&&(u=Math.pow(2,f),f++),a[c]=d++,l=String(s)}if(l!==``){if(Object.prototype.hasOwnProperty.call(o,l)){if(l.charCodeAt(0)<256){for(r=0;r<f;r++)m<<=1,h==t-1?(h=0,p.push(n(m)),m=0):h++;for(i=l.charCodeAt(0),r=0;r<8;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1}else{for(i=1,r=0;r<f;r++)m=m<<1|i,h==t-1?(h=0,p.push(n(m)),m=0):h++,i=0;for(i=l.charCodeAt(0),r=0;r<16;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1}u--,u==0&&(u=Math.pow(2,f),f++),delete o[l]}else for(i=a[l],r=0;r<f;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1;u--,u==0&&(u=Math.pow(2,f),f++)}for(i=2,r=0;r<f;r++)m=m<<1|i&1,h==t-1?(h=0,p.push(n(m)),m=0):h++,i>>=1;for(;;)if(m<<=1,h==t-1){p.push(n(m));break}else h++;return p.join(``)},decompress:function(e){return e==null?``:e==``?null:a._decompress(e.length,32768,function(t){return e.charCodeAt(t)})},_decompress:function(t,n,r){var i=[],a=4,o=4,s=3,c=``,l=[],u,d,f,p,m,h,g,_={val:r(0),position:n,index:1};for(u=0;u<3;u+=1)i[u]=u;for(f=0,m=Math.pow(2,2),h=1;h!=m;)p=_.val&_.position,_.position>>=1,_.position==0&&(_.position=n,_.val=r(_.index++)),f|=(p>0?1:0)*h,h<<=1;switch(f){case 0:for(f=0,m=Math.pow(2,8),h=1;h!=m;)p=_.val&_.position,_.position>>=1,_.position==0&&(_.position=n,_.val=r(_.index++)),f|=(p>0?1:0)*h,h<<=1;g=e(f);break;case 1:for(f=0,m=Math.pow(2,16),h=1;h!=m;)p=_.val&_.position,_.position>>=1,_.position==0&&(_.position=n,_.val=r(_.index++)),f|=(p>0?1:0)*h,h<<=1;g=e(f);break;case 2:return``}for(i[3]=g,d=g,l.push(g);;){if(_.index>t)return``;for(f=0,m=Math.pow(2,s),h=1;h!=m;)p=_.val&_.position,_.position>>=1,_.position==0&&(_.position=n,_.val=r(_.index++)),f|=(p>0?1:0)*h,h<<=1;switch(g=f){case 0:for(f=0,m=Math.pow(2,8),h=1;h!=m;)p=_.val&_.position,_.position>>=1,_.position==0&&(_.position=n,_.val=r(_.index++)),f|=(p>0?1:0)*h,h<<=1;i[o++]=e(f),g=o-1,a--;break;case 1:for(f=0,m=Math.pow(2,16),h=1;h!=m;)p=_.val&_.position,_.position>>=1,_.position==0&&(_.position=n,_.val=r(_.index++)),f|=(p>0?1:0)*h,h<<=1;i[o++]=e(f),g=o-1,a--;break;case 2:return l.join(``)}if(a==0&&(a=Math.pow(2,s),s++),i[g])c=i[g];else if(g===o)c=d+d.charAt(0);else return null;l.push(c),i[o++]=d+c.charAt(0),a--,d=c,a==0&&(a=Math.pow(2,s),s++)}}};return a})();typeof define==`function`&&define.amd?define(function(){return n}):t!==void 0&&t!=null?t.exports=n:typeof angular<`u`&&angular!=null&&angular.module(`LZString`,[]).factory(`LZString`,function(){return n})}))();function H(e){if(e.length===0)return`0`;let t=``;for(let n=0;n<e.length;n+=4){let r=0;for(let t=0;t<4&&n+t<e.length;t++)e[n+t]&&(r|=1<<t);t+=r.toString(16)}return t||`0`}function U(e,t){let n=[];for(let r=0;r<t;r++){let t=Math.floor(r/4),i=r%4,a=parseInt(e[t]||`0`,16);n.push((a&1<<i)!=0)}return n}function W(e){if(e.length===0)return``;let t=e.map((e,t)=>({val:e,idx:t})).filter(e=>e.val!==0);return t.length===0?``:t.length>e.length/2?e.join(`,`):t.map(e=>`${e.idx}=${e.val}`).join(`,`)}function G(e,t){if(!e)return t?Array.from({length:t},()=>0):[];if(e.includes(`=`)){let n=t?Array.from({length:t},()=>0):[],r=e.split(`,`);for(let e of r){let[t,r]=e.split(`=`),i=Number(t),a=Number(r);!isNaN(i)&&!isNaN(a)&&(n[i]=a)}return n}return e.split(`,`).map(e=>Number(e))}function K(e,t=`,`){return e.join(t)}function q(e,t=`,`){return e?e.split(t):[]}function J(e){return(0,V.compressToEncodedURIComponent)(JSON.stringify(e))}function Y(e){if(!e)return;let t=(0,V.decompressFromEncodedURIComponent)(e);return t?JSON.parse(t):void 0}function X(e,t,n){let r=Object.entries(e).filter(([e,t])=>t!=null);return n?r.map(([e,r])=>{let i=n.indexOf(e);return i===-1?null:`${i}=${t(r)}`}).filter(e=>e!==null).join(`,`):r.map(([e,n])=>`${e}=${t(n)}`).join(`;`)}function Z(e,t,n){if(!e)return{};let r={};if(n){let i=e.split(`,`);for(let e of i){if(!e)continue;let[i,a]=e.split(`=`),o=Number(i);!isNaN(o)&&a&&n[o]&&(r[n[o]]=t(a))}}else{let n=e.split(`;`);for(let e of n){if(!e)continue;let[n,i]=e.split(`=`);n&&i&&(r[n]=t(i))}}return r}function ee(e,t,n){switch(t.type){case`bitArray`:return H(e);case`intArray`:return W(e);case`int`:return String(e);case`string`:return String(e);case`stringArray`:return K(e,t.delimiter);case`sparseMap`:return X(e,t.valueEncoder,n==null?void 0:n.keys);case`json`:return J(e);default:throw Error(`Unknown field type: ${t.type}`)}}function Q(e,t,n){let r=e.delimiter||`:`,i=Object.keys(e.fields).map(r=>{let i=e.fields[r],a=t[r];return ee(a,i,n==null?void 0:n[r])});return`v${e.version}${r}${i.join(r)}`}function te(e,t,n){switch(t.type){case`bitArray`:if(!(n!=null&&n.length))throw Error(`bitArray requires length in context`);return U(e,n.length);case`intArray`:return G(e,n==null?void 0:n.length);case`int`:return Number(e);case`string`:return e;case`stringArray`:return q(e,t.delimiter);case`sparseMap`:return Z(e,t.valueDecoder,n==null?void 0:n.keys);case`json`:return Y(e);default:throw Error(`Unknown field type: ${t.type}`)}}function $(e,t,n){let r=e.delimiter||`:`,i=t.split(r),a=i[0],o=a.match(/^v(\d+)$/);if(!o)throw Error(`Invalid input string format: ${a}`);let s=Number(o[1]);if(s!==e.version)throw Error(`Version mismatch: expected v${e.version}, got v${s}. Make sure to run migrations first.`);let c=Object.keys(e.fields),l={};for(let t=0;t<c.length;t++){let r=c[t],a=e.fields[r];l[r]=te(i[t+1]||``,a,n==null?void 0:n[r])}return l}function ne(e){return function(t,n){let r=t.match(/^v(\d+)/);if(!r)throw Error(`Invalid input string: no version found`);let i=Number(r[1]);if(i===e.version)return t;if(!e.migrations)throw Error(`No migrations defined for schema. Cannot migrate from v${i} to v${e.version}`);let a=$(d(d({},e),{},{version:i}),t,n);for(let t=i;t<e.version;t++){let n=e.migrations[t];n&&(a=n(a))}return Q(e,a,n)}}function re(e){return e}var ie=r({createEncoder:()=>ae,defineSchema:()=>re});function ae(e,t){let n=ne(e);return{encode:n=>Q(e,n,t),decode:n=>$(e,n,t),migrate:e=>n(e,t)}}return e.EditorImportError=B,e.createPuzzmoSDK=I,e.defaultKeyboardConfig=R,Object.defineProperty(e,`inputs`,{enumerable:!0,get:function(){return ie}}),e.keyStylesFromRules=z,e})({});
|
|
2
2
|
//# sourceMappingURL=index.global.js.map
|