@astl/astrolabe 0.0.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (188) hide show
  1. package/CHANGELOG.md +134 -0
  2. package/LICENSE +202 -0
  3. package/README.md +65 -0
  4. package/dist/cdn/astrolabe-editor.js +1441 -0
  5. package/dist/cdn/astrolabe-editor.js.map +1 -0
  6. package/dist/cdn/astrolabe-player.js +2 -0
  7. package/dist/cdn/astrolabe-player.js.map +1 -0
  8. package/dist/cdn/astrolabe.css +238 -0
  9. package/dist/cdn/astrolabe.js +3 -0
  10. package/dist/cdn/astrolabe.js.map +1 -0
  11. package/dist/cdn/astrolabe.standalone.js +8007 -0
  12. package/dist/cdn/chunks/audio-B0LSIn5N.js +48 -0
  13. package/dist/cdn/chunks/audio-B0LSIn5N.js.map +1 -0
  14. package/dist/cdn/chunks/audio-manifest-B9FWQzRy.js +2 -0
  15. package/dist/cdn/chunks/audio-manifest-B9FWQzRy.js.map +1 -0
  16. package/dist/cdn/chunks/block-styles-CKo9x7Vt.js +68 -0
  17. package/dist/cdn/chunks/block-styles-CKo9x7Vt.js.map +1 -0
  18. package/dist/cdn/chunks/book-CHzDDaim.js +15 -0
  19. package/dist/cdn/chunks/book-CHzDDaim.js.map +1 -0
  20. package/dist/cdn/chunks/callout-QFLFLPc5.js +49 -0
  21. package/dist/cdn/chunks/callout-QFLFLPc5.js.map +1 -0
  22. package/dist/cdn/chunks/callout-manifest-Cb12O4jl.js +2 -0
  23. package/dist/cdn/chunks/callout-manifest-Cb12O4jl.js.map +1 -0
  24. package/dist/cdn/chunks/categorise-BO2tNVJ3.js +203 -0
  25. package/dist/cdn/chunks/categorise-BO2tNVJ3.js.map +1 -0
  26. package/dist/cdn/chunks/categorise-manifest-C_hEDVYQ.js +2 -0
  27. package/dist/cdn/chunks/categorise-manifest-C_hEDVYQ.js.map +1 -0
  28. package/dist/cdn/chunks/chip-styles-Dme5daTO.js +77 -0
  29. package/dist/cdn/chunks/chip-styles-Dme5daTO.js.map +1 -0
  30. package/dist/cdn/chunks/choice-CExBvqKj.js +136 -0
  31. package/dist/cdn/chunks/choice-CExBvqKj.js.map +1 -0
  32. package/dist/cdn/chunks/choice-manifest-C-XahD7m.js +2 -0
  33. package/dist/cdn/chunks/choice-manifest-C-XahD7m.js.map +1 -0
  34. package/dist/cdn/chunks/color-control-Cl5cuMSO.js +91 -0
  35. package/dist/cdn/chunks/color-control-Cl5cuMSO.js.map +1 -0
  36. package/dist/cdn/chunks/crossword-Cb-a3Tjj.js +270 -0
  37. package/dist/cdn/chunks/crossword-Cb-a3Tjj.js.map +1 -0
  38. package/dist/cdn/chunks/crossword-manifest-2qlu7AYd.js +2 -0
  39. package/dist/cdn/chunks/crossword-manifest-2qlu7AYd.js.map +1 -0
  40. package/dist/cdn/chunks/declarations-BhqOz1ap.js +2 -0
  41. package/dist/cdn/chunks/declarations-BhqOz1ap.js.map +1 -0
  42. package/dist/cdn/chunks/definitions-CNX90WtL.js +6 -0
  43. package/dist/cdn/chunks/definitions-CNX90WtL.js.map +1 -0
  44. package/dist/cdn/chunks/directive-helpers-D7lOZKnB.js +14 -0
  45. package/dist/cdn/chunks/directive-helpers-D7lOZKnB.js.map +1 -0
  46. package/dist/cdn/chunks/drop-manifest-bzNOa5ks.js +2 -0
  47. package/dist/cdn/chunks/drop-manifest-bzNOa5ks.js.map +1 -0
  48. package/dist/cdn/chunks/drop-vRXndjHu.js +86 -0
  49. package/dist/cdn/chunks/drop-vRXndjHu.js.map +1 -0
  50. package/dist/cdn/chunks/flash-cards-0NrrKdrx.js +87 -0
  51. package/dist/cdn/chunks/flash-cards-0NrrKdrx.js.map +1 -0
  52. package/dist/cdn/chunks/flash-cards-manifest-B8nWXbRy.js +2 -0
  53. package/dist/cdn/chunks/flash-cards-manifest-B8nWXbRy.js.map +1 -0
  54. package/dist/cdn/chunks/gap-lor-khst.js +78 -0
  55. package/dist/cdn/chunks/gap-lor-khst.js.map +1 -0
  56. package/dist/cdn/chunks/gap-manifest-RSydA41N.js +2 -0
  57. package/dist/cdn/chunks/gap-manifest-RSydA41N.js.map +1 -0
  58. package/dist/cdn/chunks/help-C-woafz5.js +138 -0
  59. package/dist/cdn/chunks/help-C-woafz5.js.map +1 -0
  60. package/dist/cdn/chunks/help-form-DaC6KaFG.js +160 -0
  61. package/dist/cdn/chunks/help-form-DaC6KaFG.js.map +1 -0
  62. package/dist/cdn/chunks/hotspot-manifest-CNs1oiZ_.js +2 -0
  63. package/dist/cdn/chunks/hotspot-manifest-CNs1oiZ_.js.map +1 -0
  64. package/dist/cdn/chunks/hotspot-oel1Eelo.js +154 -0
  65. package/dist/cdn/chunks/hotspot-oel1Eelo.js.map +1 -0
  66. package/dist/cdn/chunks/image-drop-Dkprw0Kn.js +295 -0
  67. package/dist/cdn/chunks/image-drop-Dkprw0Kn.js.map +1 -0
  68. package/dist/cdn/chunks/image-drop-manifest-BZ6hCoAd.js +2 -0
  69. package/dist/cdn/chunks/image-drop-manifest-BZ6hCoAd.js.map +1 -0
  70. package/dist/cdn/chunks/image-label-Dm5shQSh.js +177 -0
  71. package/dist/cdn/chunks/image-label-Dm5shQSh.js.map +1 -0
  72. package/dist/cdn/chunks/image-label-manifest--1CLRJzd.js +2 -0
  73. package/dist/cdn/chunks/image-label-manifest--1CLRJzd.js.map +1 -0
  74. package/dist/cdn/chunks/inline-styles-CTgXWnHb.js +80 -0
  75. package/dist/cdn/chunks/inline-styles-CTgXWnHb.js.map +1 -0
  76. package/dist/cdn/chunks/insert-menu-LgrifBYT.js +80 -0
  77. package/dist/cdn/chunks/insert-menu-LgrifBYT.js.map +1 -0
  78. package/dist/cdn/chunks/issue-list-BgnXzXRM.js +51 -0
  79. package/dist/cdn/chunks/issue-list-BgnXzXRM.js.map +1 -0
  80. package/dist/cdn/chunks/keys-DU-Qknmz.js +2 -0
  81. package/dist/cdn/chunks/keys-DU-Qknmz.js.map +1 -0
  82. package/dist/cdn/chunks/live-jdiyYln2.js +7 -0
  83. package/dist/cdn/chunks/live-jdiyYln2.js.map +1 -0
  84. package/dist/cdn/chunks/long-answer-CtzClLAx.js +71 -0
  85. package/dist/cdn/chunks/long-answer-CtzClLAx.js.map +1 -0
  86. package/dist/cdn/chunks/long-answer-manifest-BYJpZRtB.js +2 -0
  87. package/dist/cdn/chunks/long-answer-manifest-BYJpZRtB.js.map +1 -0
  88. package/dist/cdn/chunks/mark-words-CpH3gTcX.js +131 -0
  89. package/dist/cdn/chunks/mark-words-CpH3gTcX.js.map +1 -0
  90. package/dist/cdn/chunks/mark-words-manifest-Cs2pXCEx.js +2 -0
  91. package/dist/cdn/chunks/mark-words-manifest-Cs2pXCEx.js.map +1 -0
  92. package/dist/cdn/chunks/match-DKE_4o-x.js +352 -0
  93. package/dist/cdn/chunks/match-DKE_4o-x.js.map +1 -0
  94. package/dist/cdn/chunks/match-manifest-D0UfoajU.js +2 -0
  95. package/dist/cdn/chunks/match-manifest-D0UfoajU.js.map +1 -0
  96. package/dist/cdn/chunks/memory-B6hSyHyz.js +187 -0
  97. package/dist/cdn/chunks/memory-B6hSyHyz.js.map +1 -0
  98. package/dist/cdn/chunks/memory-manifest-D1589iR0.js +2 -0
  99. package/dist/cdn/chunks/memory-manifest-D1589iR0.js.map +1 -0
  100. package/dist/cdn/chunks/menu-messages-Dx3jYUEp.js +2 -0
  101. package/dist/cdn/chunks/menu-messages-Dx3jYUEp.js.map +1 -0
  102. package/dist/cdn/chunks/messages-9xiYDvRT.js +2 -0
  103. package/dist/cdn/chunks/messages-9xiYDvRT.js.map +1 -0
  104. package/dist/cdn/chunks/option-styles-WKzjKmCH.js +50 -0
  105. package/dist/cdn/chunks/option-styles-WKzjKmCH.js.map +1 -0
  106. package/dist/cdn/chunks/order-BhG_6IC-.js +225 -0
  107. package/dist/cdn/chunks/order-BhG_6IC-.js.map +1 -0
  108. package/dist/cdn/chunks/order-manifest-J5IXN0he.js +2 -0
  109. package/dist/cdn/chunks/order-manifest-J5IXN0he.js.map +1 -0
  110. package/dist/cdn/chunks/pick-and-place-DVQIPYuL.js +2 -0
  111. package/dist/cdn/chunks/pick-and-place-DVQIPYuL.js.map +1 -0
  112. package/dist/cdn/chunks/picture-D10YRMYH.js +2 -0
  113. package/dist/cdn/chunks/picture-D10YRMYH.js.map +1 -0
  114. package/dist/cdn/chunks/picture-view-BKnAyScQ.js +92 -0
  115. package/dist/cdn/chunks/picture-view-BKnAyScQ.js.map +1 -0
  116. package/dist/cdn/chunks/repeat-CY2W2URZ.js +8 -0
  117. package/dist/cdn/chunks/repeat-CY2W2URZ.js.map +1 -0
  118. package/dist/cdn/chunks/roving-focus-BxGgi2DD.js +2 -0
  119. package/dist/cdn/chunks/roving-focus-BxGgi2DD.js.map +1 -0
  120. package/dist/cdn/chunks/runtime-DxAbpr3S.js +526 -0
  121. package/dist/cdn/chunks/runtime-DxAbpr3S.js.map +1 -0
  122. package/dist/cdn/chunks/scan-jWgPnVxA.js +2 -0
  123. package/dist/cdn/chunks/scan-jWgPnVxA.js.map +1 -0
  124. package/dist/cdn/chunks/select-DTA3dJzr.js +345 -0
  125. package/dist/cdn/chunks/select-DTA3dJzr.js.map +1 -0
  126. package/dist/cdn/chunks/select-manifest-BBMbvdkH.js +2 -0
  127. package/dist/cdn/chunks/select-manifest-BBMbvdkH.js.map +1 -0
  128. package/dist/cdn/chunks/source-view-DXKPFCl9.js +29 -0
  129. package/dist/cdn/chunks/source-view-DXKPFCl9.js.map +1 -0
  130. package/dist/cdn/chunks/style-form-D5haJtWM.js +240 -0
  131. package/dist/cdn/chunks/style-form-D5haJtWM.js.map +1 -0
  132. package/dist/cdn/chunks/style-messages-BbZpeD2a.js +2 -0
  133. package/dist/cdn/chunks/style-messages-BbZpeD2a.js.map +1 -0
  134. package/dist/cdn/chunks/style-model-ZXNe_c8R.js +2 -0
  135. package/dist/cdn/chunks/style-model-ZXNe_c8R.js.map +1 -0
  136. package/dist/cdn/chunks/style-placing-DPw1zyrz.js +2 -0
  137. package/dist/cdn/chunks/style-placing-DPw1zyrz.js.map +1 -0
  138. package/dist/cdn/chunks/style-popups-BobgX1WK.js +74 -0
  139. package/dist/cdn/chunks/style-popups-BobgX1WK.js.map +1 -0
  140. package/dist/cdn/chunks/style-rules-D45PZLCv.js +136 -0
  141. package/dist/cdn/chunks/style-rules-D45PZLCv.js.map +1 -0
  142. package/dist/cdn/chunks/styled-Dmx5Yjv7.js +57 -0
  143. package/dist/cdn/chunks/styled-Dmx5Yjv7.js.map +1 -0
  144. package/dist/cdn/chunks/styles-DxJJxVNH.js +136 -0
  145. package/dist/cdn/chunks/styles-DxJJxVNH.js.map +1 -0
  146. package/dist/cdn/chunks/surface-CgxfAwCR.js +1019 -0
  147. package/dist/cdn/chunks/surface-CgxfAwCR.js.map +1 -0
  148. package/dist/cdn/chunks/true-false-DP3MO599.js +146 -0
  149. package/dist/cdn/chunks/true-false-DP3MO599.js.map +1 -0
  150. package/dist/cdn/chunks/true-false-manifest-B4exv60u.js +2 -0
  151. package/dist/cdn/chunks/true-false-manifest-B4exv60u.js.map +1 -0
  152. package/dist/cdn/chunks/video-j9MCH6Kw.js +98 -0
  153. package/dist/cdn/chunks/video-j9MCH6Kw.js.map +1 -0
  154. package/dist/cdn/chunks/video-manifest-8OwkhhAI.js +2 -0
  155. package/dist/cdn/chunks/video-manifest-8OwkhhAI.js.map +1 -0
  156. package/dist/cdn/chunks/word-bank-ARjwUKZf.js +80 -0
  157. package/dist/cdn/chunks/word-bank-ARjwUKZf.js.map +1 -0
  158. package/dist/cdn/chunks/word-bank-manifest-C1FSo1kH.js +2 -0
  159. package/dist/cdn/chunks/word-bank-manifest-C1FSo1kH.js.map +1 -0
  160. package/dist/cdn/chunks/word-search-AHvM7yCJ.js +274 -0
  161. package/dist/cdn/chunks/word-search-AHvM7yCJ.js.map +1 -0
  162. package/dist/cdn/chunks/word-search-manifest-Fg1a59Z1.js +2 -0
  163. package/dist/cdn/chunks/word-search-manifest-Fg1a59Z1.js.map +1 -0
  164. package/dist/editor.d.ts +32 -0
  165. package/dist/editor.d.ts.map +1 -0
  166. package/dist/editor.js +51 -0
  167. package/dist/editor.js.map +1 -0
  168. package/dist/engine.d.ts +33 -0
  169. package/dist/engine.d.ts.map +1 -0
  170. package/dist/engine.js +53 -0
  171. package/dist/engine.js.map +1 -0
  172. package/dist/player.d.ts +19 -0
  173. package/dist/player.d.ts.map +1 -0
  174. package/dist/player.js +22 -0
  175. package/dist/player.js.map +1 -0
  176. package/dist/server.d.ts +8 -0
  177. package/dist/server.d.ts.map +1 -0
  178. package/dist/server.js +8 -0
  179. package/dist/server.js.map +1 -0
  180. package/package.json +82 -4
  181. package/src/bundles/astrolabe-editor.ts +11 -0
  182. package/src/bundles/astrolabe-player.ts +10 -0
  183. package/src/bundles/astrolabe-standalone.ts +23 -0
  184. package/src/bundles/astrolabe.ts +12 -0
  185. package/src/editor.ts +98 -0
  186. package/src/engine.ts +59 -0
  187. package/src/player.ts +23 -0
  188. package/src/server.ts +7 -0
@@ -0,0 +1 @@
1
+ {"version":3,"file":"runtime-DxAbpr3S.js","names":["palette","en","pl","rule","t","e","s","o","n","r","i","S","c","i","e","h","r","o","n","a","c","l","p","d","u","f","b","y","t","s","i","s","o","t","e","r","o","t","ifDefined","loading","unsupported","en","pl","unsafeCSS","nothing","LitElement","supportsAdoptingStyleSheets","definePlayer","LitElement","nothing","MAX_ANSWER_LENGTH","OPEN_SLOT_KIND","MAX_OPEN_ANSWER_LENGTH","MAX_ANSWER_COUNT","FLAG_SELECTED","maxAnswerLength","kind","fitsAnswer","max","value","count","_","isAnswers","entries","k","v","element","text","isElement","node","tag","textContent","out","child","childElements","c","CheckerError","problem","KEY_FORMAT_VERSION","isAnswerKey","BLOCK_TAGS","INLINE_TAGS","FIGURE_TAG","CAPTION_TAG","REMOVED_WITH_CONTENT","CONTENT_ATTRIBUTES","CLASS_ATTRIBUTE","INERT_STYLE","START_TAG","STYLE_IN_TAG","inertStyles","html","space","found","STYLE_TAG","COLUMNS_TAG","COLUMN_TAG","MIN_COLUMNS","MAX_COLUMNS","TAG_ATTRIBUTES","URL_ATTRIBUTES","DOC_ATTRIBUTES","DOC_KINDS","DEFAULT_DOC_KIND","PAGE_ATTRIBUTES","MAX_ATTRIBUTES_PER_ELEMENT","MAX_NESTING_DEPTH","SAFE_SCHEMES","isSafeUrl","scheme","url","strictUrlPolicy","policy","context","FORMAT_VERSION","SUPPORTED_FORMATS","DOC_TAG","PAGE_TAG","MAX_SOURCE_LENGTH","SOURCE_ID_PATTERN","OPAQUE_ID_PATTERN","ELEMENT_TAG_PATTERN","BUILT_IN_PREFIX","isSourceId","isOpaqueId","RTL_LANGUAGES","directionOf","parts","lang","LANGUAGE_TAG_PATTERN","HINT_TAG","EXPLANATION_TAG","FEEDBACK_TAG","HELP_TAGS","FEEDBACK_VARIANTS","HELP_ATTRIBUTES","MessageSyntaxError","message","offset","PLURAL_KEYWORDS","Parser","src","buf","flush","ch","inPlural","next","start","name","style","s","n","options","key","m","parseMessage","messageParams","names","walk","p","list","sub","option","render","pound","params","formatNumber","locale","branch","exact","category","pluralRules","pluralCache","id","ordinal","rules","pluralCategories","parsedCache","icuFormatter","pluralProblems","missing","checkCatalog","problems","catalog","detail","compareCatalogs","translation","source","other","want","got","negotiateLocale","byLower","available","a","requested","hit","sameLanguage","fallback","chain","createI18n","fallbackLocale","formatter","table","byLocale","entry","t","namespace","ns","catalogs","ENGINE_NAMESPACE","EngineIssue","hasErrors","issues","i","STYLE_TEMPLATE_ATTRIBUTE","STYLE_TEMPLATE_NAME","SCOPES","isRecord","isStrings","isStyleTemplate","version","scopes","scope","components","messages","tokens","light","dark","byTag","COMMON_ATTRIBUTES","SCORING_ATTRIBUTES","variantAttribute","variants","allAttributes","scoring","manifest","variant","canonical","b","sameChildSpec","attributes","spec","x","y","childTagConflict","first","manifests","seen","PlayerEvent","PRACTICE_POLICY","TEST_POLICY","helpPolicy","base","practice","isMoment","isAttemptPolicy","PROTOCOL_VERSION","JSON_MEDIA_TYPE","PROBLEM_MEDIA_TYPE","ProtocolPath","ProblemCode","MAX_REQUEST_BYTES","isProblemDetails","roundScore","SCORING_RULES","groupMax","rule","points","slotCount","DEFAULT_PROFILE","SNAPSHOT_FORMAT","isSnapshot","en_default$1","pl_default$1","PALETTE","PALETTE_COLORS","palette$1","lightSoft","darkSoft","hc","main","soft","theme","color","systemStack","palette","colors","of","ROUNDED","ROUNDED_BOLD","BOOK","PROMPTS","builtInStyleTemplates","withAttribute","selector","attribute","host","declarations","values","rule$1","body","tokensCss","themed","any","PART_PROPERTIES","isSafeStyleValue","open","quote","builtInElements","t$1","e$2","s$2","o$4","n$2","o","e","r$2","i$3","S$1","c$2","i$2","e$1","h$1","r$1","o$3","n$1","a$1","c$1","l$1","p$1","d$1","u$1","f$1","b$1","y$1","h","r","i$1","s$1","o$2","l","u","d","f","g","$","w","E","A","C","P","V","N","S","I","L","z","H","M","R","Z","j","B","D","\"finalized\"","o$1","visuallyHidden","verdictStyles","ICONS","verdictIcon","verdict","renderVerdict","pending","announce","region","documentLiveRegion","refusal","code","asCheckerError","error","AttemptController","#now","#slots","snapshot","#restorable","#answers","#page","#checks","#checksLeft","#state","viewHash","#result","#solution","#response","index","#listeners","listener","#setState","changed","partial","#emit","previous","#check","page","#pendingCheck","refused","#checkRefusal","run","#runCheck","#pendingSubmit","#runSubmit","answers","response","state","change","STATUS_CODES","parseJson","helpOf","object","feedback","explanations","httpChecker","send","input","init","post","path","data","isProblem","request","en_default","pl_default","PLAYER_NAMESPACE","playerMessages","elementTranslator","own","i18n","isLazyElement","runtime","loadElement","loaded","registration","existing","loadElements","tags","playerStyles","DOCUMENT_TEMPLATE_ATTRIBUTE","NAME","TAG","NOT_HC","tokenLines","partLines","property","selectors","templateRules","at","condition","target","query","template","byPart","part","styleTemplatesCss","valid","templates","document","component","docAttribute","noDocumentTemplate","defaults","documents","root","allowed","owner","layer","sheet","built","styleTemplateSheet","refreshStyleTemplateSheet","LoadError","sha256Hex","subtle","digest","isView","doc","el","UNKNOWN_ATTRIBUTES","NONE","POSITIVE_INTEGER","keepAttributes","blocked","urls","cleanPicture","cleanFigure","cleaning","cleanContent","inline","parent","publicChild","urlPolicy","cleanChild","cleanComponent","keepPublic","kept","specs","extra","readView","view","roots","viewTags","fragment","hasHelp","isBook","isStyled","cleanView","STORAGE_PREFIX","SNAPSHOT_DELAY_MS","VERDICTS","TIMER_ALERTS","THEMES","PROGRESS_ICONS","pick","ids","codeOf","clock","seconds","ms","pad","AstlPlayer","#requireChecker","#viewHash","#controller","#loadView","controller","#problem","#effectiveChecker","#showProblem","#confirming","#query","#step","accepted","touched","#mounted","shown","#uiState","#syncClock","#resize","#autoload","#flushSnapshot","event","#theme","#source","#loadSrc","policyChanged","localeChanged","#mountedLocale","#uiLocale","#sourceChecker","#i18n","#documentTemplate","#spread","#loadError","#errorMessage","#loadDetails","#renderHeader","#renderResult","#renderFooter","pages","left","#counter","#renderSegment","last","#shown","#pageState","current","label","result","passed","scored","#scored","teacher","#teacherText","#scoreText","#openAnswers","slots","answered","actions","#renderActions","linear","#cancelConfirm","#emptyCount","#onSubmit","resolve","#generation","#loadLightDom","generation","#begin","compile","#fail","copy","compiled","details","actual","sourceChecker","#mount","#unsubscribe","#help","#pages","#doc","#book","#headings","#alerted","#autoSubmitted","styling","helping","booking","styled","styles","content","#collect","note","headings","heading","generated","mounted","#announce","canvas","candidate","snapshotOverride","#storedSnapshot","#checkerProxy","ui","#onChange","help","book","#setSpread","spread","#showPage","ready","#dispatch","notice","#scheduleSnapshot","#applyResult","#removeStored","checked","solution","groups","only","group","named","#resultAnnouncement","from","focus","direction","#snapshotTimer","#emitSnapshot","#store","#storageKey","raw","empty","running","#clock","#tick","due","minutes","#endpointChecker","checker","units","total","#i18nCache","type","PLAYER_TAG","definePlayer$1","registry","classes","claim","taken","eager","lazy","known","load","defaultContext","hash","random","seed","seededShuffle","items","AstlElement","#assignSlots","#context","children","slot","SingleSlotElement","definePlayer"],"sources":["../../../../core/src/answers.ts","../../../../core/src/ast.ts","../../../../core/src/checker.ts","../../../../core/src/compiled.ts","../../../../core/src/content.ts","../../../../core/src/format.ts","../../../../core/src/help.ts","../../../../core/src/i18n/format.ts","../../../../core/src/i18n/check.ts","../../../../core/src/i18n/i18n.ts","../../../../core/src/issues.ts","../../../../core/src/style.ts","../../../../core/src/manifest.ts","../../../../core/src/player.ts","../../../../core/src/policy.ts","../../../../core/src/protocol.ts","../../../../core/src/result.ts","../../../../core/src/scoring.ts","../../../../core/src/slots.ts","../../../../core/src/snapshot.ts","../../../../tokens/src/messages/en.json","../../../../tokens/src/messages/pl.json","../../../../tokens/src/tokens.ts","../../../../tokens/src/built-in-templates.ts","../../../../tokens/src/css.ts","../../../../tokens/src/templates.ts","../../../../components/src/elements.ts","../../../../../node_modules/.pnpm/@lit+reactive-element@2.1.2/node_modules/@lit/reactive-element/css-tag.js","../../../../../node_modules/.pnpm/@lit+reactive-element@2.1.2/node_modules/@lit/reactive-element/reactive-element.js","../../../../../node_modules/.pnpm/lit-html@3.3.3/node_modules/lit-html/lit-html.js","../../../../../node_modules/.pnpm/lit-element@4.2.2/node_modules/lit-element/lit-element.js","../../../../../node_modules/.pnpm/lit-html@3.3.3/node_modules/lit-html/directives/if-defined.js","../../../../player/src/a11y.ts","../../../../player/src/attempt/controller.ts","../../../../player/src/checker/http.ts","../../../../player/src/messages/en.json","../../../../player/src/messages/pl.json","../../../../player/src/messages.ts","../../../../player/src/runtime.ts","../../../../player/src/player/styles.ts","../../../../player/src/player/templates.ts","../../../../player/src/player/view.ts","../../../../player/src/player/player.ts","../../../../player/src/define.ts","../../../../player/src/element/base.ts","../../../src/player.ts"],"sourcesContent":["/**\n * Answers on the wire. Strings only, so any backend in any language can store and grade them.\n * - A missing key or `''` means unanswered.\n * - Text and number slots: what the student typed.\n * - Choice slots: the picked value, an opaque option id or a fixed public value (`true` / `false` of a statement).\n * - Flag slots (selection): `'true'` when selected.\n * - Open slots: what the student wrote, kept for a teacher.\n */\nexport type SlotId = string;\n\nexport type Answers = Readonly<Record<SlotId, string>>;\n\n/**\n * Longest accepted answer per slot, in Unicode code points, for every slot kind but `open`. Longer values count as\n * unanswered (engine, servers, protocol 1).\n */\nexport const MAX_ANSWER_LENGTH = 500;\n\n/** The built-in slot kind of open answers: stored with the attempt for a teacher, never graded. */\nexport const OPEN_SLOT_KIND = 'open';\n\n/** Longest open answer, in Unicode code points (so Polish and English letters count one each). */\nexport const MAX_OPEN_ANSWER_LENGTH = 2000;\n\n/** Most slots one request may carry. */\nexport const MAX_ANSWER_COUNT = 2000;\n\nexport const FLAG_SELECTED = 'true';\n\n/** The longest answer a slot of `kind` accepts, in code points: 2000 for open slots, 500 for the others. */\nexport function maxAnswerLength(kind: string | undefined): number {\n return kind === OPEN_SLOT_KIND ? MAX_OPEN_ANSWER_LENGTH : MAX_ANSWER_LENGTH;\n}\n\n/** Whether `value` is within the length limit of a slot of `kind`, counted in Unicode code points. */\nexport function fitsAnswer(value: string, kind?: string): boolean {\n const max = maxAnswerLength(kind);\n // Code points never outnumber UTF-16 units, and each takes at most two: count only in between.\n if (value.length <= max) return true;\n if (value.length > 2 * max) return false;\n let count = 0;\n for (const _ of value) if (++count > max) return false;\n return true;\n}\n\n/** Type guard for untrusted input (request bodies, storage). */\nexport function isAnswers(value: unknown): value is Answers {\n if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;\n const entries = Object.entries(value);\n if (entries.length > MAX_ANSWER_COUNT) return false;\n return entries.every(([k, v]) => k.length > 0 && k.length <= 200 && typeof v === 'string');\n}\n","/**\n * The document tree the engine and component definitions work on. Produced by the engine's HTML parser\n * (sources) and serialised back to HTML (views). Plain data: no DOM, no parent pointers.\n */\n\nexport interface ElementNode {\n readonly type: 'element';\n /** Lowercase tag name, e.g. `p`, `astl-gap`. */\n readonly tag: string;\n /** Attributes in source order. Values are already entity-decoded. */\n readonly attrs: Readonly<Record<string, string>>;\n readonly children: readonly Node[];\n}\n\nexport interface TextNode {\n readonly type: 'text';\n readonly value: string;\n}\n\nexport type Node = ElementNode | TextNode;\n\nexport function element(\n tag: string,\n attrs: Readonly<Record<string, string>> = {},\n children: readonly Node[] = [],\n): ElementNode {\n return { type: 'element', tag, attrs, children };\n}\n\nexport function text(value: string): TextNode {\n return { type: 'text', value };\n}\n\nexport function isElement(node: Node | undefined, tag?: string): node is ElementNode {\n return node !== undefined && node.type === 'element' && (tag === undefined || node.tag === tag);\n}\n\n/** Concatenated text of a subtree, like DOM `textContent`. */\nexport function textContent(node: Node): string {\n if (node.type === 'text') return node.value;\n let out = '';\n for (const child of node.children) out += textContent(child);\n return out;\n}\n\n/** Element children with the given tag, in order. */\nexport function childElements(node: ElementNode, tag?: string): ElementNode[] {\n return node.children.filter((c): c is ElementNode => isElement(c, tag));\n}\n","/**\n * Checker: how a player gets verdicts without ever holding the answer key (unless the host opts into local grading).\n * The HTTP binding of these bodies is the grading protocol (see protocol.ts and\n * apps/docs/src/content/docs/reference/protocol.md).\n */\nimport type { Answers } from './answers.js';\nimport type { Feedback } from './help.js';\nimport type { ProblemDetails } from './protocol.js';\nimport type { GradeResult, Solution } from './result.js';\n\nexport interface CheckRequest {\n readonly answers: Answers;\n /** View page id: grade only that page. Omit to grade everything. */\n readonly page?: string;\n /**\n * View element id: grade that interaction only, under a policy with `checkScope: 'interaction'`. It counts against\n * `maxChecks` like any check. Never together with `page`.\n */\n readonly element?: string;\n}\n\n/**\n * Help that comes with a result when the policy shows it (the engine's `helpShown`), for what was graded: absent when there is\n * none, so responses without help stay as they were.\n */\nexport interface ResultHelp {\n /** By view element id, and by view page id for a page's own feedback (picked by the page's score). */\n readonly feedback?: Readonly<Record<string, Feedback>>;\n /** HTML by view element id or view page id. */\n readonly explanations?: Readonly<Record<string, string>>;\n}\n\nexport interface CheckResponse extends ResultHelp {\n readonly result: GradeResult;\n /** Checks left in this attempt; null = unlimited. */\n readonly checksLeft: number | null;\n}\n\nexport interface SubmitRequest {\n readonly answers: Answers;\n}\n\nexport interface SubmitResponse extends ResultHelp {\n /** null when the policy reveals nothing yet. */\n readonly result: GradeResult | null;\n /** Only when the policy reveals answers. */\n readonly solution: Solution | null;\n /** null when there is no pass mark or nothing is revealed. */\n readonly passed: boolean | null;\n /** ISO 8601, set by whoever grades. */\n readonly submittedAt: string;\n}\n\nexport interface HintRequest {\n /** View element id, or a view page id for the page's own hints. */\n readonly element: string;\n}\n\n/** The next hint of an interaction or page. Whoever grades records it: a hint's cost counts when it is used. */\nexport interface HintResponse {\n /** HTML of content format 1. */\n readonly html: string;\n /** 0-based position of this hint. */\n readonly index: number;\n /** Hints still to come after this one. */\n readonly left: number;\n /** The fraction 0..1 of the points this hint takes off (0: free). */\n readonly cost: number;\n}\n\nexport interface Checker {\n /** Practice only. Rejects with CheckerError (`check_not_allowed`) under other policies. */\n check(request: CheckRequest): Promise<CheckResponse>;\n submit(request: SubmitRequest): Promise<SubmitResponse>;\n /**\n * The next hint, practice only; checkers without hints leave it out. Rejects with CheckerError `hints_not_allowed`\n * when the policy offers none, `hints_exhausted` when all are used, `not_found` for an unknown element.\n */\n hint?(request: HintRequest): Promise<HintResponse>;\n}\n\n/** Thrown by checkers for protocol-level refusals, carrying the RFC 9457 problem document. */\nexport class CheckerError extends Error {\n readonly problem: ProblemDetails;\n\n constructor(problem: ProblemDetails) {\n super(problem.detail ?? problem.title);\n this.name = 'CheckerError';\n this.problem = problem;\n }\n}\n","/**\n * Compile outputs. A source compiles to three artefacts:\n * - view: public HTML (no answers), cacheable on a CDN under its SHA-256;\n * - key: private answer key, only for whoever grades;\n * - metadata: public facts for catalogues and hosts.\n */\nimport type { DocKind } from './content.js';\nimport type { FeedbackVariant } from './help.js';\nimport type { JsonObject } from './json.js';\nimport type { ScoringGroup } from './scoring.js';\n\nexport const KEY_FORMAT_VERSION = 1;\n\nexport interface KeySlot {\n readonly kind: string;\n readonly key: JsonObject;\n /**\n * Opaque id of the component the slot belongs to, which is also the id of its scoring group, unless the component\n * is graded in parts (`ComponentDefinition.groups`): then its groups list the slot. Open slots (an ungraded kind)\n * belong to no group: no `groups` entry has this id or lists them.\n */\n readonly group: string;\n /** View page id. */\n readonly page: string;\n}\n\n/** A hint as the key holds it: its content (HTML of format 1) and the fraction 0..1 of the points it costs. */\nexport interface KeyHint {\n readonly html: string;\n readonly cost: number;\n}\n\n/** The help of one interaction or page (see help.ts): key-side, as it may give the answer away. */\nexport interface KeyHelp {\n readonly hints: readonly KeyHint[];\n /** HTML; null when there is none. */\n readonly explanation: string | null;\n /** HTML by variant, only the variants written. */\n readonly feedback: Readonly<Partial<Record<FeedbackVariant, string>>>;\n}\n\nexport interface AnswerKey {\n readonly format: typeof KEY_FORMAT_VERSION;\n /** Content language of the document. Slots inherit it unless their key says otherwise. */\n readonly lang: string;\n /** View hash this key belongs to. Hosts must store and serve them together. */\n readonly viewHash: string;\n readonly slots: Readonly<Record<string, KeySlot>>;\n readonly groups: readonly ScoringGroup[];\n /** View page ids in order. */\n readonly pages: readonly string[];\n /** Help by view element id and view page id; absent when the source has none. */\n readonly help?: Readonly<Record<string, KeyHelp>>;\n}\n\nexport interface PageMetadata {\n /** View page id. */\n readonly id: string;\n readonly label: string | null;\n /** Answer slots on the page, open ones included. */\n readonly slots: number;\n readonly maxScore: number;\n}\n\nexport interface Metadata {\n readonly format: number;\n readonly lang: string;\n readonly dir: 'ltr' | 'rtl';\n /**\n * The document's `kind` when it is not `exercise`, the default: as in the view, the metadata of every exercise (and\n * every conformance golden) stays as it was. Absent means `exercise`.\n */\n readonly kind?: DocKind;\n readonly viewHash: string;\n readonly pages: readonly PageMetadata[];\n /** Element counts by tag, e.g. `{ \"astl-gap\": 5 }`. */\n readonly elements: Readonly<Record<string, number>>;\n /** Answer slots, open ones included: what a player's `astl-ready` counts. */\n readonly slots: number;\n /**\n * Ids of the open slots (stored for a teacher, never graded), in reading order, so a server or a teacher's view can\n * pick these answers out of a submission. They add nothing to `maxScore`.\n */\n readonly open: readonly string[];\n readonly groups: number;\n readonly maxScore: number;\n /** Words of running text, for reading-time estimates. */\n readonly words: number;\n /** Numbers contributed by component `metadata` hooks, keyed `tag.name`. */\n readonly extra: Readonly<Record<string, number>>;\n}\n\nexport interface Compilation {\n readonly view: string;\n /** Lowercase hex SHA-256 of the UTF-8 view. */\n readonly viewHash: string;\n readonly key: AnswerKey;\n readonly metadata: Metadata;\n}\n\n/** Narrow check for keys loaded from storage. Full validation happens in the engine. */\nexport function isAnswerKey(value: unknown): value is AnswerKey {\n if (typeof value !== 'object' || value === null) return false;\n const v = value as Partial<AnswerKey>;\n return (\n v.format === KEY_FORMAT_VERSION &&\n typeof v.lang === 'string' &&\n typeof v.viewHash === 'string' &&\n typeof v.slots === 'object' &&\n v.slots !== null &&\n Array.isArray(v.groups) &&\n Array.isArray(v.pages) &&\n (v.help === undefined || (typeof v.help === 'object' && v.help !== null))\n );\n}\n","/**\n * The rich-text allow-list of content format 1, shared by the engine (sanitiser, view guard) and the player\n * (defensive pass when mounting a view). One list, so both sides can never disagree.\n */\nimport type { UrlPolicy } from './engine.js';\n\nexport const BLOCK_TAGS: ReadonlySet<string> = new Set([\n 'p',\n 'h2',\n 'h3',\n 'h4',\n 'ul',\n 'ol',\n 'li',\n 'blockquote',\n]);\n\n/** `img` is a picture: inline, so it can sit in text, prompts, options and cards. */\nexport const INLINE_TAGS: ReadonlySet<string> = new Set([\n 'strong',\n 'em',\n 'b',\n 'i',\n 'u',\n 's',\n 'sub',\n 'sup',\n 'code',\n 'mark',\n 'span',\n 'a',\n 'br',\n 'img',\n]);\n\n/**\n * A picture with a caption: a block directly in a page (or the document), holding exactly one `img` and at most one\n * `figcaption` (rich inline text), nothing else. A `figcaption` anywhere else is unwrapped.\n */\nexport const FIGURE_TAG = 'figure';\nexport const CAPTION_TAG = 'figcaption';\n\n/** Dropped together with their content: active content, embeds, media and form controls. */\nexport const REMOVED_WITH_CONTENT: ReadonlySet<string> = new Set([\n 'script',\n 'style',\n 'template',\n 'iframe',\n 'object',\n 'embed',\n 'noscript',\n 'svg',\n 'math',\n 'video',\n 'audio',\n 'form',\n 'input',\n 'select',\n 'textarea',\n 'button',\n]);\n\n/**\n * Attributes allowed on every content element. `style` goes through the allow-list of `declarations.ts` at each side\n * that reads it. `class` is not here on purpose: it exists in sources only, and the engine inlines it.\n */\nexport const CONTENT_ATTRIBUTES: ReadonlySet<string> = new Set(['lang', 'dir', 'style']);\n\n/** A source attribute naming named styles (`<astl-style name>`); no view ever holds it. */\nexport const CLASS_ATTRIBUTE = 'class';\n\n/** What `inertStyles` renames `style` to. */\nexport const INERT_STYLE = 'data-astl-style';\n\nconst START_TAG = /<[a-z](?:[^<>\"']|\"[^\"]*\"|'[^']*')*>/gi;\nconst STYLE_IN_TAG = /\"[^\"]*\"|'[^']*'|(\\s)style\\s*=/gi;\n\n/**\n * The HTML with every `style` attribute under another name, for parsing. Under a strict CSP any HTML parser reports a\n * `style` attribute as a violation the moment it meets one, in a template or a DOMParser document too (seen in Chromium\n * on all of them), though nothing in those documents is ever drawn. Only start tags change, never text or values.\n */\nexport const inertStyles = (html: string): string =>\n html.replace(START_TAG, (tag) =>\n tag.replace(STYLE_IN_TAG, (found, space?: string) =>\n space === undefined ? found : `${space}${INERT_STYLE}=`,\n ),\n );\n\n/**\n * A rule, first in `<astl-doc>`: `name` and `label` (a named style, applied with `class`) or `for` (every element of\n * that tag), with its declarations in `style`. Sources only: the engine inlines it.\n */\nexport const STYLE_TAG = 'astl-style';\n\n/** A layout: 2 to 4 columns directly on a page or in the document, wrapping by themselves; no nesting. */\nexport const COLUMNS_TAG = 'astl-columns';\n/** One column of a layout: blocks, figures and block components, as a page holds them. */\nexport const COLUMN_TAG = 'astl-column';\nexport const MIN_COLUMNS = 2;\nexport const MAX_COLUMNS = 4;\n\n/**\n * Extra attributes allowed on specific rich-text elements. A picture: `src` and `alt` (required; `alt=\"\"` marks\n * decoration), `width` and `height` (positive integers, so the layout does not jump while it loads).\n */\nexport const TAG_ATTRIBUTES: Readonly<Record<string, readonly string[]>> = {\n a: ['href'],\n ol: ['start'],\n img: ['src', 'alt', 'width', 'height'],\n};\n\n/** The attribute of a rich-text element that holds a URL, checked by the URL policy. */\nexport const URL_ATTRIBUTES: Readonly<Record<string, string>> = { a: 'href', img: 'src' };\n\n/** Attributes the document and page elements may carry in a view. */\nexport const DOC_ATTRIBUTES: readonly string[] = ['format', 'lang', 'dir', 'kind', 'style', 'style-template'];\n\n/**\n * What a document is, its `kind`: how it shows, never how it grades. An `exercise` (the default when absent) shows one\n * page at a time; a `book` shows two pages side by side (1-2, 3-4, ...) where the player is wide enough, turning them\n * a spread at a time. Practice and test are not kinds: they are policies over any kind (policy.ts).\n */\nexport const DOC_KINDS = ['exercise', 'book'] as const;\nexport type DocKind = (typeof DOC_KINDS)[number];\nexport const DEFAULT_DOC_KIND: DocKind = 'exercise';\nexport const PAGE_ATTRIBUTES: readonly string[] = ['id', 'label', 'lang', 'dir', 'style'];\n\n/** Most attributes one element may carry in a source (beyond it: SOURCE_TOO_COMPLEX, checked before parsing). */\nexport const MAX_ATTRIBUTES_PER_ELEMENT = 256;\n\n/** Deepest element nesting a source may have (beyond it: SOURCE_TOO_DEEP). */\nexport const MAX_NESTING_DEPTH = 100;\n\nconst SAFE_SCHEMES: ReadonlySet<string> = new Set(['http', 'https', 'mailto']);\n\n/** The default URL policy: absolute `http:`, `https:` and `mailto:` URLs (tabs and newlines ignored, as browsers do). */\nexport function isSafeUrl(url: string): boolean {\n const scheme = /^([a-z][a-z0-9+.-]*):/i.exec(url.replace(/[\\t\\n\\r]/g, '').trim());\n return scheme !== null && SAFE_SCHEMES.has((scheme[1] ?? '').toLowerCase());\n}\n\n/**\n * A host's URL policy as engines, players and the authoring kit use it: a URL passes only when the policy returns\n * `true`. A policy that throws, or returns anything else (the Promise of an async function, say), blocks the URL.\n */\nexport function strictUrlPolicy(policy: UrlPolicy): UrlPolicy {\n if (policy === isSafeUrl) return isSafeUrl;\n return (url, context) => {\n try {\n return policy(url, context) === true;\n } catch {\n return false;\n }\n };\n}\n","/**\n * Content format constants and the id grammar.\n *\n * Source: `<astl-doc format=\"1\" lang=\"pl\">` with `<astl-page>` children (or loose content = one implicit page).\n * Source ids are written by authors and editors; opaque ids are written by the compiler into views.\n */\n\n/** Current content format. Written as `format=\"1\"` on `<astl-doc>` in sources and views. */\nexport const FORMAT_VERSION = 1;\nexport const SUPPORTED_FORMATS: readonly number[] = [1];\n\nexport const DOC_TAG = 'astl-doc';\nexport const PAGE_TAG = 'astl-page';\n\n/** Largest accepted source, in UTF-16 code units. */\nexport const MAX_SOURCE_LENGTH = 1_000_000;\n\n/** Author ids: a letter, then letters, digits, `_` or `-`; at most 64 characters. Unique within one document. */\nexport const SOURCE_ID_PATTERN: RegExp = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;\n\n/** Opaque ids in views: `k` + 16 lowercase base32 characters (80 bits of an HMAC-SHA-256). */\nexport const OPAQUE_ID_PATTERN: RegExp = /^k[a-z2-7]{16}$/;\n\n/** Custom element names that components may use (HTML custom element rules, lowercase ASCII). */\nexport const ELEMENT_TAG_PATTERN: RegExp = /^[a-z][a-z0-9]*-[a-z0-9-]*$/;\n\n/** Prefix reserved for built-in Astrolabe elements. */\nexport const BUILT_IN_PREFIX = 'astl-';\n\nexport function isSourceId(value: string): boolean {\n return SOURCE_ID_PATTERN.test(value);\n}\n\nexport function isOpaqueId(value: string): boolean {\n return OPAQUE_ID_PATTERN.test(value);\n}\n\nexport type Direction = 'ltr' | 'rtl';\n\n/** Scripts written right to left, by BCP 47 primary language subtag (enough for the markets we target). */\nconst RTL_LANGUAGES: ReadonlySet<string> = new Set([\n 'ar',\n 'arc',\n 'ckb',\n 'dv',\n 'fa',\n 'he',\n 'ks',\n 'ku',\n 'ps',\n 'sd',\n 'ug',\n 'ur',\n 'yi',\n]);\n\n/** Writing direction for a BCP 47 tag, e.g. `he` -> `rtl`, `pl-PL` -> `ltr`. Script subtags win (`az-Arab`). */\nexport function directionOf(lang: string): Direction {\n const parts = lang.toLowerCase().split('-');\n if (parts.includes('arab') || parts.includes('hebr') || parts.includes('thaa') || parts.includes('syrc'))\n return 'rtl';\n if (parts.includes('latn') || parts.includes('cyrl')) return 'ltr';\n return RTL_LANGUAGES.has(parts[0] ?? '') ? 'rtl' : 'ltr';\n}\n\n/** Loose BCP 47 check: `pl`, `pl-PL`, `zh-Hant-TW`, `sr-Latn`. */\nexport const LANGUAGE_TAG_PATTERN: RegExp = /^[a-zA-Z]{2,3}(-[a-zA-Z0-9]{2,8})*$/;\n","/**\n * Help for students (content format 1, additive): hints, an explanation and feedback texts. Inside a graded component\n * they belong to that interaction; directly on a page, to the page. They usually give the answer away, so they are\n * key-side data: compile moves their content into the answer key (`AnswerKey.help`), and the view keeps only what a\n * player needs to offer them (`ElementHelp`, written as the attributes `HELP_ATTRIBUTES`).\n */\n/** One hint, rich content; hints come in source order. `cost`: the fraction 0..1 of the points it takes off. */\nexport const HINT_TAG = 'astl-hint';\n/** Why the answer is what it is; at most one per interaction or page. */\nexport const EXPLANATION_TAG = 'astl-explanation';\n/** The text for one verdict, picked by `when`; at most one per `when`. */\nexport const FEEDBACK_TAG = 'astl-feedback';\nexport const HELP_TAGS: ReadonlySet<string> = new Set([HINT_TAG, EXPLANATION_TAG, FEEDBACK_TAG]);\n\n/** The `when` of a feedback text: one per group verdict, `omitted` for `empty`. */\nexport type FeedbackVariant = 'correct' | 'incorrect' | 'partial' | 'omitted';\nexport const FEEDBACK_VARIANTS: readonly FeedbackVariant[] = ['correct', 'incorrect', 'partial', 'omitted'];\n\n/** What a view says about the help of an interaction or a page, so a player can offer it: never its text. */\nexport interface ElementHelp {\n /** The cost of each hint, in order (0: free). */\n readonly hints: readonly number[];\n readonly explanation: boolean;\n /** The variants with a text, in `FEEDBACK_VARIANTS` order. */\n readonly feedback: readonly FeedbackVariant[];\n}\n\n/**\n * The view attributes of `ElementHelp`, on a graded component or a page: `hints=\"0 0.25\"` (the costs, space\n * separated), `explanation` (present when there is one) and `feedback=\"correct incorrect\"` (the variants with a text,\n * in `FEEDBACK_VARIANTS` order). Only those with something to say are written; sources never carry them. The engine\n * writes them (compile), the player reads them.\n */\nexport const HELP_ATTRIBUTES: readonly string[] = ['hints', 'explanation', 'feedback'];\n\n/** A feedback text as a student gets it: the variant of the verdict and the author's text (HTML of format 1). */\nexport interface Feedback {\n /** The verdict's variant; its text is the `incorrect` one when a partial verdict has none of its own. */\n readonly variant: FeedbackVariant;\n readonly html: string;\n}\n","/**\n * A dependency-free ICU MessageFormat 1 subset: `{name}`, `{name, number[, integer|percent]}`,\n * `{name, plural|selectordinal, [offset:n] =0 {..} one {..} few {..} many {..} other {..}}` with `#`,\n * and `{name, select, a {..} other {..}}`, nested to any depth. Apostrophe quoting as in ICU\n * (`''` is a literal apostrophe, `'{'` quotes syntax characters). Dates and times are not supported on purpose:\n * hosts format them and pass strings.\n */\nimport type { MessageFormatter, MessageParams } from './types.js';\n\nexport type MessagePart =\n | { readonly type: 'text'; readonly value: string }\n | {\n readonly type: 'arg';\n readonly name: string;\n readonly style: 'plain' | 'number' | 'integer' | 'percent';\n }\n | {\n readonly type: 'plural';\n readonly name: string;\n readonly ordinal: boolean;\n readonly offset: number;\n readonly options: Readonly<Record<string, readonly MessagePart[]>>;\n }\n | {\n readonly type: 'select';\n readonly name: string;\n readonly options: Readonly<Record<string, readonly MessagePart[]>>;\n }\n | { readonly type: 'pound' };\n\nexport class MessageSyntaxError extends Error {\n readonly offset: number;\n\n constructor(message: string, offset: number) {\n super(`${message} at offset ${offset}`);\n this.name = 'MessageSyntaxError';\n this.offset = offset;\n }\n}\n\nconst PLURAL_KEYWORDS: ReadonlySet<string> = new Set(['zero', 'one', 'two', 'few', 'many', 'other']);\n\nclass Parser {\n private pos = 0;\n\n constructor(private readonly src: string) {}\n\n parse(): MessagePart[] {\n const parts = this.message(false);\n if (this.pos < this.src.length) throw new MessageSyntaxError('Unexpected \"}\"', this.pos);\n return parts;\n }\n\n /** Parses until an unmatched `}` (not consumed) or the end. */\n private message(inPlural: boolean): MessagePart[] {\n const parts: MessagePart[] = [];\n let buf = '';\n const flush = () => {\n if (buf !== '') parts.push({ type: 'text', value: buf });\n buf = '';\n };\n while (this.pos < this.src.length) {\n const ch = this.src[this.pos] as string;\n if (ch === \"'\") {\n buf += this.apostrophe(inPlural);\n } else if (ch === '{') {\n flush();\n parts.push(this.argument());\n } else if (ch === '}') {\n break;\n } else if (ch === '#' && inPlural) {\n flush();\n parts.push({ type: 'pound' });\n this.pos++;\n } else {\n buf += ch;\n this.pos++;\n }\n }\n flush();\n return parts;\n }\n\n private apostrophe(inPlural: boolean): string {\n const next = this.src[this.pos + 1];\n if (next === \"'\") {\n this.pos += 2;\n return \"'\";\n }\n if (next === '{' || next === '}' || (inPlural && next === '#')) {\n // Quoted literal until the next lone apostrophe.\n this.pos++;\n let out = '';\n while (this.pos < this.src.length) {\n const ch = this.src[this.pos] as string;\n if (ch === \"'\") {\n if (this.src[this.pos + 1] === \"'\") {\n out += \"'\";\n this.pos += 2;\n continue;\n }\n this.pos++;\n return out;\n }\n out += ch;\n this.pos++;\n }\n return out;\n }\n this.pos++;\n return \"'\";\n }\n\n private argument(): MessagePart {\n const start = this.pos;\n this.pos++; // {\n const name = this.word();\n if (name === '') throw new MessageSyntaxError('Missing argument name', this.pos);\n this.space();\n if (this.eat('}')) return { type: 'arg', name, style: 'plain' };\n if (!this.eat(',')) throw new MessageSyntaxError('Expected \",\" or \"}\"', this.pos);\n this.space();\n const kind = this.word();\n this.space();\n if (kind === 'number') {\n let style: 'number' | 'integer' | 'percent' = 'number';\n if (this.eat(',')) {\n this.space();\n const s = this.word();\n if (s !== 'integer' && s !== 'percent')\n throw new MessageSyntaxError(`Unsupported number style \"${s}\"`, this.pos);\n style = s;\n this.space();\n }\n this.expect('}');\n return { type: 'arg', name, style };\n }\n if (kind === 'plural' || kind === 'selectordinal' || kind === 'select') {\n this.expect(',');\n this.space();\n let offset = 0;\n if (kind !== 'select' && this.src.startsWith('offset:', this.pos)) {\n this.pos += 'offset:'.length;\n this.space();\n const n = this.word();\n offset = Number(n);\n if (!Number.isInteger(offset) || offset < 0)\n throw new MessageSyntaxError(`Invalid offset \"${n}\"`, this.pos);\n this.space();\n }\n // Null prototype: option keys like `__proto__` or `constructor` stay plain data.\n const options: Record<string, readonly MessagePart[]> = Object.create(null);\n while (!this.eat('}')) {\n if (this.pos >= this.src.length) throw new MessageSyntaxError('Unclosed argument', start);\n const key = this.word();\n if (key === '') throw new MessageSyntaxError('Expected an option key', this.pos);\n if (kind !== 'select' && !PLURAL_KEYWORDS.has(key) && !/^=\\d+$/.test(key)) {\n throw new MessageSyntaxError(`Invalid plural key \"${key}\"`, this.pos);\n }\n if (Object.hasOwn(options, key)) throw new MessageSyntaxError(`Duplicate option \"${key}\"`, this.pos);\n this.space();\n this.expect('{');\n options[key] = this.message(kind !== 'select');\n this.expect('}');\n this.space();\n }\n if (!Object.hasOwn(options, 'other')) throw new MessageSyntaxError('Missing \"other\" option', start);\n return kind === 'select'\n ? { type: 'select', name, options }\n : { type: 'plural', name, ordinal: kind === 'selectordinal', offset, options };\n }\n throw new MessageSyntaxError(`Unsupported argument type \"${kind}\"`, this.pos);\n }\n\n private word(): string {\n const m = /^[^\\s{}#,'\"]+/u.exec(this.src.slice(this.pos));\n if (!m) return '';\n this.pos += m[0].length;\n return m[0];\n }\n\n private space(): void {\n while (this.pos < this.src.length && /\\s/u.test(this.src[this.pos] as string)) this.pos++;\n }\n\n private eat(ch: string): boolean {\n if (this.src[this.pos] === ch) {\n this.pos++;\n return true;\n }\n return false;\n }\n\n private expect(ch: string): void {\n if (!this.eat(ch)) throw new MessageSyntaxError(`Expected \"${ch}\"`, this.pos);\n }\n}\n\nexport function parseMessage(message: string): MessagePart[] {\n return new Parser(message).parse();\n}\n\n/** Names of all arguments a message uses, including plural and select selectors. */\nexport function messageParams(parts: readonly MessagePart[]): Set<string> {\n const names = new Set<string>();\n const walk = (list: readonly MessagePart[]) => {\n for (const p of list) {\n if (p.type === 'arg') names.add(p.name);\n if (p.type === 'plural' || p.type === 'select') {\n names.add(p.name);\n for (const sub of Object.values(p.options)) walk(sub);\n }\n }\n };\n walk(parts);\n return names;\n}\n\n/** Own-property lookup: option keys such as `constructor` must never resolve to Object.prototype members. */\nfunction option(\n options: Readonly<Record<string, readonly MessagePart[]>>,\n key: string,\n): readonly MessagePart[] | undefined {\n return Object.hasOwn(options, key) ? options[key] : undefined;\n}\n\nfunction render(\n parts: readonly MessagePart[],\n params: MessageParams,\n locale: string,\n pound: string | null,\n): string {\n let out = '';\n for (const p of parts) {\n switch (p.type) {\n case 'text':\n out += p.value;\n break;\n case 'pound':\n out += pound ?? '#';\n break;\n case 'arg': {\n const v = params[p.name];\n if (v === undefined) out += `{${p.name}}`;\n else if (typeof v === 'number' || p.style !== 'plain')\n out += formatNumber(Number(v), p.style, locale);\n else out += v;\n break;\n }\n case 'select': {\n const v = params[p.name];\n const branch =\n (v !== undefined ? option(p.options, String(v)) : undefined) ?? option(p.options, 'other') ?? [];\n out += render(branch, params, locale, pound);\n break;\n }\n case 'plural': {\n const n = Number(params[p.name]);\n if (Number.isNaN(n)) {\n out += render(option(p.options, 'other') ?? [], params, locale, `{${p.name}}`);\n break;\n }\n const exact = option(p.options, `=${n}`);\n const value = n - p.offset;\n const category = pluralRules(locale, p.ordinal).select(value);\n const branch = exact ?? option(p.options, category) ?? option(p.options, 'other') ?? [];\n out += render(branch, params, locale, formatNumber(value, 'number', locale));\n break;\n }\n }\n }\n return out;\n}\n\nconst pluralCache = new Map<string, Intl.PluralRules>();\n\nfunction pluralRules(locale: string, ordinal: boolean): Intl.PluralRules {\n const id = `${locale}|${ordinal ? 'o' : 'c'}`;\n let rules = pluralCache.get(id);\n if (!rules) {\n rules = new Intl.PluralRules(locale, { type: ordinal ? 'ordinal' : 'cardinal' });\n pluralCache.set(id, rules);\n }\n return rules;\n}\n\nfunction formatNumber(\n value: number,\n style: 'plain' | 'number' | 'integer' | 'percent',\n locale: string,\n): string {\n if (style === 'integer') return new Intl.NumberFormat(locale, { maximumFractionDigits: 0 }).format(value);\n if (style === 'percent') return new Intl.NumberFormat(locale, { style: 'percent' }).format(value);\n return new Intl.NumberFormat(locale, { maximumFractionDigits: 2 }).format(value);\n}\n\n/** Plural categories a locale needs, e.g. `pl` -> one, few, many, other. */\nexport function pluralCategories(locale: string, ordinal = false): readonly string[] {\n return pluralRules(locale, ordinal).resolvedOptions().pluralCategories as readonly string[];\n}\n\nconst parsedCache = new Map<string, readonly MessagePart[] | null>();\n\n/** The default MessageFormatter. A message with a syntax error renders as its raw text instead of throwing. */\nexport const icuFormatter: MessageFormatter = {\n format(message: string, params: MessageParams, locale: string): string {\n let parts = parsedCache.get(message);\n if (parts === undefined) {\n try {\n parts = parseMessage(message);\n } catch {\n parts = null;\n }\n parsedCache.set(message, parts);\n }\n return parts === null ? message : render(parts, params, locale, null);\n },\n};\n","/**\n * Catalog checks for CI: every translation has the same keys and parameters as the source catalog, parses, and\n * covers every plural category its locale needs (Polish: one, few, many, other).\n */\nimport { type MessagePart, messageParams, parseMessage, pluralCategories } from './format.js';\nimport type { MessageCatalog } from './types.js';\n\nexport interface CatalogProblem {\n readonly key: string;\n readonly kind: 'missing' | 'extra' | 'syntax' | 'params' | 'plural';\n readonly detail: string;\n}\n\nfunction pluralProblems(parts: readonly MessagePart[], locale: string): string[] {\n const out: string[] = [];\n const walk = (list: readonly MessagePart[]) => {\n for (const p of list) {\n if (p.type === 'plural') {\n const needed = pluralCategories(locale, p.ordinal);\n const missing = needed.filter((c) => !Object.hasOwn(p.options, c));\n if (missing.length > 0) out.push(`{${p.name}} lacks ${missing.join(', ')}`);\n }\n if (p.type === 'plural' || p.type === 'select') for (const sub of Object.values(p.options)) walk(sub);\n }\n };\n walk(parts);\n return out;\n}\n\n/** Problems of `catalog` alone (syntax and plural coverage). */\nexport function checkCatalog(catalog: MessageCatalog): CatalogProblem[] {\n const problems: CatalogProblem[] = [];\n for (const [key, message] of Object.entries(catalog.messages)) {\n try {\n const parts = parseMessage(message);\n for (const detail of pluralProblems(parts, catalog.locale))\n problems.push({ key, kind: 'plural', detail });\n } catch (e) {\n problems.push({ key, kind: 'syntax', detail: (e as Error).message });\n }\n }\n return problems;\n}\n\n/** Problems of a translation compared with its source catalog (same namespace). */\nexport function compareCatalogs(source: MessageCatalog, translation: MessageCatalog): CatalogProblem[] {\n const problems = checkCatalog(translation);\n for (const [key, message] of Object.entries(source.messages)) {\n const other = Object.hasOwn(translation.messages, key) ? translation.messages[key] : undefined;\n if (other === undefined) {\n problems.push({ key, kind: 'missing', detail: `missing in ${translation.locale}` });\n continue;\n }\n try {\n const want = [...messageParams(parseMessage(message))].sort().join(',');\n const got = [...messageParams(parseMessage(other))].sort().join(',');\n if (want !== got) problems.push({ key, kind: 'params', detail: `expected {${want}}, got {${got}}` });\n } catch {\n // Syntax problems are already reported by checkCatalog.\n }\n }\n for (const key of Object.keys(translation.messages)) {\n if (!Object.hasOwn(source.messages, key))\n problems.push({ key, kind: 'extra', detail: `not in ${source.locale}` });\n }\n return problems;\n}\n","import { icuFormatter } from './format.js';\nimport type { I18n, MessageCatalog, MessageFormatter, MessageParams, Translate } from './types.js';\n\n/**\n * BCP 47 lookup (RFC 4647 section 3.4, extended): for each requested tag try the tag, then shorter prefixes\n * (`pl-PL` -> `pl`), then any available tag with the same language (`pt` -> `pt-BR`). Case-insensitive.\n */\nexport function negotiateLocale(\n requested: readonly string[],\n available: readonly string[],\n fallback: string,\n): string {\n const byLower = new Map(available.map((a) => [a.toLowerCase(), a]));\n for (const tag of requested) {\n const parts = tag.toLowerCase().split('-');\n for (let n = parts.length; n > 0; n--) {\n const hit = byLower.get(parts.slice(0, n).join('-'));\n if (hit) return hit;\n }\n const lang = parts[0];\n const sameLanguage = available.find((a) => a.toLowerCase().split('-')[0] === lang);\n if (sameLanguage) return sameLanguage;\n }\n return fallback;\n}\n\n/** `pl-PL` -> [`pl-PL`, `pl`]. */\nfunction chain(locale: string): string[] {\n const parts = locale.split('-');\n const out: string[] = [];\n for (let n = parts.length; n > 0; n--) out.push(parts.slice(0, n).join('-').toLowerCase());\n return out;\n}\n\nexport interface CreateI18nOptions {\n readonly catalogs: readonly MessageCatalog[];\n /** Default `en`. */\n readonly fallbackLocale?: string;\n readonly formatter?: MessageFormatter;\n}\n\nexport function createI18n(options: CreateI18nOptions): I18n {\n const fallbackLocale = options.fallbackLocale ?? 'en';\n const formatter = options.formatter ?? icuFormatter;\n // namespace -> lowercased locale -> { locale, messages }\n const table = new Map<string, Map<string, { locale: string; messages: Record<string, string> }>>();\n for (const c of options.catalogs) {\n let byLocale = table.get(c.namespace);\n if (!byLocale) {\n byLocale = new Map();\n table.set(c.namespace, byLocale);\n }\n const id = c.locale.toLowerCase();\n const entry = byLocale.get(id) ?? {\n locale: c.locale,\n messages: Object.create(null) as Record<string, string>,\n };\n Object.assign(entry.messages, c.messages);\n byLocale.set(id, entry);\n }\n\n const t = (locale: string, namespace: string, key: string, params: MessageParams = {}): string => {\n const byLocale = table.get(namespace);\n if (byLocale) {\n for (const id of [...chain(locale), ...chain(fallbackLocale)]) {\n const entry = byLocale.get(id);\n const message = entry && Object.hasOwn(entry.messages, key) ? entry.messages[key] : undefined;\n if (entry && message !== undefined) return formatter.format(message, params, entry.locale);\n }\n }\n return key;\n };\n\n return {\n fallbackLocale,\n locales(namespace?: string): readonly string[] {\n const out = new Set<string>();\n for (const [ns, byLocale] of table) {\n if (namespace !== undefined && ns !== namespace) continue;\n for (const entry of byLocale.values()) out.add(entry.locale);\n }\n return [...out];\n },\n t,\n translator(locale: string, namespace: string): Translate {\n return (key, params) => t(locale, namespace, key, params);\n },\n with(catalogs: readonly MessageCatalog[]): I18n {\n return createI18n({ ...options, catalogs: [...options.catalogs, ...catalogs] });\n },\n };\n}\n","/**\n * Validation issues. Codes + params, never English sentences: hosts render them with message catalogs\n * (`<namespace>` of the reporting component, or `astl.engine` for document-level codes).\n */\n\nexport type Severity = 'error' | 'warning';\n\nexport type IssueParams = Readonly<Record<string, string | number>>;\n\nexport interface IssueLocation {\n /** Source id of the page, or null for the implicit page / document level. */\n readonly page: string | null;\n /** Source id of the closest element that has one (the component), or null. */\n readonly element: string | null;\n /** Tag of the element the issue is about, or null for the document. */\n readonly tag: string | null;\n /**\n * Readable path from the root, e.g. `astl-doc > astl-page#p1 > p[2] > astl-gap#g1`. Empty for issues raised before\n * the document could be parsed (SOURCE_TOO_LARGE, DOC_ROOT_INVALID), whose `tag` is null.\n */\n readonly path: string;\n}\n\nexport interface Issue {\n /** Stable UPPER_SNAKE code. Component codes start with the type, e.g. `CHOICE_CORRECT_MISSING`. */\n readonly code: string;\n /** Errors block compiling; warnings do not. */\n readonly severity: Severity;\n /** i18n namespace of the message (`astl.engine` or the manifest's `messages`). */\n readonly namespace: string;\n readonly params: IssueParams;\n readonly at: IssueLocation;\n}\n\n/** i18n namespace of document-level issues reported by the engine. */\nexport const ENGINE_NAMESPACE = 'astl.engine';\n\n/** Document-level issue codes. Component codes are listed in each manifest's `issues`. */\nexport const EngineIssue = {\n SOURCE_TOO_LARGE: 'SOURCE_TOO_LARGE',\n SOURCE_TOO_DEEP: 'SOURCE_TOO_DEEP',\n SOURCE_TOO_COMPLEX: 'SOURCE_TOO_COMPLEX',\n DOC_ROOT_INVALID: 'DOC_ROOT_INVALID',\n DOC_FORMAT_UNSUPPORTED: 'DOC_FORMAT_UNSUPPORTED',\n DOC_LANG_MISSING: 'DOC_LANG_MISSING',\n DOC_LANG_INVALID: 'DOC_LANG_INVALID',\n DOC_EMPTY: 'DOC_EMPTY',\n DOC_MIXED_PAGES: 'DOC_MIXED_PAGES',\n NO_COMPONENTS: 'NO_COMPONENTS',\n PAGE_EMPTY: 'PAGE_EMPTY',\n PAGE_NESTED: 'PAGE_NESTED',\n ID_MISSING: 'ID_MISSING',\n ID_INVALID: 'ID_INVALID',\n ID_DUPLICATE: 'ID_DUPLICATE',\n ELEMENT_UNKNOWN: 'ELEMENT_UNKNOWN',\n ELEMENT_REMOVED: 'ELEMENT_REMOVED',\n ATTRIBUTE_REMOVED: 'ATTRIBUTE_REMOVED',\n ATTRIBUTE_INVALID: 'ATTRIBUTE_INVALID',\n ATTRIBUTE_REQUIRED: 'ATTRIBUTE_REQUIRED',\n CHILD_UNEXPECTED: 'CHILD_UNEXPECTED',\n /** A child tag of a registered component outside that component (a word to select outside its passage). */\n CHILD_OUTSIDE: 'CHILD_OUTSIDE',\n CHILD_COUNT: 'CHILD_COUNT',\n PLACEMENT_INVALID: 'PLACEMENT_INVALID',\n COMPONENT_NESTED: 'COMPONENT_NESTED',\n URL_BLOCKED: 'URL_BLOCKED',\n IMG_ALT_MISSING: 'IMG_ALT_MISSING',\n FIGURE_INVALID: 'FIGURE_INVALID',\n SCORING_MODE_INVALID: 'SCORING_MODE_INVALID',\n POINTS_INVALID: 'POINTS_INVALID',\n VERSION_UNSUPPORTED: 'VERSION_UNSUPPORTED',\n STYLE_TEMPLATE_UNKNOWN: 'STYLE_TEMPLATE_UNKNOWN',\n /** A declaration the `style` allow-list refuses (`declarations.ts`): it goes, the rest of the style stays. */\n STYLE_REMOVED: 'STYLE_REMOVED',\n /** A `style` over MAX_STYLE_LENGTH: it goes whole. */\n STYLE_TOO_LONG: 'STYLE_TOO_LONG',\n /** A class no `<astl-style>` defines. */\n STYLE_UNKNOWN: 'STYLE_UNKNOWN',\n /** An `<astl-style>` that defines nothing usable: a bad or reserved `name`, an unknown `for`, or both or neither. */\n STYLE_NAME_INVALID: 'STYLE_NAME_INVALID',\n /** More `<astl-style>` rules than MAX_STYLE_RULES. */\n STYLE_RULES_TOO_MANY: 'STYLE_RULES_TOO_MANY',\n /** Inlining the rules would write more than MAX_INLINED_STYLES into the view. */\n STYLE_TOO_LARGE: 'STYLE_TOO_LARGE',\n /** Text and background of an element too close to read: the author decides. */\n STYLE_LOW_CONTRAST: 'STYLE_LOW_CONTRAST',\n /** Help (`astl-hint`, `astl-explanation`, `astl-feedback`) with nothing graded around it or on its page: it goes. */\n HELP_UNGRADED: 'HELP_UNGRADED',\n /** Help without content: it goes. */\n HELP_EMPTY: 'HELP_EMPTY',\n /** A hint `cost` that is not a number from 0 to 1. */\n HINT_COST_INVALID: 'HINT_COST_INVALID',\n /** A feedback `when` that is not one of `correct`, `incorrect`, `partial`, `omitted`. */\n FEEDBACK_WHEN_INVALID: 'FEEDBACK_WHEN_INVALID',\n /** Two feedback texts for one `when` in one interaction or page. */\n FEEDBACK_DUPLICATE: 'FEEDBACK_DUPLICATE',\n /** Two explanations in one interaction or page. */\n EXPLANATION_DUPLICATE: 'EXPLANATION_DUPLICATE',\n /** A layout of the wrong shape: `<astl-columns>` directly on a page, holding 2 to 4 `<astl-column>`, not nested. */\n COLUMNS_INVALID: 'COLUMNS_INVALID',\n} as const;\n\nexport type EngineIssueCode = (typeof EngineIssue)[keyof typeof EngineIssue];\n\nexport function hasErrors(issues: readonly Issue[]): boolean {\n return issues.some((i) => i.severity === 'error');\n}\n","/**\n * StyleTemplate: a named look for a whole exercise or for single components, registered by the host (trusted code,\n * like the host's own CSS; exercises only refer to templates by name). Authors pick one with\n * `style-template=\"<name>\"` on `<astl-doc>` or on a component. The closest one wins: the component's, then the\n * document's, then the player's default. A template restyles through design tokens and `::part()` declarations only:\n * it never changes behaviour or grading, and it does not apply in the `hc` theme or under forced colours, so\n * high-contrast users always get the high-contrast look.\n */\nimport type { MessageCatalog } from './i18n/types.js';\n\n/** The attribute that picks a template, on `<astl-doc>` and on every component. */\nexport const STYLE_TEMPLATE_ATTRIBUTE = 'style-template';\n\n/** Template names: lowercase kebab-case, 1 to 40 characters, starting with a letter. */\nexport const STYLE_TEMPLATE_NAME: RegExp = /^(?=.{1,40}$)[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\n\n/** `document`: the whole exercise (the player's canvas and chrome). `component`: one element and its subtree. */\nexport type StyleScope = 'document' | 'component';\n\n/** Token values by token name without the `--astl-` prefix, e.g. `{ accent: '#7a3ff2', 'radius-m': '1rem' }`. */\nexport type TokenOverrides = Readonly<Record<string, string>>;\n\n/** CSS declarations by property name, e.g. `{ 'border-radius': 'var(--astl-radius-l)' }`. */\nexport type Declarations = Readonly<Record<string, string>>;\n\nexport interface StyleTemplate {\n /** What authors write in `style-template`. Matches STYLE_TEMPLATE_NAME. */\n readonly name: string;\n /** Bumped when the look changes visibly. Exercises keep referring to the name. */\n readonly version: number;\n /** Where the template may be used. */\n readonly scopes: readonly StyleScope[];\n /** Component tags it supports at the `component` scope; absent = every registered component. */\n readonly components?: readonly string[];\n /** i18n namespace of its texts: `label` (picker label) and `description` (one line), e.g. `astl.style.notebook`. */\n readonly messages: string;\n /** Catalogs of that namespace. */\n readonly catalogs?: readonly MessageCatalog[];\n /** Token overrides for the light and dark themes (never `hc`). */\n readonly tokens?: TokenOverrides;\n /** Overrides on top of `tokens` for the light theme only. */\n readonly light?: TokenOverrides;\n /** Overrides on top of `tokens` for the dark theme only. */\n readonly dark?: TokenOverrides;\n /**\n * `::part()` declarations by component tag, then part name (a name from the manifest's `cssParts`), e.g.\n * `{ 'astl-choice': { option: { 'border-radius': 'var(--astl-radius-l)' } } }`. Use tokens in values so the\n * declarations follow the theme.\n */\n readonly parts?: Readonly<Record<string, Readonly<Record<string, Declarations>>>>;\n}\n\nconst SCOPES: readonly unknown[] = ['document', 'component'];\n\nconst isRecord = (value: unknown): value is Readonly<Record<string, unknown>> =>\n typeof value === 'object' && value !== null && !Array.isArray(value);\n\n/** Absent, or a record of strings. */\nconst isStrings = (value: unknown): boolean =>\n value === undefined || (isRecord(value) && Object.values(value).every((v) => typeof v === 'string'));\n\n/**\n * Whether `value` has the shape of a StyleTemplate: a valid name, a positive version, one or both scopes, string tags,\n * a namespace, and records of strings for tokens and parts. Registries use it for hosts without type checking.\n */\nexport function isStyleTemplate(value: unknown): value is StyleTemplate {\n if (!isRecord(value)) return false;\n const { name, version, scopes, components, messages, catalogs, tokens, light, dark, parts } = value;\n const parted = (byTag: unknown) => isRecord(byTag) && Object.values(byTag).every(isStrings);\n return (\n typeof name === 'string' &&\n STYLE_TEMPLATE_NAME.test(name) &&\n typeof version === 'number' &&\n Number.isInteger(version) &&\n version >= 1 &&\n Array.isArray(scopes) &&\n scopes.length > 0 &&\n new Set(scopes).size === scopes.length &&\n scopes.every((scope) => SCOPES.includes(scope)) &&\n (components === undefined ||\n (Array.isArray(components) && components.every((t) => typeof t === 'string'))) &&\n typeof messages === 'string' &&\n (catalogs === undefined || Array.isArray(catalogs)) &&\n isStrings(tokens) &&\n isStrings(light) &&\n isStrings(dark) &&\n (parts === undefined || (isRecord(parts) && Object.values(parts).every(parted)))\n );\n}\n","/**\n * ComponentManifest: the ONLY per-type schema. Plain data, shared by the engine (sanitiser allow-list, validation,\n * view allow-list), the player (attribute parsing), the editor (node attributes, default inspector), docs, JSON Schema\n * and agent tool schemas. Nothing else may restate a component's attributes.\n */\nimport type { ScoringRule } from './scoring.js';\nimport { STYLE_TEMPLATE_ATTRIBUTE } from './style.js';\n\n/**\n * - `public`: kept in the view as written.\n * - `private`: kept only in the answer key / never leaves the server.\n * - `derived`: computed by the definition's `toView`; authors cannot write it.\n */\nexport type Visibility = 'public' | 'private' | 'derived';\n\n/**\n * - `id`: a source id local to the component (e.g. an option id); replaced by an opaque id in the view.\n * - `boolean`: HTML boolean attribute (present = true; `\"false\"` is invalid).\n * - `url`: checked by the engine's UrlPolicy; a blocked URL is removed with a URL_BLOCKED warning.\n */\nexport type AttributeType = 'string' | 'boolean' | 'integer' | 'number' | 'enum' | 'id' | 'url';\n\nexport interface AttributeSpec {\n readonly name: string;\n readonly type: AttributeType;\n readonly visibility: Visibility;\n readonly required?: boolean;\n /** Allowed values for `enum`. */\n readonly values?: readonly string[];\n /** Inclusive bounds for `integer` and `number`. */\n readonly min?: number;\n readonly max?: number;\n /** Value used when the attribute is absent. Documented and shown by the editor. */\n readonly default?: string | number | boolean;\n}\n\n/**\n * A child element type a component accepts, e.g. `<astl-option>` inside `<astl-choice>`.\n * - `content: 'text'`: plain text only (e.g. an accepted alternative answer).\n * - `content: 'inline'`: rich inline content (emphasis, `lang` spans, math).\n */\nexport interface ChildSpec {\n readonly tag: string;\n readonly visibility: 'public' | 'private';\n readonly content: 'text' | 'inline';\n readonly min: number;\n /** null = unbounded. */\n readonly max: number | null;\n readonly attributes: readonly AttributeSpec[];\n /**\n * Only in a type with rich content (`content: 'flow'`). Absent: the child sits in that content's text (a word to\n * select). `'lead'`: it stands before the content, as the element's first child, never in its text (a prompt).\n */\n readonly place?: 'lead';\n}\n\n/**\n * Scoring modes an author can pick with the `scoring` attribute, each mapped to one engine rule.\n * Mode names speak the author's language (`all`, `per-option`); rules are the three engine rules.\n */\nexport interface ScoringSpec {\n readonly default: string;\n readonly modes: Readonly<Record<string, ScoringRule>>;\n}\n\n/**\n * Presentation variants, picked by authors with the public `variant` attribute: how the element looks and behaves for\n * the student (a gap that grows while typing, a select with a search box), never what it grades or which answers\n * exist, so every variant of a source grades the same. The engine validates the value (an enum of `values`), elements\n * render it, the authoring kit offers it (labels: `editor.value.variant.<value>` in the manifest's namespace).\n * Adding a variant is not a breaking change; removing one or changing the default is (bump `version`).\n */\nexport interface VariantSpec {\n /** Used when the attribute is absent or unknown to an older player. */\n readonly default: string;\n /** Kebab-case names, `default` included. */\n readonly values: readonly string[];\n}\n\nexport interface ComponentManifest {\n /** Custom element name. Built-ins use the `astl-` prefix; third parties use their own. */\n readonly tag: string;\n /** Element format version, written as `v=\"n\"` in views. Bump on incompatible changes and add a migration. */\n readonly version: number;\n /** `inline` sits inside text (a gap); `block` stands between paragraphs (a multiple choice). */\n readonly display: 'inline' | 'block';\n /**\n * Whether the type is scored. Graded types form one scoring group of graded slots. Ungraded types have no scoring\n * and add nothing to the maximum: they produce no slots (flash cards, media), or only open slots (a long answer),\n * whose answers are stored with the attempt for a teacher.\n */\n readonly graded: boolean;\n /** Type-specific attributes. The common ones (`id`, `v`, `scoring`, `points`) come from `COMMON_ATTRIBUTES`. */\n readonly attributes: readonly AttributeSpec[];\n /**\n * Absent: the element holds its declared children only. `'flow'` (blocks only): it wraps rich content as a page\n * holds it (paragraphs, headings, lists, quotes, figures, formatting, pictures; no components), and its declared\n * children are inline children that sit in that content's text where an inline component may sit (a word to\n * select in a passage), except those with `place: 'lead'`, which come first, before the content (a prompt);\n * `min` and `max` count them wherever they are.\n */\n readonly content?: 'flow';\n readonly children: readonly ChildSpec[];\n /** null for ungraded types. */\n readonly scoring: ScoringSpec | null;\n /** null for types with a single presentation. */\n readonly variants: VariantSpec | null;\n /**\n * Slot kinds the definition produces; each must be registered with the engine. Graded types list graded kinds only,\n * ungraded types ungraded ones only (`open`).\n */\n readonly slotKinds: readonly string[];\n /** Issue codes the definition may report (namespace = `messages`). */\n readonly issues: readonly string[];\n /** i18n namespace for this type's messages, e.g. `astl.gap`. */\n readonly messages: string;\n /** Accessibility contract, used by docs and conformance: ARIA pattern and the keys that operate it. */\n readonly a11y: { readonly pattern: string; readonly keys: readonly string[] };\n /** `part` names the element exposes for `::part()` styling. Public theming API. */\n readonly cssParts: readonly string[];\n}\n\n/** Attributes every component accepts. `scoring` and `points` only apply to graded types. */\nexport const COMMON_ATTRIBUTES: readonly AttributeSpec[] = [\n /** Source id, unique in the document. Views carry an opaque id instead. */\n { name: 'id', type: 'id', visibility: 'public', required: true },\n /** Element format version. Optional in sources (absent = 1); the compiler always writes the current one. */\n { name: 'v', type: 'integer', visibility: 'public', min: 1 },\n /** A registered StyleTemplate with the `component` scope (see style.ts); checked by the engine's registry. */\n { name: STYLE_TEMPLATE_ATTRIBUTE, type: 'string', visibility: 'public' },\n];\n\nexport const SCORING_ATTRIBUTES: readonly AttributeSpec[] = [\n /** One of the manifest's scoring modes; absent = the manifest's default mode. */\n { name: 'scoring', type: 'string', visibility: 'private' },\n /** Points of the element's scoring group. */\n { name: 'points', type: 'number', visibility: 'private', min: 0.01, max: 1000, default: 1 },\n];\n\n/** The `variant` attribute of a type with variants: an enum of the manifest's variant names. */\nexport function variantAttribute(variants: VariantSpec): AttributeSpec {\n return {\n name: 'variant',\n type: 'enum',\n visibility: 'public',\n values: variants.values,\n default: variants.default,\n };\n}\n\n/** Every attribute an element of this type may carry, common ones first. */\nexport function allAttributes(manifest: ComponentManifest): readonly AttributeSpec[] {\n const scoring = manifest.scoring === null ? [] : SCORING_ATTRIBUTES;\n const variant = manifest.variants === null ? [] : [variantAttribute(manifest.variants)];\n return [...COMMON_ATTRIBUTES, ...scoring, ...variant, ...manifest.attributes];\n}\n\n/** JSON with object keys sorted, so equal specs compare equal whatever order their keys are written in. */\nfunction canonical(value: unknown): string {\n return JSON.stringify(value, (_key, v: unknown) =>\n v !== null && typeof v === 'object' && !Array.isArray(v)\n ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => (a < b ? -1 : 1)))\n : v,\n );\n}\n\n/**\n * Whether two child specs may share a tag: the same visibility and attributes (in any order), so the tag carries the\n * same data and keeps the same things private in every type that declares it (`astl-prompt`, `astl-option`). Content\n * and counts are each type's own: a select's options are plain text, a choice's options rich.\n */\nexport function sameChildSpec(a: ChildSpec, b: ChildSpec): boolean {\n const attributes = (spec: ChildSpec) =>\n canonical([...spec.attributes].sort((x, y) => (x.name < y.name ? -1 : x.name > y.name ? 1 : 0)));\n return a.visibility === b.visibility && attributes(a) === attributes(b);\n}\n\n/** A child tag two of the manifests declare with specs that differ (see `sameChildSpec`), or null when none does. */\nexport function childTagConflict(\n manifests: readonly ComponentManifest[],\n): { readonly tag: string; readonly components: readonly [string, string] } | null {\n const first = new Map<string, { readonly component: string; readonly spec: ChildSpec }>();\n for (const manifest of manifests) {\n for (const child of manifest.children) {\n const seen = first.get(child.tag);\n if (seen === undefined) first.set(child.tag, { component: manifest.tag, spec: child });\n else if (!sameChildSpec(seen.spec, child)) {\n return { tag: child.tag, components: [seen.component, manifest.tag] };\n }\n }\n }\n return null;\n}\n","/**\n * Player element contract. Every component element (built-in or third-party, Lit or not) implements\n * PlayerElementApi; `<astl-player>` talks to elements only through it. No DOM types here on purpose:\n * the player package intersects it with HTMLElement.\n */\nimport type { Answers, SlotId } from './answers.js';\nimport type { Checker } from './checker.js';\nimport type { Feedback } from './help.js';\nimport type { MessageParams } from './i18n/types.js';\nimport type { JsonValue } from './json.js';\nimport type { GroupVerdict, SlotVerdict, Solution } from './result.js';\n\nexport interface ElementFeedback {\n /** Verdicts for this element's slots that the student may see. */\n readonly slots: Readonly<Record<SlotId, SlotVerdict>>;\n /** Verdict of the element's scoring group; null when ungraded or graded in parts. */\n readonly group: GroupVerdict | null;\n /** Verdicts of the groups an element graded in parts names in `groupIds` (a crossword's words), by group id. */\n readonly groups?: Readonly<Record<string, GroupVerdict>>;\n /**\n * The author's feedback for the element's verdict and its explanation (HTML), when the policy shows them. The player\n * shows both under the element, so an element needs to do nothing with them.\n */\n readonly message?: Feedback | null;\n readonly explanation?: string | null;\n}\n\nexport interface Units {\n readonly answered: number;\n readonly total: number;\n}\n\n/** What the player gives each element when it mounts the view. */\nexport interface ElementContext {\n /** UI locale for labels and announcements (not the content language). */\n readonly locale: string;\n /**\n * Formats a message in the UI locale from the element type's namespace, falling back to the shared `astl.player`\n * namespace (verdict words such as `verdict.correct`, generic labels).\n */\n t(key: string, params?: MessageParams): string;\n /** Polite announcement through the player's single live region. */\n announce(message: string): void;\n /** 1-based position among numbered elements (inline questions), for labels such as \"Gap 3\". 0 = not numbered. */\n readonly number: number;\n /** Per-attempt seed for UI shuffles; null = keep the view order. */\n readonly seed: string | null;\n}\n\nexport interface PlayerElementApi {\n /** Slot ids this element answers, in reading order. Stable after the element connects. */\n readonly slotIds: readonly SlotId[];\n /**\n * The ids of the groups an element may be graded in (`ComponentDefinition.groups`), as its view names them: the\n * player passes their verdicts in `feedback.groups`. Absent: one group, the element's id.\n */\n readonly groupIds?: readonly string[];\n /** Answered slots only. */\n getAnswers(): Answers;\n /** Unknown ids are ignored; `''` clears a slot. Does not fire a change event. */\n setAnswers(answers: Answers): void;\n /** Shows verdicts; null clears them. Editing a slot clears its own verdict. */\n feedback: ElementFeedback | null;\n /** Shows the correct answers next to the student's; null hides them. */\n solution: Solution | null;\n disabled: boolean;\n /** Progress units, e.g. 3 of 5 cards placed. */\n units(): Units;\n /** Called by the player once, before the first render. Elements must work with a default context too. */\n attach(context: ElementContext): void;\n /** Non-answer UI state worth restoring after a reload. */\n getUiState?(): JsonValue;\n setUiState?(state: JsonValue): void;\n}\n\n/** DOM events. All bubble and are composed (they cross shadow roots). */\nexport const PlayerEvent = {\n /** From an element when the student changes an answer. Detail: ChangeDetail. */\n change: 'astl-change',\n /** From `<astl-player>` when the view is mounted and elements are attached. Detail: ReadyDetail. */\n ready: 'astl-ready',\n /** Page changed. Detail: PageDetail. */\n page: 'astl-page',\n /** Attempt state changed. Detail: StateDetail. */\n state: 'astl-state',\n /** A check or submit finished. Detail: the CheckResponse or SubmitResponse. */\n result: 'astl-result',\n /** Snapshot to persist (debounced). Detail: Snapshot. */\n snapshot: 'astl-snapshot',\n /** Loading or grading failed. Detail: ErrorDetail. */\n error: 'astl-error',\n} as const;\n\n/** Detail of `astl-ready`. */\nexport interface ReadyDetail {\n readonly viewHash: string;\n /** Number of pages. */\n readonly pages: number;\n /** Number of slots across all registered elements. */\n readonly slots: number;\n}\n\nexport interface ChangeDetail {\n /** Changed slots only; `''` = cleared. */\n readonly answers: Answers;\n}\n\nexport interface PageDetail {\n readonly index: number;\n readonly count: number;\n /** View page id. */\n readonly id: string;\n}\n\nexport type AttemptState =\n | 'loading'\n | 'ready'\n | 'active'\n | 'checking'\n | 'submitting'\n | 'submitted'\n | 'review'\n | 'error';\n\nexport interface StateDetail {\n readonly state: AttemptState;\n readonly previous: AttemptState;\n}\n\nexport interface ErrorDetail {\n readonly code: string;\n readonly message: string;\n}\n\n/**\n * Turns source HTML (with answers) into a view and a checker for it, for `<astl-player>` light-DOM sources. Registered\n * by bundles that ship the engine (the HTML-with-answers mode); the player itself never holds answer logic.\n * - `lang`: content language of the source (filled from the page when the `<astl-doc>` has none);\n * - `locale`: UI locale of the asking player, for the messages of a failed compile.\n * A failed compile throws; the Error message (plain text, one issue per line) is shown to the author.\n */\nexport type SourceCompiler = (\n source: string,\n context: { readonly lang: string; readonly locale: string },\n) => Promise<{ readonly view: string; readonly checker: Checker }>;\n","/**\n * Attempt policies. Practice, quiz and test are policies over the same content, not different content: a document's\n * `kind` (`DOC_KINDS`, exercise or book) is how it shows, never how it grades.\n * The server is authoritative: the player only reflects the policy it is given.\n */\nexport type AttemptMode = 'practice' | 'test' | 'review';\n\n/**\n * What a submit returns to the student:\n * - `nothing`: just the confirmation (results released later by the host);\n * - `score`: score and verdicts;\n * - `answers`: score, verdicts and the solution.\n */\nexport type Reveal = 'nothing' | 'score' | 'answers';\n\n/** `interaction`: a check may cover one interaction too (`CheckRequest.element`), not only the exercise or a page. */\nexport type CheckScope = 'exercise' | 'interaction';\n\n/**\n * When feedback texts or explanations come: `never`; `check`: after every check and the hand-in; `submit`: after the\n * hand-in only. At the hand-in they come only with the answers (`reveal: 'answers'`): they may give them away.\n */\nexport type HelpMoment = 'never' | 'check' | 'submit';\n\nexport interface AttemptPolicy {\n /** `practice`: check any time. `test`: no check, one submit. `review`: read-only, shows a submitted attempt. */\n readonly mode: AttemptMode;\n /** `linear`: no going back to earlier pages (tests). */\n readonly navigation: 'free' | 'linear';\n /** Practice only. null = unlimited. */\n readonly maxChecks: number | null;\n /** ISO 8601. The server auto-submits at the deadline; the player only shows the countdown. */\n readonly deadline: string | null;\n /** Fraction of the maximum score needed to pass, 0..1. null = no pass mark. */\n readonly passMark: number | null;\n readonly reveal: Reveal;\n /** Seed for per-attempt UI shuffles. null = keep the view order. */\n readonly seed: string | null;\n // The help fields may be left out (policies written before them): each absent one is its mode's default, the value\n // in PRACTICE_POLICY for practice and in TEST_POLICY otherwise (`helpPolicy`). A host merges an author's switches\n // into them, turning help off.\n /** Hints on request, one at a time from the checker (`Checker.hint`). Practice only. */\n readonly hints?: boolean;\n /** Practice only. */\n readonly checkScope?: CheckScope;\n readonly feedback?: HelpMoment;\n readonly explanations?: HelpMoment;\n}\n\nexport const PRACTICE_POLICY: AttemptPolicy = {\n mode: 'practice',\n navigation: 'free',\n maxChecks: null,\n deadline: null,\n passMark: null,\n reveal: 'answers',\n seed: null,\n hints: true,\n checkScope: 'interaction',\n feedback: 'check',\n explanations: 'check',\n};\n\nexport const TEST_POLICY: AttemptPolicy = {\n mode: 'test',\n navigation: 'free',\n maxChecks: 0,\n deadline: null,\n passMark: null,\n reveal: 'score',\n seed: null,\n hints: false,\n checkScope: 'exercise',\n feedback: 'submit',\n explanations: 'submit',\n};\n\n/** The help fields of a policy, with every absent one taken from its mode's default policy. */\nexport interface HelpPolicy {\n readonly hints: boolean;\n readonly checkScope: CheckScope;\n readonly feedback: HelpMoment;\n readonly explanations: HelpMoment;\n}\n\nexport function helpPolicy(policy: AttemptPolicy): HelpPolicy {\n const base = policy.mode === 'practice' ? PRACTICE_POLICY : TEST_POLICY;\n const practice = policy.mode === 'practice';\n return {\n hints: practice && (policy.hints ?? base.hints) === true,\n checkScope: practice ? (policy.checkScope ?? base.checkScope ?? 'exercise') : 'exercise',\n feedback: policy.feedback ?? base.feedback ?? 'never',\n explanations: policy.explanations ?? base.explanations ?? 'never',\n };\n}\n\nconst isMoment = (x: unknown): boolean => x === 'never' || x === 'check' || x === 'submit';\n\nexport function isAttemptPolicy(value: unknown): value is AttemptPolicy {\n if (typeof value !== 'object' || value === null) return false;\n const v = value as Partial<AttemptPolicy>;\n const nullableNumber = (x: unknown) =>\n x === null || (typeof x === 'number' && Number.isFinite(x) && x >= 0);\n return (\n (v.mode === 'practice' || v.mode === 'test' || v.mode === 'review') &&\n (v.navigation === 'free' || v.navigation === 'linear') &&\n nullableNumber(v.maxChecks) &&\n (v.deadline === null || (typeof v.deadline === 'string' && !Number.isNaN(Date.parse(v.deadline)))) &&\n (v.passMark === null || (typeof v.passMark === 'number' && v.passMark >= 0 && v.passMark <= 1)) &&\n (v.reveal === 'nothing' || v.reveal === 'score' || v.reveal === 'answers') &&\n (v.seed === null || typeof v.seed === 'string') &&\n (v.hints === undefined || typeof v.hints === 'boolean') &&\n (v.checkScope === undefined || v.checkScope === 'exercise' || v.checkScope === 'interaction') &&\n (v.feedback === undefined || isMoment(v.feedback)) &&\n (v.explanations === undefined || isMoment(v.explanations))\n );\n}\n","/**\n * Grading protocol over HTTP. Any backend in any language can implement it:\n *\n * POST {endpoint}/check body CheckRequest -> 200 CheckResponse\n * POST {endpoint}/submit body SubmitRequest -> 200 SubmitResponse\n * POST {endpoint}/hint body HintRequest -> 200 HintResponse\n *\n * `{endpoint}` identifies one attempt (e.g. `/api/attempts/123`); how it is authorised is up to the host\n * (cookie, bearer token). Errors are `application/problem+json` (RFC 9457) with a `code` from ProblemCode.\n */\n\nexport const PROTOCOL_VERSION = 1;\n\nexport const JSON_MEDIA_TYPE = 'application/json';\nexport const PROBLEM_MEDIA_TYPE = 'application/problem+json';\n\nexport const ProtocolPath = {\n check: 'check',\n submit: 'submit',\n hint: 'hint',\n} as const;\n\nexport const ProblemCode = {\n /** 400: body is not valid JSON or does not match the request schema. */\n invalidRequest: 'invalid_request',\n /** 401: the host could not identify the attempt. */\n unauthorized: 'unauthorized',\n /** 403: checking is not allowed under this policy (tests). */\n checkNotAllowed: 'check_not_allowed',\n /** 403: the practice policy's maxChecks is used up. */\n checksExhausted: 'checks_exhausted',\n /** 403: the policy offers no hints (tests, or a practice policy with `hints: false`). */\n hintsNotAllowed: 'hints_not_allowed',\n /** 403: every hint of that interaction or page is used. */\n hintsExhausted: 'hints_exhausted',\n /** 404: unknown attempt, page or element. */\n notFound: 'not_found',\n /** 405: wrong method. */\n methodNotAllowed: 'method_not_allowed',\n /** 409: the attempt is already submitted. */\n attemptClosed: 'attempt_closed',\n /** 413: body too large. */\n payloadTooLarge: 'payload_too_large',\n /** 500: unexpected server error. */\n internal: 'internal_error',\n} as const;\n\nexport type ProblemCodeValue = (typeof ProblemCode)[keyof typeof ProblemCode];\n\nexport interface ProblemDetails {\n readonly type: string;\n readonly title: string;\n readonly status: number;\n readonly detail?: string;\n readonly code: ProblemCodeValue;\n}\n\n/** Largest request body servers should accept, in bytes. */\nexport const MAX_REQUEST_BYTES: number = 256 * 1024;\n\nexport function isProblemDetails(value: unknown): value is ProblemDetails {\n if (typeof value !== 'object' || value === null) return false;\n const v = value as Partial<ProblemDetails>;\n return typeof v.title === 'string' && typeof v.status === 'number' && typeof v.code === 'string';\n}\n","/**\n * Grading results as students and hosts see them. Results never contain key data: no accepted answers, no correct\n * option ids. Solutions travel separately and only when the attempt policy reveals them.\n */\nimport type { SlotId } from './answers.js';\n\nexport type SlotVerdict = 'correct' | 'incorrect';\n\nexport type GroupVerdict = 'correct' | 'partial' | 'incorrect' | 'empty';\n\nexport interface GroupResult {\n readonly id: string;\n readonly verdict: GroupVerdict;\n readonly score: number;\n readonly max: number;\n}\n\nexport interface Score {\n readonly score: number;\n readonly max: number;\n}\n\nexport interface VerdictCounts {\n readonly correct: number;\n readonly partial: number;\n readonly incorrect: number;\n readonly empty: number;\n /** Number of groups counted. */\n readonly total: number;\n}\n\nexport interface GradeResult extends Score {\n /** True when every included group is correct; false when no group is included (empty key or unknown page). */\n readonly correct: boolean;\n /**\n * Per-slot verdicts the student may see: answered slots only, selected flags only, and nothing for slots of\n * multi-slot `all-correct` groups (those show only the group verdict).\n */\n readonly slots: Readonly<Record<SlotId, SlotVerdict>>;\n readonly groups: readonly GroupResult[];\n /** Score per view page id. */\n readonly pages: Readonly<Record<string, Score>>;\n /** Counts over groups. */\n readonly counts: VerdictCounts;\n}\n\n/** Correct answers by slot, shown when the policy reveals them. `''` entries are omitted. */\nexport type Solution = Readonly<Record<SlotId, string>>;\n\n/** Rounds a score for display: at most 2 decimals, no trailing zeros. */\nexport function roundScore(value: number): number {\n return Math.round(value * 100) / 100;\n}\n","/**\n * Scoring groups. Every graded component forms one group by default (id = the component's opaque id), or one per\n * part when its definition grades it in parts (`ComponentDefinition.groups`, a crossword's words), where a slot may\n * sit in several groups.\n *\n * Rules (n = slots in the group, c = correct slots, P = points):\n * - `all-correct`: max P; score P when c = n, else 0. Feedback shows only the group verdict, never which slot is wrong.\n * - `per-slot`: max P x n; score P x c.\n * - `proportional`: max P; score P x c / n (exact, not rounded).\n *\n * Selection slots (flags, e.g. options of a multiple-answer choice): an unselected flag gets no verdict, and a group\n * whose flags are all unselected scores 0 with verdict `empty`.\n */\nexport type ScoringRule = 'all-correct' | 'per-slot' | 'proportional';\n\nexport const SCORING_RULES: readonly ScoringRule[] = ['all-correct', 'per-slot', 'proportional'];\n\nexport interface ScoringGroup {\n readonly id: string;\n readonly rule: ScoringRule;\n readonly points: number;\n /** Slot ids in reading order. */\n readonly slots: readonly string[];\n /** View page id the group belongs to. */\n readonly page: string;\n}\n\n/** Group maximum for a rule. */\nexport function groupMax(rule: ScoringRule, points: number, slotCount: number): number {\n return rule === 'per-slot' ? points * slotCount : points;\n}\n","/**\n * Slot kinds: the open registry of grading semantics. The engine never switches on a kind; it asks the registered\n * SlotKind. Built-ins (engine): `text`, `number`, `choice`, `flag`, and `open` (stored for a teacher, never graded).\n * Hosts and third parties may register more.\n */\nimport type { JsonObject } from './json.js';\n\nexport interface GradeContext {\n /** Content language of the slot (BCP 47), for locale-aware comparisons. */\n readonly lang: string;\n}\n\nexport interface SlotKind<TKey extends JsonObject = JsonObject> {\n readonly kind: string;\n /** Selection slots use flag semantics (see scoring.ts). */\n readonly selection: boolean;\n /**\n * False for a kind that is stored but never graded (the built-in `open`): its slots belong to no scoring group, get\n * no verdict and add nothing to the maximum, and only ungraded types (`graded: false`) produce them. Default true:\n * graded types produce only graded kinds.\n */\n readonly graded?: boolean;\n /** Validates a stored key (compile output, or a key loaded from storage). */\n isKey(key: JsonObject): key is TKey;\n /** `answer` is never empty here: the engine handles unanswered slots before calling. */\n isCorrect(key: TKey, answer: string, context: GradeContext): boolean;\n /** The answer that shows the solution. `''` = leave the slot empty (an unselected flag). */\n solution(key: TKey): string;\n}\n\n/**\n * How typed text is compared. Resolved at compile time and stored inside each text key, so stored keys grade the same\n * forever, whatever the defaults are later.\n */\nexport interface NormalisationProfile {\n /** Unicode normalisation applied first. */\n readonly form: 'NFC' | 'NFKC';\n /** `collapse`: trim and turn every whitespace run into one space. */\n readonly space: 'strict' | 'collapse';\n /** `insensitive`: locale-aware lower-casing with the content language (Turkish dotless i works). */\n readonly case: 'sensitive' | 'insensitive';\n /** `fold`: ignore diacritics (ą = a, ł = l, ø = o, ß = ss). `strict` keeps them: żółw != zolw. */\n readonly marks: 'strict' | 'fold';\n /** `ignore-edge`: drop punctuation at the start and end (\"ssak.\" = \"ssak\"). */\n readonly punctuation: 'strict' | 'ignore-edge';\n /** `fold`: typographic quotes, apostrophes and dashes compare equal to ASCII ones. */\n readonly quotes: 'strict' | 'fold';\n}\n\nexport const DEFAULT_PROFILE: NormalisationProfile = {\n form: 'NFC',\n space: 'collapse',\n case: 'insensitive',\n marks: 'strict',\n punctuation: 'ignore-edge',\n quotes: 'fold',\n};\n","/**\n * Snapshot: everything needed to restore an attempt in the player after a reload. Hosts store it\n * (localStorage, server draft); the player emits it and accepts it back.\n */\nimport { type Answers, isAnswers } from './answers.js';\nimport type { JsonValue } from './json.js';\n\nexport const SNAPSHOT_FORMAT = 1;\n\nexport interface Snapshot {\n readonly format: typeof SNAPSHOT_FORMAT;\n /** View the snapshot was taken on. A player ignores snapshots of another view. */\n readonly viewHash: string | null;\n readonly answers: Answers;\n /** 0-based page index. */\n readonly page: number;\n readonly checks: number;\n readonly submitted: boolean;\n /** Non-answer UI state per element id (e.g. a flashcard index). */\n readonly ui: Readonly<Record<string, JsonValue>>;\n /** ISO 8601. */\n readonly savedAt: string;\n}\n\nexport function isSnapshot(value: unknown): value is Snapshot {\n if (typeof value !== 'object' || value === null) return false;\n const v = value as Partial<Snapshot>;\n return (\n v.format === SNAPSHOT_FORMAT &&\n (v.viewHash === null || typeof v.viewHash === 'string') &&\n isAnswers(v.answers) &&\n Number.isInteger(v.page) &&\n (v.page ?? -1) >= 0 &&\n Number.isInteger(v.checks) &&\n typeof v.submitted === 'boolean' &&\n typeof v.ui === 'object' &&\n v.ui !== null &&\n typeof v.savedAt === 'string'\n );\n}\n","{\n \"playful.label\": \"Playful\",\n \"playful.description\": \"Rounder shapes, bolder lines and brighter colours, still calm enough to read.\",\n \"notebook.label\": \"Notebook\",\n \"notebook.description\": \"Cream paper, ink-blue text and small corners, like a school notebook.\"\n}\n","{\n \"playful.label\": \"Zabawny\",\n \"playful.description\": \"Bardziej zaokrąglone kształty, grubsze linie i żywsze kolory, a tekst nadal czyta się spokojnie.\",\n \"notebook.label\": \"Zeszyt\",\n \"notebook.description\": \"Kremowy papier, granatowy tekst i małe zaokrąglenia, jak w szkolnym zeszycie.\"\n}\n","/**\n * Neutral, brand-free design tokens. Every value becomes a CSS custom property `--astl-<name>`.\n * Hosts brand the player by overriding these properties, never by styling internals.\n */\n\nexport type Theme = 'light' | 'dark' | 'hc';\n\n/** `auto` follows `prefers-color-scheme` (light or dark). */\nexport type ThemeSetting = Theme | 'auto';\n\nexport const THEMES: readonly Theme[] = ['light', 'dark', 'hc'];\n\n/** A slot of the group palette. */\nexport type PaletteSlot = 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8;\n\n/** A colour of the group palette. */\nexport type PaletteColor = `palette-${PaletteSlot}`;\n\n/** The group palette: a colour (`palette-<n>`) and its soft fill (`palette-<n>-soft`) per slot. */\nexport type PaletteToken = PaletteColor | `${PaletteColor}-soft`;\n\n/**\n * The group palette in slot order: eight colours that tell groups apart (categories, pairs, zones, joined lines,\n * found words, regions). Give groups the slots in order and start again after the eighth; each colour has a soft\n * fill, `--astl-palette-<n>-soft`, for backgrounds.\n * - Never red or green, the verdict colours: every slot stays at least 15 (CIEDE2000) from success and danger, and\n * at least 10 from the partial amber (warning).\n * - Neighbours stay apart for red-green colour blindness (protanopia, deuteranopia), also the eighth and the first:\n * warm and cool slots alternate.\n * - Each colour reads as text on the page and surface backgrounds (4.5:1, 7:1 in hc), and so do ink, ink-muted and\n * the colour itself on its soft fill.\n * - Colour never carries meaning alone: groups also differ by their label or a pattern. Under forced colours the\n * palette gives way to system colours (CanvasText, and Canvas for the soft fills).\n */\nexport const PALETTE: readonly PaletteColor[] = [\n 'palette-1',\n 'palette-2',\n 'palette-3',\n 'palette-4',\n 'palette-5',\n 'palette-6',\n 'palette-7',\n 'palette-8',\n];\n\n/**\n * Per slot: the colour and its soft fill in light, the colour and its soft fill in dark, the colour in hc (darker,\n * for 7:1; its fill is white, like every soft fill of hc). One row per slot keeps the player's first load small.\n */\nconst PALETTE_COLORS: readonly (readonly [string, string, string, string, string])[] = [\n ['#066086', '#e5f3fe', '#59c7fe', '#152c3a', '#035678'], // blue\n ['#7d5036', '#ffeee4', '#f9914d', '#37261c', '#884501'], // clay (orange in dark and hc)\n ['#6d377e', '#f8edfb', '#d08edc', '#332635', '#663575'], // purple\n ['#7c6301', '#f8f0e1', '#ffe490', '#2f2a19', '#6b5500'], // gold\n ['#016f6f', '#def5f5', '#10c7c8', '#0f2f2f', '#045455'], // teal\n ['#603211', '#ffede4', '#bd8c68', '#37271b', '#4e2104'], // brown\n ['#9a2b64', '#ffecf3', '#e27eaa', '#39242d', '#9a2562'], // magenta\n ['#4b4f00', '#f3f1e2', '#bdc16c', '#2b2b19', '#3d4100'], // olive\n];\n\n/** The palette tokens of a theme, or the system colours they become under forced colours. */\nfunction palette(theme: Theme | 'forced'): Readonly<Record<PaletteToken, string>> {\n return Object.fromEntries(\n PALETTE.flatMap((color, i) => {\n const [light = '', lightSoft = '', dark = '', darkSoft = '', hc = ''] = PALETTE_COLORS[i] ?? [];\n const [main, soft] = {\n light: [light, lightSoft],\n dark: [dark, darkSoft],\n hc: [hc, '#ffffff'],\n forced: ['CanvasText', 'Canvas'],\n }[theme];\n return [\n [color, main],\n [`${color}-soft`, soft],\n ];\n }),\n ) as Record<PaletteToken, string>;\n}\n\nexport type ColorToken =\n | 'canvas'\n | 'surface'\n | 'surface-raised'\n | 'ink'\n | 'ink-muted'\n | 'line'\n | 'outline'\n | 'accent'\n | 'on-accent'\n | 'accent-soft'\n | 'focus'\n | 'success'\n | 'success-soft'\n | 'on-success'\n | 'danger'\n | 'danger-soft'\n | 'warning'\n | 'warning-soft'\n | 'selected'\n | 'selected-soft'\n | PaletteToken;\n\nexport type ScaleToken =\n | 'font-body'\n | 'font-display'\n | 'font-mono'\n | 'size-content'\n | 'size-ui'\n | 'size-small'\n | 'line-height-content'\n | 'space-1'\n | 'space-2'\n | 'space-3'\n | 'space-4'\n | 'space-5'\n | 'space-6'\n | 'space-7'\n | 'space-8'\n | 'radius-s'\n | 'radius-m'\n | 'radius-l'\n | 'radius-pill'\n | 'outline-width'\n | 'focus-width'\n | 'focus-offset'\n | 'target-min'\n | 'duration-fast'\n | 'duration-normal'\n | 'separator-display';\n\n/** Non-colour values that change with the theme. */\nexport type ThemeScaleToken = 'selected-bar' | 'selected-weight';\n\nexport type TokenName = ColorToken | ScaleToken | ThemeScaleToken;\n\nexport type ColorScheme = Readonly<Record<ColorToken, string>>;\n\nexport interface Tokens {\n /** Theme-independent tokens: type, space, radii, widths, durations. */\n readonly scale: Readonly<Record<ScaleToken, string>>;\n /**\n * Theme-dependent non-colour cues. `hc` marks selected items with a bar at their inline start and bold text, so\n * selection never depends on a native control mark or on colour alone (and never looks like a verdict border).\n */\n readonly themeScale: Readonly<Record<Theme, Readonly<Record<ThemeScaleToken, string>>>>;\n /** Colours per theme. `hc` is black on white: every text pair reaches 7:1. */\n readonly themes: Readonly<Record<Theme, ColorScheme>>;\n /** System colours used under `forced-colors: active`. */\n readonly forced: ColorScheme;\n}\n\nconst systemStack =\n 'system-ui, -apple-system, \"Segoe UI\", Roboto, \"Noto Sans\", Ubuntu, Cantarell, \"Helvetica Neue\", Arial, sans-serif';\n\nexport const tokens: Tokens = {\n scale: {\n 'font-body': systemStack,\n 'font-display': systemStack,\n 'font-mono': 'ui-monospace, SFMono-Regular, Menlo, Consolas, \"Liberation Mono\", monospace',\n 'size-content': '1.1875rem',\n 'size-ui': '1rem',\n 'size-small': '0.875rem',\n 'line-height-content': '1.6',\n 'space-1': '0.25rem',\n 'space-2': '0.5rem',\n 'space-3': '0.75rem',\n 'space-4': '1rem',\n 'space-5': '1.5rem',\n 'space-6': '2rem',\n 'space-7': '3rem',\n 'space-8': '4rem',\n 'radius-s': '4px',\n 'radius-m': '8px',\n 'radius-l': '12px',\n 'radius-pill': '999px',\n 'outline-width': '2px',\n 'focus-width': '3px',\n 'focus-offset': '2px',\n 'target-min': '44px',\n 'duration-fast': '120ms',\n 'duration-normal': '200ms',\n // `inline` shows the separator between options laid out as words (a select's buttons: \"mat / hat\"); looks set it.\n 'separator-display': 'none',\n },\n themeScale: {\n light: { 'selected-bar': '0px', 'selected-weight': 'normal' },\n dark: { 'selected-bar': '0px', 'selected-weight': 'normal' },\n hc: { 'selected-bar': '6px', 'selected-weight': '700' },\n },\n themes: {\n light: {\n canvas: '#f3f4f6',\n surface: '#ffffff',\n 'surface-raised': '#ffffff',\n ink: '#16191d',\n 'ink-muted': '#4f5763',\n line: '#d3d7de',\n outline: '#6b7380',\n accent: '#1d55c9',\n 'on-accent': '#ffffff',\n 'accent-soft': '#e7eefb',\n focus: '#1d4fbf',\n success: '#1b7337',\n 'success-soft': '#e5f3e9',\n 'on-success': '#ffffff',\n danger: '#b3261e',\n 'danger-soft': '#fcebea',\n warning: '#8a4f00',\n 'warning-soft': '#fcf1df',\n selected: '#5233b8',\n 'selected-soft': '#efebfb',\n ...palette('light'),\n },\n dark: {\n canvas: '#0f1114',\n surface: '#1a1d21',\n 'surface-raised': '#23272c',\n ink: '#eceef1',\n 'ink-muted': '#aab1bc',\n line: '#3a3f47',\n outline: '#8a929e',\n accent: '#8bb3ff',\n 'on-accent': '#0a1530',\n 'accent-soft': '#1d2a45',\n focus: '#9fc0ff',\n success: '#6dcf8d',\n 'success-soft': '#14301f',\n 'on-success': '#062010',\n danger: '#ff8a80',\n 'danger-soft': '#3d1715',\n warning: '#f0bd62',\n 'warning-soft': '#3a2a0d',\n selected: '#b9a6ff',\n 'selected-soft': '#2a2448',\n ...palette('dark'),\n },\n hc: {\n canvas: '#ffffff',\n surface: '#ffffff',\n 'surface-raised': '#ffffff',\n ink: '#000000',\n 'ink-muted': '#2b2b2b',\n line: '#000000',\n outline: '#000000',\n accent: '#000000',\n 'on-accent': '#ffffff',\n 'accent-soft': '#ffffff',\n focus: '#000000',\n success: '#005a1e',\n 'success-soft': '#ffffff',\n 'on-success': '#ffffff',\n danger: '#8f0000',\n 'danger-soft': '#ffffff',\n warning: '#5a3600',\n 'warning-soft': '#ffffff',\n selected: '#000000',\n 'selected-soft': '#ffffff',\n ...palette('hc'),\n },\n },\n forced: {\n canvas: 'Canvas',\n surface: 'Canvas',\n 'surface-raised': 'Canvas',\n ink: 'CanvasText',\n 'ink-muted': 'CanvasText',\n line: 'GrayText',\n outline: 'ButtonText',\n accent: 'Highlight',\n 'on-accent': 'HighlightText',\n 'accent-soft': 'Canvas',\n focus: 'Highlight',\n success: 'CanvasText',\n 'success-soft': 'Canvas',\n 'on-success': 'Canvas',\n danger: 'CanvasText',\n 'danger-soft': 'Canvas',\n warning: 'CanvasText',\n 'warning-soft': 'Canvas',\n selected: 'Highlight',\n 'selected-soft': 'Canvas',\n ...palette('forced'),\n },\n};\n\n/**\n * Text (foreground) on background pairs the themes guarantee: 4.5:1, and 7:1 in `hc`. Built by a pure call, so a\n * bundle that does not use the list (the player) leaves it out.\n */\nexport const TEXT_PAIRS: readonly (readonly [ColorToken, ColorToken])[] = /* @__PURE__ */ (() => [\n ...(['canvas', 'surface', 'surface-raised'] as const).flatMap((bg) =>\n (['ink', 'ink-muted', 'accent', 'success', 'danger', 'warning', 'selected'] as const).map(\n (fg) => [fg, bg] as const,\n ),\n ),\n ...(['accent-soft', 'success-soft', 'danger-soft', 'warning-soft', 'selected-soft'] as const).flatMap(\n (bg) => [['ink', bg] as const, ['ink-muted', bg] as const],\n ),\n ['on-accent', 'accent'],\n ['on-success', 'success'],\n ['accent', 'accent-soft'],\n ['success', 'success-soft'],\n ['danger', 'danger-soft'],\n ['warning', 'warning-soft'],\n ['selected', 'selected-soft'],\n // The group palette: each colour on the page and surfaces; ink, ink-muted and the colour itself on its soft fill.\n ...PALETTE.flatMap((color) => [\n ...(['canvas', 'surface', 'surface-raised'] as const).map((bg) => [color, bg] as const),\n ...(['ink', 'ink-muted', color] as const).map((fg) => [fg, `${color}-soft`] as const),\n ]),\n])();\n\n/** Non-text pairs (control borders, focus rings, verdict borders) the themes guarantee: 3:1. Pure, as above. */\nexport const UI_PAIRS: readonly (readonly [ColorToken, ColorToken])[] = /* @__PURE__ */ (() =>\n (['canvas', 'surface', 'surface-raised'] as const).flatMap((bg) =>\n (['outline', 'focus', 'accent', 'success', 'danger', 'warning', 'selected'] as const).map(\n (fg) => [fg, bg] as const,\n ),\n ))();\n","/**\n * The built-in style templates, for `definePlayer({ styleTemplates })`, `createEngine({ styleTemplates })` and\n * `createAuthoring({ styleTemplates })`. Each sets the whole light and dark colour scheme (so any document template\n * combined with any component template keeps every contrast pair) and passes `checkStyleTemplate`.\n */\nimport en from './messages/en.json' with { type: 'json' };\nimport pl from './messages/pl.json' with { type: 'json' };\nimport type { StyleTemplateShape, TemplateCatalog, TemplateTheme } from './templates.js';\nimport { PALETTE, tokens } from './tokens.js';\n\n/**\n * The group palette of a theme. The built-in looks keep it as it is: it passes on their backgrounds too, and groups\n * keep their colours from one look to another.\n */\nfunction palette(theme: TemplateTheme): Readonly<Record<string, string>> {\n const colors = tokens.themes[theme];\n return Object.fromEntries(\n PALETTE.flatMap((color) => [\n [color, colors[color]],\n [`${color}-soft`, colors[`${color}-soft`]],\n ]),\n );\n}\n\n/** Label and description of one template from the flat catalogs (`<name>.label`, `<name>.description`). */\nfunction catalogs(name: string): readonly TemplateCatalog[] {\n const of = (locale: string, messages: Readonly<Record<string, string>>): TemplateCatalog => ({\n namespace: `astl.style.${name}`,\n locale,\n messages: { label: messages[`${name}.label`] ?? '', description: messages[`${name}.description`] ?? '' },\n });\n return [of('en', en), of('pl', pl)];\n}\n\nconst ROUNDED =\n 'ui-rounded, \"SF Pro Rounded\", \"Hiragino Maru Gothic ProN\", Nunito, \"Varela Round\", system-ui, sans-serif';\n/** Headings only: a bold rounded face that ships with macOS and Office, else the rounded stack. */\nconst ROUNDED_BOLD =\n 'ui-rounded, \"Arial Rounded MT Bold\", \"SF Pro Rounded\", Nunito, \"Varela Round\", system-ui, sans-serif';\nconst BOOK = '\"Iowan Old Style\", \"Palatino Linotype\", Palatino, \"Book Antiqua\", Georgia, serif';\n\n/** The built-in types with a `prompt` part: the notebook look sets their questions in the book face. */\nconst PROMPTS = [\n 'astl-categorise',\n 'astl-choice',\n 'astl-crossword',\n 'astl-hotspot',\n 'astl-image-drop',\n 'astl-image-label',\n 'astl-long-answer',\n 'astl-mark-words',\n 'astl-match',\n 'astl-memory',\n 'astl-order',\n 'astl-true-false',\n 'astl-word-search',\n];\n\n/** The \"funny\" look: rounder, bolder, more colourful, but calm enough for reading. */\nconst playful: StyleTemplateShape = {\n name: 'playful',\n version: 1,\n scopes: ['document', 'component'],\n messages: 'astl.style.playful',\n catalogs: catalogs('playful'),\n tokens: {\n 'font-body': ROUNDED,\n 'font-display': ROUNDED_BOLD,\n 'radius-s': '6px',\n 'radius-m': '16px',\n 'radius-l': '24px',\n 'outline-width': '3px',\n },\n light: {\n canvas: '#f5f0ff',\n surface: '#ffffff',\n 'surface-raised': '#ffffff',\n ink: '#1f1830',\n 'ink-muted': '#544a6b',\n line: '#d8ccf3',\n outline: '#7556b8',\n accent: '#7428c9',\n 'on-accent': '#ffffff',\n 'accent-soft': '#f0e6ff',\n focus: '#b3136a',\n success: '#17733f',\n 'success-soft': '#e3f5ea',\n 'on-success': '#ffffff',\n danger: '#b3261e',\n 'danger-soft': '#fdebea',\n warning: '#8a4b00',\n 'warning-soft': '#fff0db',\n selected: '#1f5bc6',\n 'selected-soft': '#e8effc',\n ...palette('light'),\n },\n dark: {\n canvas: '#150f1f',\n surface: '#211830',\n 'surface-raised': '#2a1f3d',\n ink: '#f3eeff',\n 'ink-muted': '#c3b6de',\n line: '#45385e',\n outline: '#a492cf',\n accent: '#c7a2ff',\n 'on-accent': '#1c0b36',\n 'accent-soft': '#33214f',\n focus: '#ff8fd0',\n success: '#70d498',\n 'success-soft': '#15301f',\n 'on-success': '#06200f',\n danger: '#ff8f85',\n 'danger-soft': '#3d1716',\n warning: '#f6bf66',\n 'warning-soft': '#3a290d',\n selected: '#8fb8ff',\n 'selected-soft': '#16284a',\n ...palette('dark'),\n },\n parts: {\n ...Object.fromEntries(\n ['astl-choice', 'astl-true-false', 'astl-match'].map((tag) => [\n tag,\n { option: { 'box-shadow': '0 3px 0 var(--astl-line)' } },\n ]),\n ),\n // The dropdown's list lifts like the cards, and its option in focus rounds. Its own parts only: a select's `option`\n // is also a button of the buttons variant, whose pick ring is an inset shadow.\n 'astl-select': {\n listbox: { 'box-shadow': '0 3px 0 var(--astl-line)' },\n 'option-active': { 'border-radius': 'var(--astl-radius-s)' },\n },\n },\n};\n\n/** Paper-like: cream sheets on a kraft desk, ink-blue text, a book face for questions, small corners. */\nconst notebook: StyleTemplateShape = {\n name: 'notebook',\n version: 1,\n scopes: ['document', 'component'],\n messages: 'astl.style.notebook',\n catalogs: catalogs('notebook'),\n tokens: {\n 'font-display': BOOK,\n 'radius-s': '2px',\n 'radius-m': '3px',\n 'radius-l': '4px',\n 'radius-pill': '4px',\n // Printed exercises separate the words to choose from: \"mat / hat\".\n 'separator-display': 'inline',\n },\n light: {\n canvas: '#ece5d4',\n surface: '#fffdf5',\n 'surface-raised': '#fffbee',\n ink: '#1c2333',\n 'ink-muted': '#485166',\n line: '#b4cbea',\n outline: '#5c6c8c',\n accent: '#1c4ba3',\n 'on-accent': '#ffffff',\n 'accent-soft': '#e5edfa',\n focus: '#2152b0',\n success: '#1d6b3a',\n 'success-soft': '#e6f2e6',\n 'on-success': '#ffffff',\n danger: '#ad2a22',\n 'danger-soft': '#fbe9e4',\n warning: '#844b00',\n 'warning-soft': '#fbeed6',\n selected: '#6c3796',\n 'selected-soft': '#f2e9f8',\n ...palette('light'),\n },\n dark: {\n canvas: '#12151b',\n surface: '#1b1f27',\n 'surface-raised': '#232833',\n ink: '#e8ecf4',\n 'ink-muted': '#adb5c6',\n line: '#384760',\n outline: '#8491a8',\n accent: '#9bbfff',\n 'on-accent': '#0c1a33',\n 'accent-soft': '#1d2a43',\n focus: '#a9c8ff',\n success: '#76cf92',\n 'success-soft': '#15301e',\n 'on-success': '#06200f',\n danger: '#ff8f85',\n 'danger-soft': '#3b1816',\n warning: '#f0be66',\n 'warning-soft': '#382a10',\n selected: '#d4abf2',\n 'selected-soft': '#2d2340',\n ...palette('dark'),\n },\n parts: Object.fromEntries(\n PROMPTS.map((tag) => [tag, { prompt: { 'font-family': 'var(--astl-font-display)' } }]),\n ),\n};\n\n/** `playful` and `notebook`, usable on documents and on every component. The default look is no template at all. */\nexport const builtInStyleTemplates: readonly StyleTemplateShape[] = [playful, notebook];\n","import { type ColorScheme, type Theme, tokens } from './tokens.js';\n\n/** `selector[attr]`, written `:host([attr])` for shadow hosts (`:host[attr]` never matches). */\nfunction withAttribute(selector: string, attribute: string): string {\n if (selector === ':host') return `:host(${attribute})`;\n const host = /^:host\\((.*)\\)$/.exec(selector);\n if (host) return `:host(${host[1]}${attribute})`;\n return `${selector}${attribute}`;\n}\n\nfunction declarations(values: Readonly<Record<string, string>>): string {\n return Object.entries(values)\n .map(([name, value]) => ` --astl-${name}: ${value};\\n`)\n .join('');\n}\n\nfunction rule(selector: string, body: string): string {\n return `${selector} {\\n${body}}\\n`;\n}\n\nfunction theme(name: Theme, scheme: 'light' | 'dark', values: ColorScheme): string {\n return ` color-scheme: ${scheme};\\n${declarations(values)}${declarations(tokens.themeScale[name])}`;\n}\n\n/**\n * The token stylesheet for `selector` (comma-separated selectors allowed, `:host` included):\n * light by default, `data-theme=\"dark\" | \"hc\"` themes, `data-theme=\"auto\"` following `prefers-color-scheme`,\n * system colours under `forced-colors: active` and no motion under `prefers-reduced-motion: reduce`.\n */\nexport function tokensCss(selector: string): string {\n const parts = selector\n .split(',')\n .map((s) => s.trim())\n .filter((s) => s !== '');\n const base = parts.join(', ');\n const themed = (value: string) => parts.map((s) => withAttribute(s, `[data-theme=\"${value}\"]`)).join(', ');\n // `[data-theme]` gives the overrides below the same specificity as the theme rules, so they win by order.\n const any = `${base}, ${parts.map((s) => withAttribute(s, '[data-theme]')).join(', ')}`;\n const { light, dark, hc } = tokens.themes;\n return [\n rule(base, `${declarations(tokens.scale)}${theme('light', 'light', light)}`),\n rule(themed('dark'), theme('dark', 'dark', dark)),\n rule(themed('hc'), theme('hc', 'light', hc)),\n `@media (prefers-color-scheme: dark) {\\n${rule(themed('auto'), theme('dark', 'dark', dark))}}\\n`,\n `@media (forced-colors: active) {\\n${rule(any, declarations(tokens.forced))}}\\n`,\n `@media (prefers-reduced-motion: reduce) {\\n${rule(any, ' --astl-duration-fast: 0ms;\\n --astl-duration-normal: 0ms;\\n')}}\\n`,\n ].join('');\n}\n","/**\n * Style templates on the token side: the shape of `@astl/core`'s StyleTemplate restated structurally (this\n * package depends on nothing; a type-checked test keeps both in step), WCAG contrast, the colours a theme gets with\n * templates applied, and `checkStyleTemplate`, the check built-in templates pass and hosts can run in CI.\n */\nimport { type ColorScheme, type ColorToken, TEXT_PAIRS, type TokenName, tokens, UI_PAIRS } from './tokens.js';\n\n/** = core `STYLE_TEMPLATE_NAME`: lowercase kebab-case, 1 to 40 characters, starting with a letter. */\nexport const TEMPLATE_NAME: RegExp = /^(?=.{1,40}$)[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/;\n\n/** = core `StyleScope`. */\nexport type TemplateScope = 'document' | 'component';\n\n/** = core `MessageCatalog`. */\nexport interface TemplateCatalog {\n readonly namespace: string;\n readonly locale: string;\n readonly messages: Readonly<Record<string, string>>;\n}\n\n/** The shape of core's `StyleTemplate` (see `@astl/core` style.ts for the meaning of each field). */\nexport interface StyleTemplateShape {\n readonly name: string;\n readonly version: number;\n readonly scopes: readonly TemplateScope[];\n readonly components?: readonly string[];\n readonly messages: string;\n readonly catalogs?: readonly TemplateCatalog[];\n readonly tokens?: Readonly<Record<string, string>>;\n readonly light?: Readonly<Record<string, string>>;\n readonly dark?: Readonly<Record<string, string>>;\n readonly parts?: Readonly<Record<string, Readonly<Record<string, Readonly<Record<string, string>>>>>>;\n}\n\n/** Themes a template changes: never `hc`. */\nexport type TemplateTheme = 'light' | 'dark';\n\n/**\n * CSS properties a template may set on `::part()`: shape, spacing and type. Outer `::part()` rules beat a component's\n * own styles, so borders, outlines, colours, display and text size stay out: they carry verdicts, focus rings,\n * selection and contrast. The player drops every other property.\n */\nexport const PART_PROPERTIES: ReadonlySet<string> = new Set([\n 'border-radius',\n 'border-start-start-radius',\n 'border-start-end-radius',\n 'border-end-start-radius',\n 'border-end-end-radius',\n 'box-shadow',\n 'padding',\n 'padding-block',\n 'padding-block-start',\n 'padding-block-end',\n 'padding-inline',\n 'padding-inline-start',\n 'padding-inline-end',\n 'gap',\n 'row-gap',\n 'column-gap',\n 'font-family',\n 'font-style',\n 'letter-spacing',\n 'line-height',\n]);\n\n/** Token names (without `--astl-`): what templates may override. */\n// Pure, so a bundle that only takes isSafeStyleValue and PART_PROPERTIES from here (the player) drops them.\nconst TOKEN_NAMES: ReadonlySet<string> = /* @__PURE__ */ (() =>\n new Set<TokenName>([\n ...(Object.keys(tokens.scale) as TokenName[]),\n ...(Object.keys(tokens.themes.light) as TokenName[]),\n ...(Object.keys(tokens.themeScale.light) as TokenName[]),\n ]))();\nconst COLOR_NAMES: ReadonlySet<string> = /* @__PURE__ */ (() => new Set(Object.keys(tokens.themes.light)))();\n\n/** Tokens with an accessible floor, in px (1rem = 16px): 44px targets, 2px focus rings, 14px readable text. */\nconst MINIMUM_PX: Readonly<Record<string, number>> = {\n 'target-min': 44,\n 'focus-width': 2,\n 'outline-width': 1,\n 'size-content': 14,\n 'size-ui': 14,\n 'size-small': 14,\n};\n\n/** `12px` or `0.75rem` in px, or null for any other form. */\nfunction pixels(value: string): number | null {\n const match = /^(\\d+(?:\\.\\d+)?|\\.\\d+)(px|rem)$/.exec(value.trim());\n return match === null ? null : Number(match[1]) * (match[2] === 'rem' ? 16 : 1);\n}\n\n/** Backgrounds a component shows through where it paints none (its text sits on the enclosing scope's colours). */\nconst PAGE_BACKGROUNDS: ReadonlySet<ColorToken> = new Set(['canvas', 'surface', 'surface-raised']);\n\nconst TAG = /^[a-z][a-z0-9]*-[a-z0-9-]*$/;\nconst PART_NAME = /^[a-z][a-z0-9-]*$/;\n\n/**\n * Whether a value can go into a generated declaration without ending it, its rule or a `<style>`: no `{ } ; < >`,\n * no comment opener, no backslash (an escape could swallow the `;` after it), no line breaks, closed quotes and\n * balanced `( )` and `[ ]` outside them (an open `calc(` would swallow everything after it), not blank.\n */\nexport function isSafeStyleValue(value: string): boolean {\n if (typeof value !== 'string' || value.trim() === '' || /[{};<>\\\\\\n\\r\\f]|\\/\\*/.test(value)) return false;\n const open: string[] = [];\n let quote: string | null = null;\n for (const ch of value) {\n if (quote !== null) {\n if (ch === quote) quote = null;\n } else if (ch === '\"' || ch === \"'\") {\n quote = ch;\n } else if (ch === '(' || ch === '[') {\n open.push(ch === '(' ? ')' : ']');\n } else if ((ch === ')' || ch === ']') && open.pop() !== ch) {\n return false;\n }\n }\n return quote === null && open.length === 0;\n}\n\n/** `#rgb` or `#rrggbb` as 0-255 channels, or null. */\nfunction channels(color: string): readonly [number, number, number] | null {\n const hex = /^#([0-9a-f]{3}|[0-9a-f]{6})$/i.exec(color.trim())?.[1];\n if (hex === undefined) return null;\n const full = hex.length === 3 ? [...hex].map((c) => c + c).join('') : hex;\n return [0, 2, 4].map((i) => Number.parseInt(full.slice(i, i + 2), 16)) as [number, number, number];\n}\n\n/** WCAG 2 relative luminance. */\nfunction luminance([r, g, b]: readonly [number, number, number]): number {\n const linear = (c: number) => {\n const s = c / 255;\n return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;\n };\n return 0.2126 * linear(r) + 0.7152 * linear(g) + 0.0722 * linear(b);\n}\n\n/** WCAG 2 contrast ratio (1 to 21) of two `#rgb` or `#rrggbb` colours. Throws a TypeError for other formats. */\nexport function contrastRatio(a: string, b: string): number {\n const x = channels(a);\n const y = channels(b);\n if (x === null || y === null) throw new TypeError(`Not a #rgb or #rrggbb colour: ${x === null ? a : b}`);\n const [hi, lo] = [luminance(x), luminance(y)].sort((p, q) => q - p) as [number, number];\n return (hi + 0.05) / (lo + 0.05);\n}\n\n/**\n * The colours of the light or dark theme with templates applied in order, e.g. `[documentTemplate,\n * componentTemplate]`: each template's `tokens`, then its `light` or `dark` values. Non-colour tokens are ignored.\n */\nexport function templateColors(theme: TemplateTheme, templates: readonly StyleTemplateShape[]): ColorScheme {\n const colors: Record<string, string> = { ...tokens.themes[theme] };\n for (const template of templates) {\n for (const [name, value] of Object.entries({ ...template.tokens, ...template[theme] })) {\n if (COLOR_NAMES.has(name)) colors[name] = value;\n }\n }\n return colors as ColorScheme;\n}\n\nexport interface StyleTemplateProblem {\n readonly kind:\n | 'name'\n | 'version'\n | 'scopes'\n | 'components'\n | 'messages'\n | 'token'\n | 'value'\n | 'color'\n | 'property'\n | 'part'\n | 'text-contrast'\n | 'ui-contrast'\n | 'pick-distance';\n /** Where, e.g. `name`, `dark.ink`, `parts.astl-choice.option.box-shadow`, `light: ink-muted on surface`. */\n readonly at: string;\n /** For developers (like `checkCatalog` in core): English, never shown to students or authors. */\n readonly detail: string;\n}\n\nexport interface CheckStyleTemplateOptions {\n /** Component manifests (tag and `cssParts` are enough): `components` and `parts` must name their tags and parts. */\n readonly manifests?: readonly { readonly tag: string; readonly cssParts: readonly string[] }[];\n /**\n * Templates already applied around this one, e.g. the document's when checking a component template. Default\n * none: the template on top of the plain light and dark themes.\n */\n readonly within?: readonly StyleTemplateShape[];\n}\n\n/**\n * How far (CIEDE2000) a pick stays from the verdict colours, so a picked box never looks checked: its edge\n * (`selected`) from `success` and `danger`, its fill (`selected-soft`) from their soft fills. A pick's edge sits where a\n * verdict's edge will; near-white fills differ less, hence the lower bound for them.\n */\nexport const PICK_DISTANCE = 25;\nexport const PICK_FILL_DISTANCE = 7;\nconst PICKS = [\n ['selected', 'success', PICK_DISTANCE],\n ['selected', 'danger', PICK_DISTANCE],\n ['selected-soft', 'success-soft', PICK_FILL_DISTANCE],\n ['selected-soft', 'danger-soft', PICK_FILL_DISTANCE],\n] as const;\n\n/** `#rgb` or `#rrggbb` to CIELAB (D65), through linear-light sRGB. */\nfunction lab(color: readonly [number, number, number]): readonly [number, number, number] {\n const [r, g, b] = color.map((c) => {\n const s = c / 255;\n return s <= 0.04045 ? s / 12.92 : ((s + 0.055) / 1.055) ** 2.4;\n }) as [number, number, number];\n const xyz = [\n (0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / 0.95047,\n 0.2126729 * r + 0.7151522 * g + 0.072175 * b,\n (0.0193339 * r + 0.119192 * g + 0.9503041 * b) / 1.08883,\n ];\n const [fx, fy, fz] = xyz.map((t) => (t > 216 / 24389 ? Math.cbrt(t) : ((24389 / 27) * t + 16) / 116)) as [\n number,\n number,\n number,\n ];\n return [116 * fy - 16, 500 * (fx - fy), 200 * (fy - fz)];\n}\n\n/**\n * CIEDE2000 colour difference of two `#rgb` or `#rrggbb` colours (kL = kC = kH = 1), after G. Sharma, W. Wu and E. N.\n * Dalal (2005), as the palette tests check it. Throws a TypeError for other formats.\n */\nexport function colorDistance(a: string, b: string): number {\n const x = channels(a);\n const y = channels(b);\n if (x === null || y === null) throw new TypeError(`Not a #rgb or #rrggbb colour: ${x === null ? a : b}`);\n const [L1, a1, b1] = lab(x);\n const [L2, a2, b2] = lab(y);\n const rad = Math.PI / 180;\n const meanC = (Math.hypot(a1, b1) + Math.hypot(a2, b2)) / 2;\n const G = 0.5 * (1 - Math.sqrt(meanC ** 7 / (meanC ** 7 + 25 ** 7)));\n const [ap1, ap2] = [(1 + G) * a1, (1 + G) * a2];\n const [C1, C2] = [Math.hypot(ap1, b1), Math.hypot(ap2, b2)];\n const hue = (bb: number, ap: number) => (bb === 0 && ap === 0 ? 0 : (Math.atan2(bb, ap) / rad + 360) % 360);\n const [h1, h2] = [hue(b1, ap1), hue(b2, ap2)];\n let dh = 0;\n if (C1 * C2 !== 0) dh = h2 - h1 > 180 ? h2 - h1 - 360 : h2 - h1 < -180 ? h2 - h1 + 360 : h2 - h1;\n const dH = 2 * Math.sqrt(C1 * C2) * Math.sin((dh / 2) * rad);\n const L = (L1 + L2) / 2;\n const C = (C1 + C2) / 2;\n let h = h1 + h2;\n if (C1 * C2 !== 0) h = Math.abs(h1 - h2) <= 180 ? h / 2 : h < 360 ? (h + 360) / 2 : (h - 360) / 2;\n const T =\n 1 -\n 0.17 * Math.cos((h - 30) * rad) +\n 0.24 * Math.cos(2 * h * rad) +\n 0.32 * Math.cos((3 * h + 6) * rad) -\n 0.2 * Math.cos((4 * h - 63) * rad);\n const RT =\n -2 * Math.sqrt(C ** 7 / (C ** 7 + 25 ** 7)) * Math.sin(60 * Math.exp(-(((h - 275) / 25) ** 2)) * rad);\n const SL = 1 + (0.015 * (L - 50) ** 2) / Math.sqrt(20 + (L - 50) ** 2);\n const SC = 1 + 0.045 * C;\n const SH = 1 + 0.015 * C * T;\n return Math.sqrt(\n ((L2 - L1) / SL) ** 2 + ((C2 - C1) / SC) ** 2 + (dH / SH) ** 2 + RT * ((C2 - C1) / SC) * (dH / SH),\n );\n}\n\n/** The pairs every template keeps, with their minimum ratio (WCAG 2.2 AA: 1.4.3 text, 1.4.11 non-text). */\nconst CONTRAST = [\n ['text-contrast', TEXT_PAIRS, 4.5],\n ['ui-contrast', UI_PAIRS, 3],\n] as const;\n\n/**\n * Problems of a template: name, version, scopes, component tags, messages, token names, values that are unsafe,\n * colours that are not `#rgb` / `#rrggbb`, targets, focus rings, control borders and text sizes under their\n * accessible minimum (MINIMUM_PX), part properties and names, picks next to the verdict colours (PICK_DISTANCE),\n * and contrast. Contrast: every TEXT_PAIRS pair at\n * least 4.5:1 and every UI_PAIRS pair at least 3:1 in light and dark after applying the template (on top of\n * `within`); for templates with the `component` scope also against the enclosing scope's backgrounds, which show\n * through where a component paints none. An empty list means the template is fine.\n */\nexport function checkStyleTemplate(\n template: StyleTemplateShape,\n options: CheckStyleTemplateOptions = {},\n): StyleTemplateProblem[] {\n const problems: StyleTemplateProblem[] = [];\n const add = (kind: StyleTemplateProblem['kind'], at: string, detail: string) =>\n problems.push({ kind, at, detail });\n const known = options.manifests === undefined ? null : new Map(options.manifests.map((m) => [m.tag, m]));\n\n if (!TEMPLATE_NAME.test(template.name)) {\n add('name', 'name', `\"${template.name}\" is not lowercase kebab-case of 1 to 40 characters`);\n }\n if (!Number.isInteger(template.version) || template.version < 1) {\n add('version', 'version', 'version must be a positive integer');\n }\n const scopes = template.scopes ?? [];\n if (\n scopes.length === 0 ||\n new Set(scopes).size !== scopes.length ||\n scopes.some((s) => s !== 'document' && s !== 'component')\n ) {\n add('scopes', 'scopes', 'scopes must list \"document\" and/or \"component\", each once');\n }\n for (const tag of template.components ?? []) {\n if (!TAG.test(tag)) add('components', `components.${tag}`, `\"${tag}\" is not a custom element name`);\n else if (known !== null && !known.has(tag))\n add('components', `components.${tag}`, `no manifest for ${tag}`);\n }\n if (template.components !== undefined && template.components.length === 0) {\n add('components', 'components', 'leave components out instead of listing none');\n }\n\n if (typeof template.messages !== 'string' || template.messages === '') {\n add('messages', 'messages', 'messages must name the i18n namespace of the label and description');\n }\n for (const catalog of template.catalogs ?? []) {\n const at = `catalogs.${catalog.locale}`;\n if (catalog.namespace !== template.messages) {\n add('messages', at, `namespace ${catalog.namespace} is not ${template.messages}`);\n }\n for (const key of ['label', 'description']) {\n const text = Object.hasOwn(catalog.messages, key) ? catalog.messages[key] : undefined;\n if (typeof text !== 'string' || text.trim() === '')\n add('messages', `${at}.${key}`, `${key} is missing`);\n }\n }\n\n let colorsOk = true;\n for (const group of ['tokens', 'light', 'dark'] as const) {\n for (const [name, value] of Object.entries(template[group] ?? {})) {\n const at = `${group}.${name}`;\n if (!TOKEN_NAMES.has(name)) add('token', at, `--astl-${name} is not a token`);\n if (!isSafeStyleValue(value)) {\n add('value', at, `unsafe or empty value: ${JSON.stringify(value)}`);\n if (COLOR_NAMES.has(name)) colorsOk = false;\n } else if (COLOR_NAMES.has(name) && channels(value) === null) {\n add('color', at, `${value} is not #rgb or #rrggbb, so its contrast cannot be checked`);\n colorsOk = false;\n } else if (Object.hasOwn(MINIMUM_PX, name)) {\n const min = MINIMUM_PX[name] ?? 0;\n const px = pixels(value);\n if (px === null) add('value', at, `write px or rem, so the minimum of ${min}px can be checked`);\n else if (px < min) add('value', at, `${value} is below the accessible minimum of ${min}px`);\n }\n }\n }\n\n for (const [tag, byPart] of Object.entries(template.parts ?? {})) {\n const manifest = known?.get(tag);\n if (!TAG.test(tag)) add('part', `parts.${tag}`, `\"${tag}\" is not a custom element name`);\n else if (known !== null && manifest === undefined) add('part', `parts.${tag}`, `no manifest for ${tag}`);\n for (const [part, declarations] of Object.entries(byPart)) {\n const at = `parts.${tag}.${part}`;\n if (!PART_NAME.test(part)) add('part', at, `\"${part}\" is not a part name`);\n else if (manifest !== undefined && !manifest.cssParts.includes(part)) {\n add('part', at, `${tag} has no part \"${part}\" (cssParts: ${manifest.cssParts.join(', ')})`);\n }\n for (const [property, value] of Object.entries(declarations)) {\n if (!PART_PROPERTIES.has(property)) {\n add('property', `${at}.${property}`, `${property} is not allowed on parts (see PART_PROPERTIES)`);\n }\n if (!isSafeStyleValue(value)) {\n add('value', `${at}.${property}`, `unsafe or empty value: ${JSON.stringify(value)}`);\n }\n }\n }\n }\n\n const within = options.within ?? [];\n const component = scopes.includes('component');\n for (const theme of colorsOk ? (['light', 'dark'] as const) : []) {\n const enclosing = templateColors(theme, within);\n const colors = templateColors(theme, [...within, template]);\n if (Object.values(enclosing).some((c) => channels(c) === null)) {\n add('color', `within (${theme})`, 'a template in within has a colour that is not #rgb or #rrggbb');\n continue;\n }\n for (const [pick, verdict, min] of PICKS) {\n const d = colorDistance(colors[pick], colors[verdict]);\n if (d < min)\n add('pick-distance', `${theme}: ${pick} and ${verdict}`, `${d.toFixed(1)} apart, needs ${min}`);\n }\n for (const [kind, list, min] of CONTRAST) {\n for (const [fg, bg] of list) {\n const own = contrastRatio(colors[fg], colors[bg]);\n if (own < min) add(kind, `${theme}: ${fg} on ${bg}`, `${own.toFixed(2)}:1, needs ${min}:1`);\n if (!component || !PAGE_BACKGROUNDS.has(bg)) continue;\n const around = contrastRatio(colors[fg], enclosing[bg]);\n if (around < min) {\n add(kind, `${theme}: ${fg} on the enclosing ${bg}`, `${around.toFixed(2)}:1, needs ${min}:1`);\n }\n }\n }\n }\n return problems;\n}\n","/**\n * The built-in player elements, for `definePlayer({ elements: builtInElements })`. Lazy: a type's element (with its\n * manifest and catalogs) is imported the first time a view contains its tag, so a page loads only the types it plays.\n * Eager users load them all: `await Promise.all(builtInElements.map((e) => e.load()))`. Player side only: nothing\n * here may import the engine or a definition, and no element statically.\n */\nimport type { LazyElement } from '@astl/player';\n\nexport const builtInElements: readonly LazyElement[] = [\n { tag: 'astl-gap', load: async () => (await import('./gap/element.js')).gapElement },\n { tag: 'astl-choice', load: async () => (await import('./choice/element.js')).choiceElement },\n { tag: 'astl-select', load: async () => (await import('./select/element.js')).selectElement },\n { tag: 'astl-true-false', load: async () => (await import('./true-false/element.js')).trueFalseElement },\n { tag: 'astl-order', load: async () => (await import('./order/element.js')).orderElement },\n { tag: 'astl-categorise', load: async () => (await import('./categorise/element.js')).categoriseElement },\n { tag: 'astl-match', load: async () => (await import('./match/element.js')).matchElement },\n { tag: 'astl-word-bank', load: async () => (await import('./word-bank/element.js')).wordBankElement },\n { tag: 'astl-drop', load: async () => (await import('./drop/element.js')).dropElement },\n { tag: 'astl-word-search', load: async () => (await import('./word-search/element.js')).wordSearchElement },\n { tag: 'astl-memory', load: async () => (await import('./memory/element.js')).memoryElement },\n { tag: 'astl-crossword', load: async () => (await import('./crossword/element.js')).crosswordElement },\n { tag: 'astl-flash-cards', load: async () => (await import('./flash-cards/element.js')).flashCardsElement },\n { tag: 'astl-long-answer', load: async () => (await import('./long-answer/element.js')).longAnswerElement },\n { tag: 'astl-mark-words', load: async () => (await import('./mark-words/element.js')).markWordsElement },\n { tag: 'astl-callout', load: async () => (await import('./callout/element.js')).calloutElement },\n { tag: 'astl-hotspot', load: async () => (await import('./hotspot/element.js')).hotspotElement },\n { tag: 'astl-image-drop', load: async () => (await import('./image-drop/element.js')).imageDropElement },\n { tag: 'astl-image-label', load: async () => (await import('./image-label/element.js')).imageLabelElement },\n { tag: 'astl-video', load: async () => (await import('./video/element.js')).videoElement },\n { tag: 'astl-audio', load: async () => (await import('./audio/element.js')).audioElement },\n];\n","/**\n * @license\n * Copyright 2019 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t=globalThis,e=t.ShadowRoot&&(void 0===t.ShadyCSS||t.ShadyCSS.nativeShadow)&&\"adoptedStyleSheets\"in Document.prototype&&\"replace\"in CSSStyleSheet.prototype,s=Symbol(),o=new WeakMap;class n{constructor(t,e,o){if(this._$cssResult$=!0,o!==s)throw Error(\"CSSResult is not constructable. Use `unsafeCSS` or `css` instead.\");this.cssText=t,this.t=e}get styleSheet(){let t=this.o;const s=this.t;if(e&&void 0===t){const e=void 0!==s&&1===s.length;e&&(t=o.get(s)),void 0===t&&((this.o=t=new CSSStyleSheet).replaceSync(this.cssText),e&&o.set(s,t))}return t}toString(){return this.cssText}}const r=t=>new n(\"string\"==typeof t?t:t+\"\",void 0,s),i=(t,...e)=>{const o=1===t.length?t[0]:e.reduce((e,s,o)=>e+(t=>{if(!0===t._$cssResult$)return t.cssText;if(\"number\"==typeof t)return t;throw Error(\"Value passed to 'css' function must be a 'css' function result: \"+t+\". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.\")})(s)+t[o+1],t[0]);return new n(o,t,s)},S=(s,o)=>{if(e)s.adoptedStyleSheets=o.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(const e of o){const o=document.createElement(\"style\"),n=t.litNonce;void 0!==n&&o.setAttribute(\"nonce\",n),o.textContent=e.cssText,s.appendChild(o)}},c=e?t=>t:t=>t instanceof CSSStyleSheet?(t=>{let e=\"\";for(const s of t.cssRules)e+=s.cssText;return r(e)})(t):t;export{n as CSSResult,S as adoptStyles,i as css,c as getCompatibleStyle,e as supportsAdoptingStyleSheets,r as unsafeCSS};\n//# sourceMappingURL=css-tag.js.map\n","import{getCompatibleStyle as t,adoptStyles as s}from\"./css-tag.js\";export{CSSResult,css,supportsAdoptingStyleSheets,unsafeCSS}from\"./css-tag.js\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const{is:i,defineProperty:e,getOwnPropertyDescriptor:h,getOwnPropertyNames:r,getOwnPropertySymbols:o,getPrototypeOf:n}=Object,a=globalThis,c=a.trustedTypes,l=c?c.emptyScript:\"\",p=a.reactiveElementPolyfillSupport,d=(t,s)=>t,u={toAttribute(t,s){switch(s){case Boolean:t=t?l:null;break;case Object:case Array:t=null==t?t:JSON.stringify(t)}return t},fromAttribute(t,s){let i=t;switch(s){case Boolean:i=null!==t;break;case Number:i=null===t?null:Number(t);break;case Object:case Array:try{i=JSON.parse(t)}catch(t){i=null}}return i}},f=(t,s)=>!i(t,s),b={attribute:!0,type:String,converter:u,reflect:!1,useDefault:!1,hasChanged:f};Symbol.metadata??=Symbol(\"metadata\"),a.litPropertyMetadata??=new WeakMap;class y extends HTMLElement{static addInitializer(t){this._$Ei(),(this.l??=[]).push(t)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(t,s=b){if(s.state&&(s.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(t)&&((s=Object.create(s)).wrapped=!0),this.elementProperties.set(t,s),!s.noAccessor){const i=Symbol(),h=this.getPropertyDescriptor(t,i,s);void 0!==h&&e(this.prototype,t,h)}}static getPropertyDescriptor(t,s,i){const{get:e,set:r}=h(this.prototype,t)??{get(){return this[s]},set(t){this[s]=t}};return{get:e,set(s){const h=e?.call(this);r?.call(this,s),this.requestUpdate(t,h,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(t){return this.elementProperties.get(t)??b}static _$Ei(){if(this.hasOwnProperty(d(\"elementProperties\")))return;const t=n(this);t.finalize(),void 0!==t.l&&(this.l=[...t.l]),this.elementProperties=new Map(t.elementProperties)}static finalize(){if(this.hasOwnProperty(d(\"finalized\")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(d(\"properties\"))){const t=this.properties,s=[...r(t),...o(t)];for(const i of s)this.createProperty(i,t[i])}const t=this[Symbol.metadata];if(null!==t){const s=litPropertyMetadata.get(t);if(void 0!==s)for(const[t,i]of s)this.elementProperties.set(t,i)}this._$Eh=new Map;for(const[t,s]of this.elementProperties){const i=this._$Eu(t,s);void 0!==i&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(s){const i=[];if(Array.isArray(s)){const e=new Set(s.flat(1/0).reverse());for(const s of e)i.unshift(t(s))}else void 0!==s&&i.push(t(s));return i}static _$Eu(t,s){const i=s.attribute;return!1===i?void 0:\"string\"==typeof i?i:\"string\"==typeof t?t.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(t=>this.enableUpdating=t),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(t=>t(this))}addController(t){(this._$EO??=new Set).add(t),void 0!==this.renderRoot&&this.isConnected&&t.hostConnected?.()}removeController(t){this._$EO?.delete(t)}_$E_(){const t=new Map,s=this.constructor.elementProperties;for(const i of s.keys())this.hasOwnProperty(i)&&(t.set(i,this[i]),delete this[i]);t.size>0&&(this._$Ep=t)}createRenderRoot(){const t=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return s(t,this.constructor.elementStyles),t}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(t=>t.hostConnected?.())}enableUpdating(t){}disconnectedCallback(){this._$EO?.forEach(t=>t.hostDisconnected?.())}attributeChangedCallback(t,s,i){this._$AK(t,i)}_$ET(t,s){const i=this.constructor.elementProperties.get(t),e=this.constructor._$Eu(t,i);if(void 0!==e&&!0===i.reflect){const h=(void 0!==i.converter?.toAttribute?i.converter:u).toAttribute(s,i.type);this._$Em=t,null==h?this.removeAttribute(e):this.setAttribute(e,h),this._$Em=null}}_$AK(t,s){const i=this.constructor,e=i._$Eh.get(t);if(void 0!==e&&this._$Em!==e){const t=i.getPropertyOptions(e),h=\"function\"==typeof t.converter?{fromAttribute:t.converter}:void 0!==t.converter?.fromAttribute?t.converter:u;this._$Em=e;const r=h.fromAttribute(s,t.type);this[e]=r??this._$Ej?.get(e)??r,this._$Em=null}}requestUpdate(t,s,i,e=!1,h){if(void 0!==t){const r=this.constructor;if(!1===e&&(h=this[t]),i??=r.getPropertyOptions(t),!((i.hasChanged??f)(h,s)||i.useDefault&&i.reflect&&h===this._$Ej?.get(t)&&!this.hasAttribute(r._$Eu(t,i))))return;this.C(t,s,i)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(t,s,{useDefault:i,reflect:e,wrapped:h},r){i&&!(this._$Ej??=new Map).has(t)&&(this._$Ej.set(t,r??s??this[t]),!0!==h||void 0!==r)||(this._$AL.has(t)||(this.hasUpdated||i||(s=void 0),this._$AL.set(t,s)),!0===e&&this._$Em!==t&&(this._$Eq??=new Set).add(t))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}const t=this.scheduleUpdate();return null!=t&&await t,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[t,s]of this._$Ep)this[t]=s;this._$Ep=void 0}const t=this.constructor.elementProperties;if(t.size>0)for(const[s,i]of t){const{wrapped:t}=i,e=this[s];!0!==t||this._$AL.has(s)||void 0===e||this.C(s,void 0,i,e)}}let t=!1;const s=this._$AL;try{t=this.shouldUpdate(s),t?(this.willUpdate(s),this._$EO?.forEach(t=>t.hostUpdate?.()),this.update(s)):this._$EM()}catch(s){throw t=!1,this._$EM(),s}t&&this._$AE(s)}willUpdate(t){}_$AE(t){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(t)),this.updated(t)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(t){return!0}update(t){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(t){}firstUpdated(t){}}y.elementStyles=[],y.shadowRootOptions={mode:\"open\"},y[d(\"elementProperties\")]=new Map,y[d(\"finalized\")]=new Map,p?.({ReactiveElement:y}),(a.reactiveElementVersions??=[]).push(\"2.1.2\");export{y as ReactiveElement,s as adoptStyles,u as defaultConverter,t as getCompatibleStyle,f as notEqual};\n//# sourceMappingURL=reactive-element.js.map\n","/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */\nconst t=globalThis,i=t=>t,s=t.trustedTypes,e=s?s.createPolicy(\"lit-html\",{createHTML:t=>t}):void 0,h=\"$lit$\",o=`lit$${Math.random().toFixed(9).slice(2)}$`,n=\"?\"+o,r=`<${n}>`,l=document,c=()=>l.createComment(\"\"),a=t=>null===t||\"object\"!=typeof t&&\"function\"!=typeof t,u=Array.isArray,d=t=>u(t)||\"function\"==typeof t?.[Symbol.iterator],f=\"[ \\t\\n\\f\\r]\",v=/<(?:(!--|\\/[^a-zA-Z])|(\\/?[a-zA-Z][^>\\s]*)|(\\/?$))/g,_=/-->/g,m=/>/g,p=RegExp(`>|${f}(?:([^\\\\s\"'>=/]+)(${f}*=${f}*(?:[^ \\t\\n\\f\\r\"'\\`<>=]|(\"|')|))|$)`,\"g\"),g=/'/g,$=/\"/g,y=/^(?:script|style|textarea|title)$/i,x=t=>(i,...s)=>({_$litType$:t,strings:i,values:s}),b=x(1),w=x(2),T=x(3),E=Symbol.for(\"lit-noChange\"),A=Symbol.for(\"lit-nothing\"),C=new WeakMap,P=l.createTreeWalker(l,129);function V(t,i){if(!u(t)||!t.hasOwnProperty(\"raw\"))throw Error(\"invalid template strings array\");return void 0!==e?e.createHTML(i):i}const N=(t,i)=>{const s=t.length-1,e=[];let n,l=2===i?\"<svg>\":3===i?\"<math>\":\"\",c=v;for(let i=0;i<s;i++){const s=t[i];let a,u,d=-1,f=0;for(;f<s.length&&(c.lastIndex=f,u=c.exec(s),null!==u);)f=c.lastIndex,c===v?\"!--\"===u[1]?c=_:void 0!==u[1]?c=m:void 0!==u[2]?(y.test(u[2])&&(n=RegExp(\"</\"+u[2],\"g\")),c=p):void 0!==u[3]&&(c=p):c===p?\">\"===u[0]?(c=n??v,d=-1):void 0===u[1]?d=-2:(d=c.lastIndex-u[2].length,a=u[1],c=void 0===u[3]?p:'\"'===u[3]?$:g):c===$||c===g?c=p:c===_||c===m?c=v:(c=p,n=void 0);const x=c===p&&t[i+1].startsWith(\"/>\")?\" \":\"\";l+=c===v?s+r:d>=0?(e.push(a),s.slice(0,d)+h+s.slice(d)+o+x):s+o+(-2===d?i:x)}return[V(t,l+(t[s]||\"<?>\")+(2===i?\"</svg>\":3===i?\"</math>\":\"\")),e]};class S{constructor({strings:t,_$litType$:i},e){let r;this.parts=[];let l=0,a=0;const u=t.length-1,d=this.parts,[f,v]=N(t,i);if(this.el=S.createElement(f,e),P.currentNode=this.el.content,2===i||3===i){const t=this.el.content.firstChild;t.replaceWith(...t.childNodes)}for(;null!==(r=P.nextNode())&&d.length<u;){if(1===r.nodeType){if(r.hasAttributes())for(const t of r.getAttributeNames())if(t.endsWith(h)){const i=v[a++],s=r.getAttribute(t).split(o),e=/([.?@])?(.*)/.exec(i);d.push({type:1,index:l,name:e[2],strings:s,ctor:\".\"===e[1]?I:\"?\"===e[1]?L:\"@\"===e[1]?z:H}),r.removeAttribute(t)}else t.startsWith(o)&&(d.push({type:6,index:l}),r.removeAttribute(t));if(y.test(r.tagName)){const t=r.textContent.split(o),i=t.length-1;if(i>0){r.textContent=s?s.emptyScript:\"\";for(let s=0;s<i;s++)r.append(t[s],c()),P.nextNode(),d.push({type:2,index:++l});r.append(t[i],c())}}}else if(8===r.nodeType)if(r.data===n)d.push({type:2,index:l});else{let t=-1;for(;-1!==(t=r.data.indexOf(o,t+1));)d.push({type:7,index:l}),t+=o.length-1}l++}}static createElement(t,i){const s=l.createElement(\"template\");return s.innerHTML=t,s}}function M(t,i,s=t,e){if(i===E)return i;let h=void 0!==e?s._$Co?.[e]:s._$Cl;const o=a(i)?void 0:i._$litDirective$;return h?.constructor!==o&&(h?._$AO?.(!1),void 0===o?h=void 0:(h=new o(t),h._$AT(t,s,e)),void 0!==e?(s._$Co??=[])[e]=h:s._$Cl=h),void 0!==h&&(i=M(t,h._$AS(t,i.values),h,e)),i}class R{constructor(t,i){this._$AV=[],this._$AN=void 0,this._$AD=t,this._$AM=i}get parentNode(){return this._$AM.parentNode}get _$AU(){return this._$AM._$AU}u(t){const{el:{content:i},parts:s}=this._$AD,e=(t?.creationScope??l).importNode(i,!0);P.currentNode=e;let h=P.nextNode(),o=0,n=0,r=s[0];for(;void 0!==r;){if(o===r.index){let i;2===r.type?i=new k(h,h.nextSibling,this,t):1===r.type?i=new r.ctor(h,r.name,r.strings,this,t):6===r.type&&(i=new Z(h,this,t)),this._$AV.push(i),r=s[++n]}o!==r?.index&&(h=P.nextNode(),o++)}return P.currentNode=l,e}p(t){let i=0;for(const s of this._$AV)void 0!==s&&(void 0!==s.strings?(s._$AI(t,s,i),i+=s.strings.length-2):s._$AI(t[i])),i++}}class k{get _$AU(){return this._$AM?._$AU??this._$Cv}constructor(t,i,s,e){this.type=2,this._$AH=A,this._$AN=void 0,this._$AA=t,this._$AB=i,this._$AM=s,this.options=e,this._$Cv=e?.isConnected??!0}get parentNode(){let t=this._$AA.parentNode;const i=this._$AM;return void 0!==i&&11===t?.nodeType&&(t=i.parentNode),t}get startNode(){return this._$AA}get endNode(){return this._$AB}_$AI(t,i=this){t=M(this,t,i),a(t)?t===A||null==t||\"\"===t?(this._$AH!==A&&this._$AR(),this._$AH=A):t!==this._$AH&&t!==E&&this._(t):void 0!==t._$litType$?this.$(t):void 0!==t.nodeType?this.T(t):d(t)?this.k(t):this._(t)}O(t){return this._$AA.parentNode.insertBefore(t,this._$AB)}T(t){this._$AH!==t&&(this._$AR(),this._$AH=this.O(t))}_(t){this._$AH!==A&&a(this._$AH)?this._$AA.nextSibling.data=t:this.T(l.createTextNode(t)),this._$AH=t}$(t){const{values:i,_$litType$:s}=t,e=\"number\"==typeof s?this._$AC(t):(void 0===s.el&&(s.el=S.createElement(V(s.h,s.h[0]),this.options)),s);if(this._$AH?._$AD===e)this._$AH.p(i);else{const t=new R(e,this),s=t.u(this.options);t.p(i),this.T(s),this._$AH=t}}_$AC(t){let i=C.get(t.strings);return void 0===i&&C.set(t.strings,i=new S(t)),i}k(t){u(this._$AH)||(this._$AH=[],this._$AR());const i=this._$AH;let s,e=0;for(const h of t)e===i.length?i.push(s=new k(this.O(c()),this.O(c()),this,this.options)):s=i[e],s._$AI(h),e++;e<i.length&&(this._$AR(s&&s._$AB.nextSibling,e),i.length=e)}_$AR(t=this._$AA.nextSibling,s){for(this._$AP?.(!1,!0,s);t!==this._$AB;){const s=i(t).nextSibling;i(t).remove(),t=s}}setConnected(t){void 0===this._$AM&&(this._$Cv=t,this._$AP?.(t))}}class H{get tagName(){return this.element.tagName}get _$AU(){return this._$AM._$AU}constructor(t,i,s,e,h){this.type=1,this._$AH=A,this._$AN=void 0,this.element=t,this.name=i,this._$AM=e,this.options=h,s.length>2||\"\"!==s[0]||\"\"!==s[1]?(this._$AH=Array(s.length-1).fill(new String),this.strings=s):this._$AH=A}_$AI(t,i=this,s,e){const h=this.strings;let o=!1;if(void 0===h)t=M(this,t,i,0),o=!a(t)||t!==this._$AH&&t!==E,o&&(this._$AH=t);else{const e=t;let n,r;for(t=h[0],n=0;n<h.length-1;n++)r=M(this,e[s+n],i,n),r===E&&(r=this._$AH[n]),o||=!a(r)||r!==this._$AH[n],r===A?t=A:t!==A&&(t+=(r??\"\")+h[n+1]),this._$AH[n]=r}o&&!e&&this.j(t)}j(t){t===A?this.element.removeAttribute(this.name):this.element.setAttribute(this.name,t??\"\")}}class I extends H{constructor(){super(...arguments),this.type=3}j(t){this.element[this.name]=t===A?void 0:t}}class L extends H{constructor(){super(...arguments),this.type=4}j(t){this.element.toggleAttribute(this.name,!!t&&t!==A)}}class z extends H{constructor(t,i,s,e,h){super(t,i,s,e,h),this.type=5}_$AI(t,i=this){if((t=M(this,t,i,0)??A)===E)return;const s=this._$AH,e=t===A&&s!==A||t.capture!==s.capture||t.once!==s.once||t.passive!==s.passive,h=t!==A&&(s===A||e);e&&this.element.removeEventListener(this.name,this,s),h&&this.element.addEventListener(this.name,this,t),this._$AH=t}handleEvent(t){\"function\"==typeof this._$AH?this._$AH.call(this.options?.host??this.element,t):this._$AH.handleEvent(t)}}class Z{constructor(t,i,s){this.element=t,this.type=6,this._$AN=void 0,this._$AM=i,this.options=s}get _$AU(){return this._$AM._$AU}_$AI(t){M(this,t)}}const j={M:h,P:o,A:n,C:1,L:N,R,D:d,V:M,I:k,H,N:L,U:z,B:I,F:Z},B=t.litHtmlPolyfillSupport;B?.(S,k),(t.litHtmlVersions??=[]).push(\"3.3.3\");const D=(t,i,s)=>{const e=s?.renderBefore??i;let h=e._$litPart$;if(void 0===h){const t=s?.renderBefore??null;e._$litPart$=h=new k(i.insertBefore(c(),t),t,void 0,s??{})}return h._$AI(t),h};export{j as _$LH,b as html,T as mathml,E as noChange,A as nothing,D as render,w as svg};\n//# sourceMappingURL=lit-html.js.map\n","import{ReactiveElement as t}from\"@lit/reactive-element\";export*from\"@lit/reactive-element\";import{render as e,noChange as r}from\"lit-html\";export*from\"lit-html\";\n/**\n * @license\n * Copyright 2017 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const s=globalThis;class i extends t{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const t=super.createRenderRoot();return this.renderOptions.renderBefore??=t.firstChild,t}update(t){const r=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(t),this._$Do=e(r,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return r}}i._$litElement$=!0,i[\"finalized\"]=!0,s.litElementHydrateSupport?.({LitElement:i});const o=s.litElementPolyfillSupport;o?.({LitElement:i});const n={_$AK:(t,e,r)=>{t._$AK(e,r)},_$AL:t=>t._$AL};(s.litElementVersions??=[]).push(\"4.2.2\");export{i as LitElement,n as _$LE};\n//# sourceMappingURL=lit-element.js.map\n","import{nothing as t}from\"../lit-html.js\";\n/**\n * @license\n * Copyright 2018 Google LLC\n * SPDX-License-Identifier: BSD-3-Clause\n */const o=o=>o??t;export{o as ifDefined};\n//# sourceMappingURL=if-defined.js.map\n","/**\n * Accessibility helpers shared by the player and component elements: a visually hidden class, the verdict\n * renderer (icon + word + border style, never colour alone) and polite announcements.\n */\nimport type { GroupVerdict, Translate } from '@astl/core';\nimport { type CSSResult, css, html, svg, type TemplateResult } from 'lit';\nimport { ifDefined } from 'lit/directives/if-defined.js';\n\n/** Slot verdicts (`correct`, `incorrect`) are a subset of group verdicts. */\nexport type Verdict = GroupVerdict;\n\n/** `.astl-vh`: hidden on screen, still read by screen readers. */\nexport const visuallyHidden: CSSResult = css`\n .astl-vh {\n position: absolute !important;\n inline-size: 1px !important;\n block-size: 1px !important;\n margin: -1px !important;\n padding: 0 !important;\n border: 0 !important;\n overflow: hidden !important;\n clip-path: inset(50%) !important;\n white-space: nowrap !important;\n }\n`;\n\n/**\n * Verdict styling. `[data-verdict]` sets `--astl-verdict-color`, `--astl-verdict-soft` and `--astl-verdict-border`\n * (solid = correct, double = partial, dashed = incorrect, dotted = empty) for borders of the element that carries it.\n */\nexport const verdictStyles: CSSResult = css`\n [data-verdict='correct'] {\n --astl-verdict-color: var(--astl-success);\n --astl-verdict-soft: var(--astl-success-soft);\n --astl-verdict-border: solid;\n }\n [data-verdict='partial'] {\n --astl-verdict-color: var(--astl-warning);\n --astl-verdict-soft: var(--astl-warning-soft);\n --astl-verdict-border: double;\n }\n [data-verdict='incorrect'] {\n --astl-verdict-color: var(--astl-danger);\n --astl-verdict-soft: var(--astl-danger-soft);\n --astl-verdict-border: dashed;\n }\n [data-verdict='empty'] {\n --astl-verdict-color: var(--astl-ink-muted);\n --astl-verdict-soft: var(--astl-surface);\n --astl-verdict-border: dotted;\n }\n .astl-verdict {\n display: inline-flex;\n align-items: center;\n gap: var(--astl-space-1);\n color: var(--astl-verdict-color);\n font-weight: 600;\n }\n .astl-verdict-icon {\n inline-size: 1.1em;\n block-size: 1.1em;\n flex: none;\n }\n`;\n\nconst ICONS: Readonly<Record<Verdict, TemplateResult>> = {\n correct: svg`<path d=\"M4 10.5l4 4 8-9\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/>`,\n partial: svg`<circle cx=\"10\" cy=\"10\" r=\"7\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\"/><path d=\"M10 3a7 7 0 0 0 0 14z\" fill=\"currentColor\"/>`,\n incorrect: svg`<path d=\"M5.5 5.5l9 9m0-9l-9 9\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" stroke-linecap=\"round\"/>`,\n empty: svg`<circle cx=\"10\" cy=\"10\" r=\"7\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2\" stroke-dasharray=\"3 3\"/>`,\n};\n\n/** A decorative icon per verdict (hidden from assistive technology: the word carries the meaning). */\nexport function verdictIcon(verdict: Verdict): TemplateResult {\n return html`<svg class=\"astl-verdict-icon\" viewBox=\"0 0 20 20\" aria-hidden=\"true\" focusable=\"false\">${ICONS[verdict]}</svg>`;\n}\n\nexport interface VerdictOptions {\n /** Hide the word visually (it stays readable, e.g. through `aria-describedby`). */\n readonly hiddenWord?: boolean;\n /** id of the word element, for `aria-describedby`. */\n readonly id?: string;\n /** `part` name of the wrapper. */\n readonly part?: string;\n /**\n * UI language and direction of the word. Pass the context locale: the word is UI text, and inside content of\n * another language it would otherwise be read with the content's voice and bidi rules.\n */\n readonly lang?: string;\n readonly dir?: 'ltr' | 'rtl';\n}\n\n/** Icon + word (`verdict.*` messages, e.g. \"Dobrze\", \"Jeszcze nie\") inside a `[data-verdict]` wrapper. */\nexport function renderVerdict(verdict: Verdict, t: Translate, options: VerdictOptions = {}): TemplateResult {\n return html`<span class=\"astl-verdict\" data-verdict=${verdict} part=${ifDefined(options.part)}\n >${verdictIcon(verdict)}<span\n class=${options.hiddenWord ? 'astl-vh' : 'astl-verdict-word'}\n id=${ifDefined(options.id)}\n lang=${ifDefined(options.lang)}\n dir=${ifDefined(options.dir)}\n >${t(`verdict.${verdict}`)}</span\n ></span\n >`;\n}\n\nconst pending = new WeakMap<HTMLElement, ReturnType<typeof setTimeout>>();\n\n/**\n * Puts a message into a polite live region. The region is emptied first and filled in a later task, so screen\n * readers also announce a message that repeats the previous one.\n */\nexport function announce(region: HTMLElement, message: string): void {\n clearTimeout(pending.get(region));\n region.textContent = '';\n pending.set(\n region,\n setTimeout(() => {\n region.textContent = message;\n }, 60),\n );\n}\n\nlet fallback: HTMLElement | null = null;\n\n/** A shared polite live region in `document.body`, for elements used without a player. */\nexport function documentLiveRegion(): HTMLElement {\n if (fallback?.isConnected) return fallback;\n fallback = document.createElement('div');\n fallback.setAttribute('aria-live', 'polite');\n fallback.style.cssText =\n 'position:absolute;inline-size:1px;block-size:1px;margin:-1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap';\n document.body.append(fallback);\n return fallback;\n}\n","/**\n * The attempt state machine, without DOM: answers, pages, checks and submission over a Checker.\n * The player renders it; hosts and tests can drive it directly.\n */\nimport {\n type Answers,\n type AttemptPolicy,\n type AttemptState,\n type Checker,\n CheckerError,\n type CheckResponse,\n type GradeResult,\n helpPolicy,\n isSnapshot,\n type JsonValue,\n ProblemCode,\n type ProblemCodeValue,\n SNAPSHOT_FORMAT,\n type Snapshot,\n type Solution,\n type SubmitResponse,\n} from '@astl/core';\n\nexport interface AttemptPage {\n /** View page id. */\n readonly id: string;\n /** Slots answered on this page, in reading order. */\n readonly slotIds: readonly string[];\n}\n\nexport interface AttemptControllerOptions {\n readonly policy: AttemptPolicy;\n readonly checker: Checker;\n readonly pages: readonly AttemptPage[];\n /** Restored when it is valid and its `viewHash` is null or equals `viewHash`. */\n readonly snapshot?: Snapshot | null;\n /** Hash of the view the attempt runs on; written into snapshots. */\n readonly viewHash?: string | null;\n /** Clock in milliseconds, for deadlines and `savedAt`. Default `Date.now`. */\n readonly now?: () => number;\n}\n\nexport type AttemptChange =\n | { readonly type: 'state'; readonly state: AttemptState; readonly previous: AttemptState }\n /** Only the slots that changed; `''` = cleared. */\n | { readonly type: 'answers'; readonly answers: Answers }\n | { readonly type: 'page'; readonly index: number; readonly previous: number }\n | { readonly type: 'result'; readonly response: CheckResponse | SubmitResponse }\n /** A check of one interaction (`checkElement`): its result only, the last whole result stays. */\n | { readonly type: 'element'; readonly id: string; readonly response: CheckResponse }\n | { readonly type: 'reset' };\n\nexport type AttemptListener = (change: AttemptChange) => void;\n\n/** A refusal decided locally, shaped like the protocol's problem documents. */\nfunction refusal(code: ProblemCodeValue, status: number, detail?: string): CheckerError {\n return new CheckerError({\n type: `urn:astrolabe:problem:${code}`,\n title: code,\n status,\n code,\n ...(detail === undefined ? {} : { detail }),\n });\n}\n\nfunction asCheckerError(error: unknown): CheckerError {\n if (error instanceof CheckerError) return error;\n return refusal(ProblemCode.internal, 500, error instanceof Error ? error.message : String(error));\n}\n\nexport class AttemptController {\n readonly policy: AttemptPolicy;\n readonly pages: readonly AttemptPage[];\n readonly viewHash: string | null;\n /** Whether the snapshot passed in was applied. */\n readonly restored: boolean;\n /** The checker can be swapped at any time (e.g. a host sets it after the view). */\n checker: Checker;\n #now: () => number;\n #state: AttemptState;\n #answers: Record<string, string> = {};\n #page = 0;\n #checks = 0;\n #checksLeft: number | null;\n #result: GradeResult | null = null;\n #solution: Solution | null = null;\n #response: CheckResponse | SubmitResponse | null = null;\n #pendingCheck: Promise<CheckResponse> | null = null;\n #pendingSubmit: Promise<SubmitResponse> | null = null;\n #listeners = new Set<AttemptListener>();\n #slots: ReadonlySet<string>;\n\n constructor(options: AttemptControllerOptions) {\n this.policy = options.policy;\n this.checker = options.checker;\n this.pages = options.pages;\n this.viewHash = options.viewHash ?? null;\n this.#now = options.now ?? Date.now;\n this.#slots = new Set(this.pages.flatMap((p) => p.slotIds));\n const snapshot = this.#restorable(options.snapshot ?? null);\n this.restored = snapshot !== null;\n if (snapshot) {\n for (const [id, value] of Object.entries(snapshot.answers)) {\n if (this.#slots.has(id) && value !== '') this.#answers[id] = value;\n }\n this.#page = Math.min(snapshot.page, Math.max(0, this.pages.length - 1));\n this.#checks = snapshot.checks;\n }\n this.#checksLeft =\n this.policy.maxChecks === null ? null : Math.max(0, this.policy.maxChecks - this.#checks);\n if (this.policy.mode === 'review') this.#state = 'review';\n else if (snapshot?.submitted) this.#state = 'submitted';\n else if (snapshot && (Object.keys(this.#answers).length > 0 || this.#checks > 0)) this.#state = 'active';\n else this.#state = 'ready';\n }\n\n /** The snapshot when it is valid and belongs to the view (`viewHash` null or equal), else null. */\n static restorable(snapshot: unknown, viewHash: string | null): Snapshot | null {\n if (!isSnapshot(snapshot)) return null;\n return snapshot.viewHash === null || snapshot.viewHash === viewHash ? snapshot : null;\n }\n\n get state(): AttemptState {\n return this.#state;\n }\n\n get answers(): Answers {\n return { ...this.#answers };\n }\n\n /** 0-based index of the current page. */\n get page(): number {\n return this.#page;\n }\n\n get pageCount(): number {\n return this.pages.length;\n }\n\n get checks(): number {\n return this.#checks;\n }\n\n /** null = unlimited. */\n get checksLeft(): number | null {\n return this.#checksLeft;\n }\n\n /** The last result (practice keeps it while the student goes on). */\n get result(): GradeResult | null {\n return this.#result;\n }\n\n get solution(): Solution | null {\n return this.#solution;\n }\n\n /** The last CheckResponse or SubmitResponse. */\n get response(): CheckResponse | SubmitResponse | null {\n return this.#response;\n }\n\n /** Answers cannot change: review, submitting or submitted. */\n get readOnly(): boolean {\n return this.#state === 'review' || this.#state === 'submitting' || this.#state === 'submitted';\n }\n\n canCheck(): boolean {\n return (\n this.policy.mode === 'practice' &&\n (this.#state === 'ready' || this.#state === 'active') &&\n this.#checksLeft !== 0\n );\n }\n\n canSubmit(): boolean {\n return this.policy.mode !== 'review' && (this.#state === 'ready' || this.#state === 'active');\n }\n\n canGoTo(index: number): boolean {\n if (!Number.isInteger(index) || index < 0 || index >= this.pages.length) return false;\n if (index >= this.#page) return true;\n // Linear attempts never return to earlier pages while answers can still change.\n return this.policy.navigation === 'free' || this.readOnly;\n }\n\n subscribe(listener: AttemptListener): () => void {\n this.#listeners.add(listener);\n return () => this.#listeners.delete(listener);\n }\n\n /** `ready -> active`. Called implicitly by the first answer, check or submit. */\n start(): void {\n if (this.#state === 'ready') this.#setState('active');\n }\n\n /** Applies a partial update (`''` deletes) and returns the slots that actually changed. Unknown ids are ignored. */\n setAnswers(partial: Answers): Answers {\n if (this.readOnly) return {};\n const changed: Record<string, string> = {};\n for (const [id, value] of Object.entries(partial)) {\n if (!this.#slots.has(id) || (this.#answers[id] ?? '') === value) continue;\n if (value === '') delete this.#answers[id];\n else this.#answers[id] = value;\n changed[id] = value;\n }\n if (Object.keys(changed).length === 0) return changed;\n this.start();\n this.#emit({ type: 'answers', answers: changed });\n return changed;\n }\n\n goTo(index: number): boolean {\n if (index === this.#page || !this.canGoTo(index)) return false;\n const previous = this.#page;\n this.#page = index;\n this.#emit({ type: 'page', index, previous });\n return true;\n }\n\n next(): boolean {\n return this.goTo(this.#page + 1);\n }\n\n previous(): boolean {\n return this.goTo(this.#page - 1);\n }\n\n /** Practice only. Grades everything, or one view page. A second call while checking joins the first. */\n check(page?: string): Promise<CheckResponse> {\n return this.#check(page);\n }\n\n /**\n * Practice with `checkScope: 'interaction'` only: grades one interaction (a view element id), counted like any\n * check. The response comes as an `element` change; `result` and `response` keep the last whole check.\n */\n checkElement(id: string): Promise<CheckResponse> {\n return this.#check(undefined, id);\n }\n\n #check(page: string | undefined, element?: string): Promise<CheckResponse> {\n if (this.#pendingCheck) return this.#pendingCheck;\n const refused = this.#checkRefusal(page, element);\n if (refused) return Promise.reject(refused);\n const run = this.#runCheck(page, element).finally(() => {\n this.#pendingCheck = null;\n });\n this.#pendingCheck = run;\n return run;\n }\n\n /** Final. Waits for a running check first; a second call while submitting joins the first. */\n submit(): Promise<SubmitResponse> {\n if (this.#pendingSubmit) return this.#pendingSubmit;\n if (this.policy.mode === 'review' || this.#state === 'submitted') {\n return Promise.reject(refusal(ProblemCode.attemptClosed, 409));\n }\n const run = this.#runSubmit().finally(() => {\n this.#pendingSubmit = null;\n });\n this.#pendingSubmit = run;\n return run;\n }\n\n /** Clears answers and the last result and goes back to the first page. Not after submitting. */\n reset(): boolean {\n if (this.#state !== 'ready' && this.#state !== 'active') return false;\n this.#answers = {};\n this.#result = null;\n this.#solution = null;\n this.#response = null;\n const previous = this.#page;\n this.#page = 0;\n this.#emit({ type: 'reset' });\n if (previous !== 0) this.#emit({ type: 'page', index: 0, previous });\n return true;\n }\n\n snapshot(ui: Readonly<Record<string, JsonValue>> = {}): Snapshot {\n return {\n format: SNAPSHOT_FORMAT,\n viewHash: this.viewHash,\n answers: this.answers,\n page: this.#page,\n checks: this.#checks,\n submitted: this.#state === 'submitted',\n ui,\n savedAt: new Date(this.#now()).toISOString(),\n };\n }\n\n /** Slot ids without an answer, on one page or on all of them. */\n emptySlots(page?: number): string[] {\n const pages = page === undefined ? this.pages : this.pages.slice(page, page + 1);\n return pages.flatMap((p) => p.slotIds).filter((id) => (this.#answers[id] ?? '') === '');\n }\n\n /** Milliseconds to the policy deadline (0 when past it); null without a deadline. */\n timeLeft(): number | null {\n if (this.policy.deadline === null) return null;\n return Math.max(0, Date.parse(this.policy.deadline) - this.#now());\n }\n\n #checkRefusal(page: string | undefined, element: string | undefined): CheckerError | null {\n if (this.policy.mode !== 'practice') return refusal(ProblemCode.checkNotAllowed, 403);\n if (element !== undefined && helpPolicy(this.policy).checkScope !== 'interaction') {\n return refusal(ProblemCode.checkNotAllowed, 403);\n }\n if (this.#state === 'submitting' || this.#state === 'submitted' || this.#state === 'review') {\n return refusal(ProblemCode.attemptClosed, 409);\n }\n if (this.#checksLeft === 0) return refusal(ProblemCode.checksExhausted, 403);\n if (page !== undefined && !this.pages.some((p) => p.id === page))\n return refusal(ProblemCode.notFound, 404);\n return null;\n }\n\n async #runCheck(page: string | undefined, element: string | undefined): Promise<CheckResponse> {\n this.start();\n this.#setState('checking');\n try {\n const answers = this.answers;\n const scope = page !== undefined ? { page } : element !== undefined ? { element } : {};\n const response = await this.checker.check({ answers, ...scope });\n this.#checks++;\n this.#checksLeft =\n response.checksLeft ??\n (this.policy.maxChecks === null ? null : Math.max(0, this.policy.maxChecks - this.#checks));\n if (element === undefined) {\n this.#result = response.result;\n this.#response = response;\n }\n this.#setState('active');\n this.#emit(\n element === undefined ? { type: 'result', response } : { type: 'element', id: element, response },\n );\n return response;\n } catch (error) {\n const problem = asCheckerError(error);\n if (problem.problem.code === ProblemCode.checksExhausted) this.#checksLeft = 0;\n this.#setState(problem.problem.code === ProblemCode.attemptClosed ? 'submitted' : 'active');\n throw problem;\n }\n }\n\n async #runSubmit(): Promise<SubmitResponse> {\n if (this.#pendingCheck) await this.#pendingCheck.catch(() => undefined);\n if (this.#state === 'submitted') throw refusal(ProblemCode.attemptClosed, 409);\n this.start();\n this.#setState('submitting');\n try {\n const response = await this.checker.submit({ answers: this.answers });\n this.#response = response;\n this.#result = response.result;\n this.#solution = response.solution;\n this.#setState('submitted');\n this.#emit({ type: 'result', response });\n return response;\n } catch (error) {\n const problem = asCheckerError(error);\n this.#setState(problem.problem.code === ProblemCode.attemptClosed ? 'submitted' : 'active');\n throw problem;\n }\n }\n\n #restorable(snapshot: Snapshot | null): Snapshot | null {\n return AttemptController.restorable(snapshot, this.viewHash);\n }\n\n #setState(state: AttemptState): void {\n const previous = this.#state;\n if (state === previous) return;\n this.#state = state;\n this.#emit({ type: 'state', state, previous });\n }\n\n #emit(change: AttemptChange): void {\n for (const listener of [...this.#listeners]) listener(change);\n }\n}\n","/**\n * Checker over the grading protocol (apps/docs/src/content/docs/reference/protocol.md): `POST {endpoint}/check`,\n * `/submit` and `/hint`.\n */\nimport {\n type Checker,\n CheckerError,\n type CheckRequest,\n type CheckResponse,\n type HintRequest,\n type HintResponse,\n isProblemDetails,\n JSON_MEDIA_TYPE,\n PROBLEM_MEDIA_TYPE,\n ProblemCode,\n type ProblemCodeValue,\n ProtocolPath,\n type ResultHelp,\n type SubmitRequest,\n type SubmitResponse,\n} from '@astl/core';\n\nexport interface HttpCheckerOptions {\n /** URL of one attempt, e.g. `/api/attempts/123`; `/check`, `/submit` and `/hint` are appended. */\n readonly endpoint: string;\n /** Extra request headers, e.g. `Authorization`. */\n readonly headers?: Readonly<Record<string, string>>;\n /** Fetch credentials mode (cookies). Default: the browser default (`same-origin`). */\n readonly credentials?: RequestCredentials;\n /** Fetch implementation, for tests or instrumented clients. Default: the global `fetch`. */\n readonly fetch?: (input: string, init: RequestInit) => Promise<Response>;\n}\n\n/** Problem codes for error statuses without a problem body. */\nconst STATUS_CODES: Readonly<Record<number, ProblemCodeValue>> = {\n 400: ProblemCode.invalidRequest,\n 401: ProblemCode.unauthorized,\n 403: ProblemCode.unauthorized,\n 404: ProblemCode.notFound,\n 405: ProblemCode.methodNotAllowed,\n 409: ProblemCode.attemptClosed,\n 413: ProblemCode.payloadTooLarge,\n};\n\nfunction problem(code: ProblemCodeValue, status: number, detail?: string): CheckerError {\n return new CheckerError({\n type: `urn:astrolabe:problem:${code}`,\n title: code,\n status,\n code,\n ...(detail === undefined ? {} : { detail }),\n });\n}\n\nfunction parseJson(text: string): unknown {\n try {\n return text === '' ? undefined : JSON.parse(text);\n } catch {\n return undefined;\n }\n}\n\n/**\n * The help fields of a response when they are objects. Their entries are the player's to check where it shows them\n * (the help module, loaded with views that offer help), like the HTML in them.\n */\nfunction helpOf({ feedback, explanations }: Record<string, unknown>): ResultHelp {\n const object = (v: unknown) => typeof v === 'object' && v !== null && !Array.isArray(v);\n return {\n ...(object(feedback) ? { feedback: feedback as NonNullable<ResultHelp['feedback']> } : {}),\n ...(object(explanations)\n ? { explanations: explanations as NonNullable<ResultHelp['explanations']> }\n : {}),\n };\n}\n\nexport function httpChecker(options: HttpCheckerOptions): Checker {\n const base = options.endpoint.replace(/\\/+$/, '');\n const send = options.fetch ?? ((input: string, init: RequestInit) => globalThis.fetch(input, init));\n\n async function post(\n path: string,\n body: CheckRequest | SubmitRequest | HintRequest,\n ): Promise<Record<string, unknown>> {\n const init: RequestInit = {\n method: 'POST',\n headers: {\n 'content-type': JSON_MEDIA_TYPE,\n accept: `${JSON_MEDIA_TYPE}, ${PROBLEM_MEDIA_TYPE}`,\n ...options.headers,\n },\n body: JSON.stringify(body),\n ...(options.credentials === undefined ? {} : { credentials: options.credentials }),\n };\n let response: Response;\n let text: string;\n try {\n response = await send(`${base}/${path}`, init);\n text = await response.text();\n } catch (error) {\n throw problem(ProblemCode.internal, 0, error instanceof Error ? error.message : String(error));\n }\n const data = parseJson(text);\n const isProblem = (response.headers.get('content-type') ?? '').includes(PROBLEM_MEDIA_TYPE);\n if (!response.ok || isProblem) {\n if (isProblemDetails(data)) {\n throw new CheckerError({ ...data, type: typeof data.type === 'string' ? data.type : 'about:blank' });\n }\n throw problem(STATUS_CODES[response.status] ?? ProblemCode.internal, response.status);\n }\n if (typeof data !== 'object' || data === null || Array.isArray(data)) {\n throw problem(ProblemCode.internal, response.status, 'response is not a JSON object');\n }\n return data as Record<string, unknown>;\n }\n\n return {\n async check(request: CheckRequest): Promise<CheckResponse> {\n const data = await post(ProtocolPath.check, request);\n if (typeof data.result !== 'object' || data.result === null) {\n throw problem(ProblemCode.internal, 200, 'check response without a result');\n }\n return {\n result: data.result as CheckResponse['result'],\n checksLeft: (data.checksLeft as number | null) ?? null,\n ...helpOf(data),\n };\n },\n async submit(request: SubmitRequest): Promise<SubmitResponse> {\n const data = await post(ProtocolPath.submit, request);\n if (typeof data.submittedAt !== 'string') {\n throw problem(ProblemCode.internal, 200, 'submit response without submittedAt');\n }\n return {\n result: (data.result as SubmitResponse['result']) ?? null,\n solution: (data.solution as SubmitResponse['solution']) ?? null,\n passed: (data.passed as boolean | null) ?? null,\n submittedAt: data.submittedAt,\n ...helpOf(data),\n };\n },\n async hint(request: HintRequest): Promise<HintResponse> {\n const data = await post(ProtocolPath.hint, request);\n if (typeof data.html !== 'string')\n throw problem(ProblemCode.internal, 200, 'hint response without html');\n return data as unknown as HintResponse;\n },\n };\n}\n","{\n \"loading\": \"Loading the exercise…\",\n \"page.heading\": \"Page {n}\",\n \"page.counter\": \"Page {n} of {total}\",\n \"page.counter.spread\": \"Pages {from}-{to} of {total}\",\n \"progress.label\": \"Pages\",\n \"progress.item\": \"Page {n}, {state, select, done {answered} partial {partly answered} other {not answered}}\",\n \"nav.previous\": \"Back\",\n \"nav.next\": \"Next\",\n \"action.check\": \"Check\",\n \"action.reset\": \"Start over\",\n \"action.submit\": \"Hand in\",\n \"confirm.empty\": \"{count, plural, one {You have # empty answer.} other {You have # empty answers.}} Hand in anyway?\",\n \"confirm.submit\": \"Hand in anyway\",\n \"confirm.cancel\": \"Back to the answers\",\n \"checks.left\": \"{count, plural, =0 {No checks left} one {# check left} other {# checks left}}\",\n \"result.title\": \"Result\",\n \"result.score\": \"{score} of {max, plural, one {# point} other {# points}}\",\n \"result.count\": \"{verdict}: {count}\",\n \"result.passed\": \"Passed\",\n \"result.notPassed\": \"Not passed yet\",\n \"result.submitted\": \"Your answers have been handed in.\",\n \"result.later\": \"You will see your results later.\",\n \"result.teacher.sent\": \"Your answers were sent to your teacher.\",\n \"result.teacher.count\": \"{count, plural, =0 {No answer goes to your teacher to mark.} one {# answer goes to your teacher to mark.} other {# answers go to your teacher to mark.}}\",\n \"result.teacher.unchecked\": \"Answers for your teacher are not checked here.\",\n \"result.practice\": \"Practice only: nothing here is scored.\",\n \"result.announce\": \"Result: {score}.\",\n \"result.countAnnounce\": \"{verdict}: {count}.\",\n \"verdict.correct\": \"Correct\",\n \"verdict.partial\": \"Partly correct\",\n \"verdict.incorrect\": \"Not yet\",\n \"verdict.empty\": \"No answer\",\n \"timer.label\": \"Time left\",\n \"timer.minutes\": \"{minutes, plural, one {# minute left} other {# minutes left}}\",\n \"timer.expired\": \"Time is up. Your answers are being handed in.\",\n \"unsupported\": \"This part of the exercise does not work in this player.\",\n \"error.invalid_request\": \"Your answers could not be sent. Try again.\",\n \"error.unauthorized\": \"We could not confirm who you are. Sign in and try again.\",\n \"error.check_not_allowed\": \"Checking is turned off in this exercise.\",\n \"error.checks_exhausted\": \"You have no checks left.\",\n \"error.not_found\": \"This exercise could not be found.\",\n \"error.method_not_allowed\": \"The exercise server turned the request down.\",\n \"error.attempt_closed\": \"These answers have already been handed in.\",\n \"error.payload_too_large\": \"Your answers are too long to send.\",\n \"error.internal_error\": \"We could not reach the exercise server. Try again in a moment.\",\n \"error.no_checker\": \"This exercise cannot be checked here.\",\n \"error.load_failed\": \"The exercise could not be loaded.\",\n \"error.view_invalid\": \"The exercise file is damaged.\",\n \"error.integrity_mismatch\": \"The exercise file did not pass verification, so it was not opened.\",\n \"error.source_needs_compiler\": \"This exercise needs the full Astrolabe script to run.\",\n \"error.source_invalid\": \"This exercise is not written correctly, so it cannot be shown.\"\n}\n","{\n \"loading\": \"Wczytywanie zadania…\",\n \"page.heading\": \"Strona {n}\",\n \"page.counter\": \"Strona {n} z {total}\",\n \"page.counter.spread\": \"Strony {from}-{to} z {total}\",\n \"progress.label\": \"Strony\",\n \"progress.item\": \"Strona {n}, {state, select, done {wszystko uzupełnione} partial {częściowo uzupełniona} other {bez odpowiedzi}}\",\n \"nav.previous\": \"Wstecz\",\n \"nav.next\": \"Dalej\",\n \"action.check\": \"Sprawdź\",\n \"action.reset\": \"Zacznij od nowa\",\n \"action.submit\": \"Oddaj\",\n \"confirm.empty\": \"{count, plural, one {Masz # pustą odpowiedź.} few {Masz # puste odpowiedzi.} many {Masz # pustych odpowiedzi.} other {Masz # pustej odpowiedzi.}} Oddać mimo to?\",\n \"confirm.submit\": \"Oddaj mimo to\",\n \"confirm.cancel\": \"Wróć do odpowiedzi\",\n \"checks.left\": \"{count, plural, =0 {Nie masz już sprawdzeń} one {Zostało # sprawdzenie} few {Zostały # sprawdzenia} many {Zostało # sprawdzeń} other {Zostało # sprawdzenia}}\",\n \"result.title\": \"Wynik\",\n \"result.score\": \"{score} z {max, plural, one {# punktu} few {# punktów} many {# punktów} other {# punktu}}\",\n \"result.count\": \"{verdict}: {count}\",\n \"result.passed\": \"Zaliczone\",\n \"result.notPassed\": \"Jeszcze nie zaliczone\",\n \"result.submitted\": \"Twoje odpowiedzi zostały oddane.\",\n \"result.later\": \"Wyniki zobaczysz później.\",\n \"result.teacher.sent\": \"Twoje odpowiedzi trafiły do nauczyciela.\",\n \"result.teacher.count\": \"{count, plural, =0 {Żadna odpowiedź nie trafia do nauczyciela do oceny.} one {# odpowiedź trafia do nauczyciela do oceny.} few {# odpowiedzi trafiają do nauczyciela do oceny.} many {# odpowiedzi trafia do nauczyciela do oceny.} other {# odpowiedzi trafia do nauczyciela do oceny.}}\",\n \"result.teacher.unchecked\": \"Odpowiedzi dla nauczyciela nie są tu sprawdzane.\",\n \"result.practice\": \"Tylko do ćwiczeń: nic tu nie jest oceniane.\",\n \"result.announce\": \"Wynik: {score}.\",\n \"result.countAnnounce\": \"{verdict}: {count}.\",\n \"verdict.correct\": \"Dobrze\",\n \"verdict.partial\": \"Częściowo dobrze\",\n \"verdict.incorrect\": \"Jeszcze nie\",\n \"verdict.empty\": \"Brak odpowiedzi\",\n \"timer.label\": \"Pozostały czas\",\n \"timer.minutes\": \"{minutes, plural, one {Została # minuta} few {Zostały # minuty} many {Zostało # minut} other {Zostało # minuty}}\",\n \"timer.expired\": \"Czas minął. Oddajemy twoje odpowiedzi.\",\n \"unsupported\": \"Ta część zadania nie działa w tym odtwarzaczu.\",\n \"error.invalid_request\": \"Nie udało się wysłać odpowiedzi. Spróbuj jeszcze raz.\",\n \"error.unauthorized\": \"Nie udało się potwierdzić, kim jesteś. Zaloguj się i spróbuj jeszcze raz.\",\n \"error.check_not_allowed\": \"W tym zadaniu nie można sprawdzać odpowiedzi.\",\n \"error.checks_exhausted\": \"Nie masz już sprawdzeń.\",\n \"error.not_found\": \"Nie znaleziono tego zadania.\",\n \"error.method_not_allowed\": \"Serwer zadania odrzucił prośbę.\",\n \"error.attempt_closed\": \"Te odpowiedzi zostały już oddane.\",\n \"error.payload_too_large\": \"Odpowiedzi są za długie, żeby je wysłać.\",\n \"error.internal_error\": \"Nie udało się połączyć z serwerem zadania. Spróbuj za chwilę.\",\n \"error.no_checker\": \"Tego zadania nie można tu sprawdzić.\",\n \"error.load_failed\": \"Nie udało się wczytać zadania.\",\n \"error.view_invalid\": \"Plik zadania jest uszkodzony.\",\n \"error.integrity_mismatch\": \"Plik zadania nie przeszedł weryfikacji, więc nie został otwarty.\",\n \"error.source_needs_compiler\": \"To zadanie wymaga pełnej wersji skryptu Astrolabe.\",\n \"error.source_invalid\": \"To zadanie nie jest poprawnie zapisane, więc nie da się go wyświetlić.\"\n}\n","import type { I18n, MessageCatalog, Translate } from '@astl/core';\nimport en from './messages/en.json' with { type: 'json' };\nimport pl from './messages/pl.json' with { type: 'json' };\n\n/** i18n namespace of the player chrome and of strings shared by all elements (verdict words). */\nexport const PLAYER_NAMESPACE = 'astl.player';\n\nexport const playerMessages: readonly MessageCatalog[] = [\n { namespace: PLAYER_NAMESPACE, locale: 'en', messages: en },\n { namespace: PLAYER_NAMESPACE, locale: 'pl', messages: pl },\n];\n\n/** Looks a key up in `namespace` first, then in the shared player namespace, else returns the key. */\nexport function elementTranslator(i18n: I18n, locale: string, namespace: string): Translate {\n return (key, params) => {\n const own = i18n.t(locale, namespace, key, params);\n return own !== key || namespace === PLAYER_NAMESPACE\n ? own\n : i18n.t(locale, PLAYER_NAMESPACE, key, params);\n };\n}\n","import {\n type ComponentManifest,\n isSafeUrl,\n type MessageCatalog,\n type SourceCompiler,\n type StyleTemplate,\n type UrlPolicy,\n} from '@astl/core';\n\n/** One component element type for the player: its manifest, element class and message catalogs. */\nexport interface ElementRegistration {\n readonly manifest: ComponentManifest;\n readonly element: CustomElementConstructor;\n readonly messages: readonly MessageCatalog[];\n}\n\n/** Imported the first time a view mounted by <astl-player> contains `tag`; resolves to that tag's registration. */\nexport interface LazyElement {\n readonly tag: string;\n readonly load: () => Promise<ElementRegistration>;\n}\n\n/** A component element for the player: registered right away, or lazily on first use. */\nexport type ElementEntry = ElementRegistration | LazyElement;\n\nexport function isLazyElement(entry: ElementEntry): entry is LazyElement {\n return typeof (entry as Partial<LazyElement>).load === 'function';\n}\n\n/** What `definePlayer` registered. Shared by every `<astl-player>` of this module instance. */\nexport interface PlayerRuntime {\n /** Registrations by tag: eager ones, and lazy ones once loaded. */\n readonly elements: Map<string, ElementRegistration>;\n /** Lazy elements by tag, with the registry `definePlayer` defines them in. */\n readonly lazy: Map<\n string,\n { readonly load: LazyElement['load']; readonly registry: CustomElementRegistry }\n >;\n /** Loads in flight by tag, shared by every player. */\n readonly loading: Map<string, Promise<void>>;\n readonly catalogs: MessageCatalog[];\n /** Style templates by name. */\n readonly styleTemplates: Map<string, StyleTemplate>;\n compileSource: SourceCompiler | null;\n /** The URL policy views are cleaned with: the engine's, so the URLs it kept stay. */\n urlPolicy: UrlPolicy;\n /**\n * Bumped on every registration and every lazy element loaded, so players rebuild cached message tables and the\n * template stylesheet.\n */\n version: number;\n}\n\nexport const runtime: PlayerRuntime = {\n elements: new Map(),\n lazy: new Map(),\n loading: new Map(),\n catalogs: [],\n styleTemplates: new Map(),\n compileSource: null,\n urlPolicy: isSafeUrl,\n version: 0,\n};\n\n/** Loads and defines one lazy element; a failed load is dropped from `loading`, so the next view tries again. */\nfunction loadElement(tag: string): Promise<void> {\n const entry = runtime.lazy.get(tag);\n if (entry === undefined || runtime.elements.has(tag)) return Promise.resolve();\n let pending = runtime.loading.get(tag);\n if (pending === undefined) {\n pending = Promise.resolve()\n .then(() => entry.load())\n .then((registration) => {\n const loaded = registration?.manifest?.tag;\n if (loaded !== tag) throw new Error(`The lazy element for <${tag}> loaded <${String(loaded)}>`);\n const existing = entry.registry.get(tag);\n if (existing === undefined) entry.registry.define(tag, registration.element);\n else if (existing !== registration.element)\n throw new Error(`<${tag}> is already defined by another class`);\n runtime.elements.set(tag, registration);\n runtime.version++;\n })\n .finally(() => runtime.loading.delete(tag));\n runtime.loading.set(tag, pending);\n }\n return pending;\n}\n\n/**\n * Loads the lazy elements of these tags that are not loaded yet, in parallel, each at most once at a time for every\n * player. Tags without a lazy element are skipped. Rejects when one fails.\n */\nexport async function loadElements(tags: Iterable<string>): Promise<void> {\n await Promise.all(Array.from(new Set(tags), loadElement));\n}\n","import { tokensCss } from '@astl/tokens';\nimport { type CSSResultGroup, css, unsafeCSS } from 'lit';\nimport { verdictStyles, visuallyHidden } from '../a11y.js';\n\nexport const playerStyles: CSSResultGroup = [\n // Tokens sit on :host so host pages can override any --astl-* property on <astl-player> itself.\n unsafeCSS(tokensCss(':host')),\n visuallyHidden,\n verdictStyles,\n css`\n :host {\n display: block;\n color: var(--astl-ink);\n }\n :host([hidden]) {\n display: none;\n }\n .root {\n display: flex;\n flex-direction: column;\n gap: var(--astl-space-4);\n padding: var(--astl-space-4);\n background: var(--astl-canvas);\n color: var(--astl-ink);\n font-family: var(--astl-font-body);\n font-size: var(--astl-size-ui);\n line-height: 1.4;\n }\n .root > * {\n box-sizing: border-box;\n inline-size: 100%;\n max-inline-size: 760px;\n margin-inline: auto;\n }\n .status {\n margin-block: 0;\n color: var(--astl-ink-muted);\n }\n .problem {\n margin-block: 0;\n padding-block: var(--astl-space-3);\n padding-inline: var(--astl-space-4);\n border: var(--astl-outline-width) solid var(--astl-danger);\n border-radius: var(--astl-radius-m);\n background: var(--astl-danger-soft);\n color: var(--astl-ink);\n }\n `,\n // The compiler's issues for the author: plain text, one per line, wrapped inside the column.\n css`\n .problem-details {\n margin-block: 0;\n padding-block: var(--astl-space-3);\n padding-inline: var(--astl-space-4);\n border: var(--astl-outline-width) solid var(--astl-line);\n border-radius: var(--astl-radius-m);\n background: var(--astl-surface);\n color: var(--astl-ink);\n white-space: pre-wrap;\n overflow-wrap: anywhere;\n }\n\n .header {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: var(--astl-space-3) var(--astl-space-5);\n }\n .counter {\n margin-block: 0;\n font-weight: 600;\n }\n .progress {\n display: flex;\n flex-wrap: wrap;\n gap: var(--astl-space-1);\n margin: 0;\n padding: 0;\n list-style: none;\n }\n .segment {\n box-sizing: border-box;\n display: inline-flex;\n align-items: center;\n justify-content: center;\n gap: var(--astl-space-1);\n min-inline-size: var(--astl-target-min);\n min-block-size: var(--astl-target-min);\n padding-inline: var(--astl-space-2);\n border: var(--astl-outline-width) solid var(--astl-outline);\n border-radius: var(--astl-radius-m);\n background: var(--astl-surface);\n color: var(--astl-ink);\n font: inherit;\n font-weight: 600;\n text-decoration: none;\n }\n button.segment {\n cursor: pointer;\n }\n `,\n // Answered state by shape: a full circle for a fully answered page, a half full one for a partly answered one.\n css`\n .segment-icon {\n flex: none;\n inline-size: 0.875em;\n block-size: 0.875em;\n }\n `,\n // The one current-page cue: a filled button (plus aria-current).\n css`\n .segment[aria-current='step'] {\n border-color: var(--astl-accent);\n background: var(--astl-accent);\n color: var(--astl-on-accent);\n }\n .timer {\n margin-block: 0;\n margin-inline-start: auto;\n font-variant-numeric: tabular-nums;\n font-weight: 600;\n }\n .timer-label {\n color: var(--astl-ink-muted);\n font-weight: 400;\n }\n `,\n // The card's edge keeps it visible where surface and canvas are the same colour (hc).\n css`\n .canvas {\n border: var(--astl-outline-width) solid var(--astl-line);\n padding: var(--astl-space-5);\n border-radius: var(--astl-radius-l);\n background: var(--astl-surface);\n color: var(--astl-ink);\n font-size: var(--astl-size-content);\n line-height: var(--astl-line-height-content);\n overflow-wrap: break-word;\n }\n .canvas[hidden],\n astl-page[hidden] {\n display: none;\n }\n astl-doc,\n astl-page {\n display: block;\n }\n .canvas :where(p, ul, ol, blockquote) {\n margin-block: 0 var(--astl-space-4);\n }\n .canvas :where(h2, h3, h4) {\n margin-block: var(--astl-space-5) var(--astl-space-3);\n font-family: var(--astl-font-display);\n line-height: 1.25;\n }\n `,\n // The card's padding is the space at its edges: no extra margin above a page's first block or below its last.\n css`\n .canvas astl-page > :first-child {\n margin-block-start: 0;\n }\n .canvas astl-page > :last-child {\n margin-block-end: 0;\n }\n `,\n // After the content headings and more specific than them: the page heading opens the card, no space above.\n css`\n .canvas .astl-page-heading {\n margin-block: 0 var(--astl-space-4);\n font-size: 1.3em;\n }\n .canvas :where(ul, ol) {\n padding-inline-start: var(--astl-space-5);\n }\n `,\n // Only real links look like links (a sanitised link without a safe href is plain text).\n css`\n .canvas a[href] {\n color: var(--astl-accent);\n }\n .canvas code {\n font-family: var(--astl-font-mono);\n font-size: 0.9em;\n }\n .canvas mark {\n background: var(--astl-warning-soft);\n color: var(--astl-ink);\n }\n .canvas blockquote {\n margin-inline: 0;\n padding-inline-start: var(--astl-space-4);\n border-inline-start: var(--astl-outline-width) solid var(--astl-line);\n }\n `,\n // A component puts the pictures of a child on lines of their own (a card's picture above its label) by setting\n // --astl-picture-display: block on that child from its shadow root: its own CSS cannot reach the pictures inside.\n css`\n .canvas img {\n display: var(--astl-picture-display, inline);\n max-inline-size: 100%;\n block-size: auto;\n vertical-align: middle;\n }\n .canvas figure {\n margin-block: 0 var(--astl-space-4);\n margin-inline: 0;\n }\n .canvas figure img {\n display: block;\n }\n .canvas figcaption {\n margin-block-start: var(--astl-space-2);\n color: var(--astl-ink-muted);\n font-size: var(--astl-size-small);\n }\n .astl-notice {\n display: inline-block;\n margin-block: var(--astl-space-1);\n padding-block: var(--astl-space-1);\n padding-inline: var(--astl-space-3);\n border: var(--astl-outline-width) solid var(--astl-warning);\n border-radius: var(--astl-radius-m);\n background: var(--astl-warning-soft);\n color: var(--astl-ink);\n font-size: var(--astl-size-small);\n line-height: 1.4;\n }\n\n .result {\n padding-block: var(--astl-space-4);\n padding-inline: var(--astl-space-5);\n border: var(--astl-outline-width) solid var(--astl-line);\n border-radius: var(--astl-radius-l);\n background: var(--astl-surface);\n }\n .result-title {\n margin-block: 0 var(--astl-space-2);\n font-size: 1.125rem;\n }\n .score {\n margin-block: 0 var(--astl-space-2);\n font-size: 1.25rem;\n font-weight: 700;\n }\n .counts {\n display: flex;\n flex-wrap: wrap;\n gap: var(--astl-space-2) var(--astl-space-4);\n margin: 0;\n padding: 0;\n list-style: none;\n }\n .passed,\n .teacher,\n .practice {\n margin-block: var(--astl-space-2) 0;\n font-weight: 600;\n }\n\n .footer {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: var(--astl-space-3);\n }\n .nav,\n .actions {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: var(--astl-space-2);\n }\n .actions {\n margin-inline-start: auto;\n }\n .hint {\n color: var(--astl-ink-muted);\n font-size: var(--astl-size-small);\n }\n .button {\n box-sizing: border-box;\n min-inline-size: var(--astl-target-min);\n min-block-size: var(--astl-target-min);\n padding-block: var(--astl-space-2);\n padding-inline: var(--astl-space-4);\n border: var(--astl-outline-width) solid var(--astl-outline);\n border-radius: var(--astl-radius-m);\n background: var(--astl-surface);\n color: var(--astl-ink);\n font: inherit;\n font-weight: 600;\n cursor: pointer;\n transition: background-color var(--astl-duration-fast);\n }\n .button:hover {\n background: var(--astl-accent-soft);\n }\n .button.primary {\n border-color: var(--astl-accent);\n background: var(--astl-accent);\n color: var(--astl-on-accent);\n }\n .button.primary:hover {\n text-decoration: underline;\n }\n `,\n // Unavailable, as the authoring kit draws it: a dashed edge and no fill, so it shows without colour too (in hc the\n // line and muted colours are as dark as the enabled ones). A button is never an answer box, so the dashed edge\n // never reads as a verdict.\n css`\n .button:disabled,\n .button[aria-disabled='true'] {\n border-color: var(--astl-line);\n border-style: dashed;\n background: transparent;\n color: var(--astl-ink-muted);\n text-decoration: none;\n cursor: not-allowed;\n }\n .practice-only {\n margin-block: 0;\n color: var(--astl-ink-muted);\n }\n .confirm {\n display: flex;\n flex-wrap: wrap;\n align-items: center;\n gap: var(--astl-space-3);\n inline-size: 100%;\n padding-block: var(--astl-space-3);\n padding-inline: var(--astl-space-4);\n border: var(--astl-outline-width) solid var(--astl-warning);\n border-radius: var(--astl-radius-m);\n background: var(--astl-warning-soft);\n color: var(--astl-ink);\n }\n .confirm p {\n margin-block: 0;\n }\n :focus-visible {\n outline: var(--astl-focus-width) solid var(--astl-focus);\n outline-offset: var(--astl-focus-offset);\n }\n `,\n // Forced colours draw a Canvas backplate behind text, which hides a HighlightText label on a Highlight fill. The\n // filled controls use only system colours there (the forced tokens), so they keep their own.\n css`\n @media (forced-colors: active) {\n .button.primary,\n .segment[aria-current='step'] {\n forced-color-adjust: none;\n }\n }\n `,\n];\n","/**\n * The style template stylesheet: one CSSStyleSheet, generated from every registered template and adopted by every\n * `<astl-player>`, rebuilt in place when registrations change (so mounted players restyle without a reload).\n *\n * - Document scope: on `.root` (canvas and chrome), from `<astl-doc style-template>` (mirrored to\n * `.root[data-style-template]`), else from `<astl-player style-template>` (the host's default).\n * - Component scope: on `.canvas <tag>[style-template]` and its subtree, for the tags the template allows.\n * - Precedence by cascade layers: component, then document, then the player default; tokens reach the component's\n * subtree by inheritance, `::part()` rules of a closer scope win.\n * - Light values for `light`, no theme and `auto` on a light system; dark values for `dark` and for `auto` under\n * `prefers-color-scheme: dark`. Nothing applies in `hc` or under `forced-colors: active`, and under\n * `prefers-reduced-motion: reduce` durations stay zero whatever a template says.\n * - Values are checked again here (`isSafeStyleValue`, `PART_PROPERTIES`): templates are trusted, but one bad value\n * must not break the sheet every player shares.\n */\nimport type { Declarations, StyleTemplate, TokenOverrides } from '@astl/core';\nimport { isSafeStyleValue, PART_PROPERTIES } from '@astl/tokens';\nimport { runtime } from '../runtime.js';\n\n/** The attribute on `.root` that mirrors the mounted view's `<astl-doc style-template>`. */\nexport const DOCUMENT_TEMPLATE_ATTRIBUTE = 'data-style-template';\n\nconst NAME = /^[a-z][a-z0-9-]*$/;\nconst TAG = /^[a-z][a-z0-9]*-[a-z0-9-]*$/;\nconst NOT_HC = ':not([data-theme=\"hc\"])';\n\n/** Token declarations that are safe to write (a bad value is dropped, never allowed to break the sheet). */\nfunction tokenLines(values: TokenOverrides | undefined): string {\n return Object.entries(values ?? {})\n .filter(([name, value]) => NAME.test(name) && isSafeStyleValue(value))\n .map(([name, value]) => ` --astl-${name}: ${value};\\n`)\n .join('');\n}\n\n/** Part declarations: allowed properties (no borders, colours or display: verdicts and focus stay) and safe values. */\nfunction partLines(declarations: Declarations): string {\n return Object.entries(declarations)\n .filter(([property, value]) => PART_PROPERTIES.has(property) && isSafeStyleValue(value))\n .map(([property, value]) => ` ${property}: ${value};\\n`)\n .join('');\n}\n\nconst rule = (selectors: readonly string[], body: string): string =>\n body === '' ? '' : `${selectors.join(',\\n')} {\\n${body}}\\n`;\n\n/**\n * Rules of one template at one place: `host` adds conditions on the player itself, `target` selects inside its shadow\n * root, `parts` maps a component tag to the selector of its elements there.\n */\nfunction templateRules(\n template: StyleTemplate,\n host: string,\n target: string,\n parts: (tag: string) => string | null,\n): string {\n const at = (condition: string) => `:host(${host}${condition}) ${target}`;\n const scheme = (query: string, body: string) =>\n body === '' ? '' : `@media ${query} {\\n${rule([at('[data-theme=\"auto\"]')], body)}}\\n`;\n const light = tokenLines(template.light);\n const dark = tokenLines(template.dark);\n // `auto` takes the light values only when the system is not dark: a value set for light alone must never reach a\n // dark scheme.\n const out = [\n rule([at(NOT_HC)], tokenLines(template.tokens)),\n rule([at(':not([data-theme])'), at('[data-theme=\"light\"]')], light),\n scheme('not all and (prefers-color-scheme: dark)', light),\n rule([at('[data-theme=\"dark\"]')], dark),\n scheme('(prefers-color-scheme: dark)', dark),\n ];\n for (const [tag, byPart] of Object.entries(template.parts ?? {})) {\n const scope = TAG.test(tag) ? parts(tag) : null;\n if (scope === null) continue;\n for (const [part, declarations] of Object.entries(byPart)) {\n if (NAME.test(part))\n out.push(rule([`:host(${host}${NOT_HC}) ${scope}::part(${part})`], partLines(declarations)));\n }\n }\n return out.join('');\n}\n\n/** The stylesheet text for these templates; `tags` are the registered component tags. */\nexport function styleTemplatesCss(templates: readonly StyleTemplate[], tags: readonly string[]): string {\n const valid = templates.filter((t) => NAME.test(t.name));\n const document = valid.filter((t) => t.scopes.includes('document'));\n const component = valid.filter((t) => t.scopes.includes('component'));\n const docAttribute = (name: string) => `[${DOCUMENT_TEMPLATE_ATTRIBUTE}=\"${name}\"]`;\n // The host's default applies only when the view names no document template this player knows.\n const noDocumentTemplate =\n document.length === 0 ? '.root' : `.root:not(${document.map((t) => docAttribute(t.name)).join(', ')})`;\n\n const defaults = document.map((t) =>\n templateRules(\n t,\n `[style-template=\"${t.name}\"]`,\n noDocumentTemplate,\n (tag) => `${noDocumentTemplate} ${tag}`,\n ),\n );\n const documents = document.map((t) => {\n const root = `.root${docAttribute(t.name)}`;\n return templateRules(t, '', root, (tag) => `${root} ${tag}`);\n });\n const components = component.flatMap((t) => {\n const allowed = (t.components ?? tags).filter((tag) => TAG.test(tag));\n const element = (tag: string) => `.canvas ${tag}[style-template=\"${t.name}\"]`;\n // One rule list per tag keeps every selector simple: `.canvas astl-gap[style-template=\"notebook\"]`.\n return allowed.map((tag) =>\n templateRules(t, '', element(tag), (owner) => (owner === tag ? element(tag) : null)),\n );\n });\n const layer = (name: string, rules: readonly string[]) => `@layer ${name} {\\n${rules.join('')}}\\n`;\n return [\n '@layer astl-default, astl-document, astl-component;\\n',\n '@media (forced-colors: none) {\\n',\n layer('astl-default', defaults),\n layer('astl-document', documents),\n layer('astl-component', components),\n '}\\n',\n // Outside the layers, so it beats every template: reduced motion keeps zero durations.\n '@media (prefers-reduced-motion: reduce) {\\n',\n '.root,\\n.canvas [style-template] {\\n --astl-duration-fast: 0ms;\\n --astl-duration-normal: 0ms;\\n}\\n',\n '}\\n',\n ].join('');\n}\n\nlet sheet: CSSStyleSheet | null = null;\nlet built = -1;\n\n/** The one template stylesheet of this module instance, up to date with the registrations. */\nexport function styleTemplateSheet(): CSSStyleSheet {\n sheet ??= new CSSStyleSheet();\n if (built !== runtime.version) {\n sheet.replaceSync(styleTemplatesCss([...runtime.styleTemplates.values()], [...runtime.elements.keys()]));\n built = runtime.version;\n }\n return sheet;\n}\n\n/** After a registration: rebuilds the sheet in place if players already adopted it. */\nexport function refreshStyleTemplateSheet(): void {\n if (sheet !== null) styleTemplateSheet();\n}\n","import {\n type AttributeSpec,\n allAttributes,\n BLOCK_TAGS,\n CAPTION_TAG,\n type ChildSpec,\n COLUMN_TAG,\n COLUMNS_TAG,\n CONTENT_ATTRIBUTES,\n type ComponentManifest,\n DOC_ATTRIBUTES,\n DOC_TAG,\n FIGURE_TAG,\n HELP_ATTRIBUTES,\n INERT_STYLE,\n INLINE_TAGS,\n inertStyles,\n isOpaqueId,\n isSafeUrl,\n PAGE_ATTRIBUTES,\n PAGE_TAG,\n REMOVED_WITH_CONTENT,\n TAG_ATTRIBUTES,\n URL_ATTRIBUTES,\n type UrlPolicy,\n} from '@astl/core';\n\n/** A load failure with a message code (`error.<code>` in the player catalog). */\nexport class LoadError extends Error {\n readonly code: string;\n\n constructor(code: string) {\n super(code);\n this.name = 'LoadError';\n this.code = code;\n }\n}\n\n/** Lowercase hex SHA-256 of the UTF-8 text; null where WebCrypto is unavailable (insecure contexts). */\nexport async function sha256Hex(text: string): Promise<string | null> {\n const subtle = globalThis.crypto?.subtle;\n if (subtle === undefined) return null;\n const digest = await subtle.digest('SHA-256', new TextEncoder().encode(text));\n return Array.from(new Uint8Array(digest), (b) => b.toString(16).padStart(2, '0')).join('');\n}\n\n/** A light-DOM `<astl-doc>` is a compiled view when every id on a custom element in it is opaque. */\nexport function isView(doc: Element): boolean {\n return Array.from(doc.querySelectorAll('[id]'))\n .filter((el) => el.localName.includes('-'))\n .every((el) => isOpaqueId(el.id));\n}\n\n/** Attributes an unknown custom element keeps: enough for the \"unsupported\" notice. */\nconst UNKNOWN_ATTRIBUTES: readonly string[] = ['id', 'v', 'lang', 'dir'];\n\nconst NONE: ReadonlySet<string> = new Set();\nconst POSITIVE_INTEGER = /^[1-9]\\d*$/;\n\n/** What a cleaning pass needs: the manifests of the registered elements and the URL policy. */\nexport interface Cleaning {\n readonly manifests: ReadonlyMap<string, ComponentManifest>;\n readonly urlPolicy: UrlPolicy;\n}\n\n/**\n * Removes every attribute not in `allowed`, and URL attributes whose URL the policy blocks. `style` always goes: a\n * strict CSP would block it. What can be kept of it was taken before the cleaning, under its parsing name (`styled.ts`).\n */\nfunction keepAttributes(\n el: Element,\n allowed: Iterable<string>,\n policy: UrlPolicy = isSafeUrl,\n urls: ReadonlySet<string> = NONE,\n): void {\n const names = new Set(allowed);\n const tag = el.localName;\n for (const { name, value } of Array.from(el.attributes)) {\n const blocked = urls.has(name) && !policy(value, { tag, attribute: name });\n if (name === 'style' || !names.has(name) || blocked) {\n el.removeAttribute(name);\n }\n }\n}\n\n/**\n * A picture keeps `src` (when the policy allows it), `alt`, and `width` and `height` when they are positive integers;\n * one without `src` or `alt` is removed. The player adds lazy loading, asynchronous decoding and no referrer (the\n * picture's host learns nothing of the page, an attempt id in its address say): they are never authored. Returns\n * false when the picture is gone.\n */\nfunction cleanPicture(el: Element, policy: UrlPolicy): boolean {\n keepAttributes(el, [...CONTENT_ATTRIBUTES, ...(TAG_ATTRIBUTES.img ?? [])], policy, new Set(['src']));\n for (const name of ['width', 'height']) {\n if (!POSITIVE_INTEGER.test(el.getAttribute(name) ?? '1')) el.removeAttribute(name);\n }\n if (!el.getAttribute('src') || !el.hasAttribute('alt')) {\n el.remove();\n return false;\n }\n el.replaceChildren();\n el.setAttribute('loading', 'lazy');\n el.setAttribute('decoding', 'async');\n el.setAttribute('referrerpolicy', 'no-referrer');\n return true;\n}\n\n/**\n * A figure keeps its picture and its caption (rich inline text, and inline components unless it is inside one),\n * nothing else.\n */\nfunction cleanFigure(el: Element, cleaning: Cleaning, components: boolean): void {\n keepAttributes(el, CONTENT_ATTRIBUTES);\n for (const node of Array.from(el.childNodes)) {\n if (node.nodeType === Node.TEXT_NODE) continue;\n const child = node as Element;\n if (node.nodeType !== Node.ELEMENT_NODE) node.remove();\n else if (child.localName === 'img') cleanPicture(child, cleaning.urlPolicy);\n else if (child.localName === CAPTION_TAG) {\n keepAttributes(child, CONTENT_ATTRIBUTES);\n cleanContent(child, cleaning, true, components);\n } else child.remove();\n }\n}\n\n/**\n * Rich text and components, recursively. `inline` content (an option, a prompt) keeps inline tags only, and with\n * `components` (a caption) inline components too. The content of a rich block (`host`) keeps blocks and the host's\n * public children. Dangerous elements go with their content; other unknown HTML is unwrapped; unknown custom elements\n * stay (with no content) so the player can show its \"unsupported\" notice in their place.\n */\nexport function cleanContent(\n parent: Element,\n cleaning: Cleaning,\n inline: boolean,\n components: boolean = !inline,\n host?: ComponentManifest,\n): void {\n const { manifests, urlPolicy } = cleaning;\n for (const node of Array.from(parent.childNodes)) {\n if (node.nodeType === Node.TEXT_NODE) continue;\n if (node.nodeType !== Node.ELEMENT_NODE) {\n node.remove();\n continue;\n }\n const el = node as Element;\n const tag = el.localName;\n const spec = host && publicChild(host, tag);\n if (REMOVED_WITH_CONTENT.has(tag)) {\n el.remove();\n } else if (tag === PAGE_TAG && components && !inline) {\n keepAttributes(el, [...PAGE_ATTRIBUTES, ...HELP_ATTRIBUTES]);\n cleanContent(el, cleaning, false);\n } else if ((tag === COLUMNS_TAG || tag === COLUMN_TAG) && components && !inline) {\n keepAttributes(el, CONTENT_ATTRIBUTES);\n cleanContent(el, cleaning, false);\n } else if (tag === 'img') {\n cleanPicture(el, urlPolicy);\n } else if (tag === FIGURE_TAG && !inline) {\n cleanFigure(el, cleaning, components);\n } else if (INLINE_TAGS.has(tag) || (BLOCK_TAGS.has(tag) && !inline)) {\n const url = URL_ATTRIBUTES[tag];\n const allowed = [...CONTENT_ATTRIBUTES, ...(TAG_ATTRIBUTES[tag] ?? [])];\n keepAttributes(el, allowed, urlPolicy, url === undefined ? NONE : new Set([url]));\n cleanContent(el, cleaning, inline, components, host);\n } else if (spec) {\n cleanChild(el, spec, cleaning);\n } else if (\n components &&\n manifests.has(tag) &&\n (!inline || (manifests.get(tag) as ComponentManifest).display === 'inline')\n ) {\n cleanComponent(el, manifests.get(tag) as ComponentManifest, cleaning);\n } else if (tag.includes('-') && tag !== DOC_TAG && tag !== PAGE_TAG) {\n keepAttributes(el, UNKNOWN_ATTRIBUTES);\n el.replaceChildren();\n } else {\n cleanContent(el, cleaning, inline, components, host);\n el.replaceWith(...Array.from(el.childNodes));\n }\n }\n}\n\nconst publicChild = (manifest: ComponentManifest, tag: string): ChildSpec | undefined =>\n manifest.children.find((c) => c.tag === tag && c.visibility === 'public');\n\n/**\n * Keeps `lang`, `dir`, the public and derived attributes of `specs` and the `extra` ones, URLs only where the policy\n * allows them.\n */\nfunction keepPublic(\n el: Element,\n specs: readonly AttributeSpec[],\n cleaning: Cleaning,\n extra: readonly string[] = [],\n): void {\n const kept = specs.filter((a) => a.visibility !== 'private');\n keepAttributes(\n el,\n [...CONTENT_ATTRIBUTES, ...kept.map((a) => a.name), ...extra],\n cleaning.urlPolicy,\n new Set(kept.filter((a) => a.type === 'url').map((a) => a.name)),\n );\n}\n\n/** A declared public child: its public attributes, and its text or rich inline content. */\nfunction cleanChild(child: Element, spec: ChildSpec, cleaning: Cleaning): void {\n keepPublic(child, spec.attributes, cleaning);\n if (spec.content === 'text') child.textContent = child.textContent ?? '';\n else cleanContent(child, cleaning, true);\n}\n\n/**\n * A component keeps `id`, `v`, `lang`, `dir`, its public and derived attributes (the engine's view keeps a\n * component's language) and what it offers of help (`HELP_ATTRIBUTES`), and its declared public children; a rich\n * block also keeps its rich content around them.\n */\nfunction cleanComponent(el: Element, manifest: ComponentManifest, cleaning: Cleaning): void {\n keepPublic(el, allAttributes(manifest), cleaning, manifest.graded ? HELP_ATTRIBUTES : []);\n if (manifest.content === 'flow') {\n cleanContent(el, cleaning, false, false, manifest);\n return;\n }\n for (const node of Array.from(el.childNodes)) {\n if (node.nodeType === Node.TEXT_NODE) continue;\n const spec = publicChild(manifest, (node as Element).localName);\n if (node.nodeType !== Node.ELEMENT_NODE || spec === undefined) node.remove();\n else cleanChild(node as Element, spec, cleaning);\n }\n}\n\n/**\n * Parses a view into an inert fragment (template content: no scripts run, nothing loads, no elements upgrade) that\n * holds one `<astl-doc>`. Not cleaned yet: the manifests of its lazy elements may still have to load.\n */\nexport function readView(view: string): DocumentFragment {\n const template = document.createElement('template');\n template.innerHTML = inertStyles(view);\n const roots = Array.from(template.content.children);\n const doc = roots[0];\n if (roots.length !== 1 || doc === undefined || doc.localName !== DOC_TAG)\n throw new LoadError('view_invalid');\n for (const node of Array.from(template.content.childNodes)) if (node !== doc) node.remove();\n return template.content;\n}\n\n/** The custom element tags in a read view: the lazy elements to load before it is cleaned. */\nexport function viewTags(fragment: DocumentFragment): Set<string> {\n return new Set(\n Array.from(fragment.querySelectorAll('*'), (el) => el.localName).filter(\n (tag) => tag.includes('-') && tag !== COLUMNS_TAG && tag !== COLUMN_TAG,\n ),\n );\n}\n\n/** Whether a read view offers help (hints, explanations, feedback): then the help module loads with it. */\nexport function hasHelp(fragment: DocumentFragment): boolean {\n return fragment.querySelector(HELP_ATTRIBUTES.map((name) => `[${name}]`).join()) !== null;\n}\n\n/** Whether a read view is a book (`kind=\"book\"` on its `astl-doc`): then the book's module loads with it. */\nexport function isBook(fragment: DocumentFragment): boolean {\n return fragment.firstElementChild?.getAttribute('kind') === 'book';\n}\n\n/** Whether a read view needs the module of styles and layouts. */\nexport function isStyled(fragment: DocumentFragment): boolean {\n return fragment.querySelector(`[${INERT_STYLE}],${COLUMNS_TAG}`) !== null;\n}\n\n/**\n * Cleans a read view in place. Views are engine output; the cleaning is defence in depth against a tampered or\n * hand-edited view: the content format's allow-list (`@astl/core` content.ts), each registered component's\n * manifest and the URL policy (the engine's, so the URLs it kept stay).\n */\nexport function cleanView(\n fragment: DocumentFragment,\n manifests: ReadonlyMap<string, ComponentManifest>,\n urlPolicy: UrlPolicy = isSafeUrl,\n): DocumentFragment {\n const doc = fragment.firstElementChild as Element;\n keepAttributes(doc, DOC_ATTRIBUTES);\n cleanContent(doc, { manifests, urlPolicy }, false);\n return fragment;\n}\n\n/** `readView` and `cleanView` in one step, for views whose elements are all loaded. */\nexport function parseView(\n view: string,\n manifests: ReadonlyMap<string, ComponentManifest>,\n urlPolicy: UrlPolicy = isSafeUrl,\n): DocumentFragment {\n return cleanView(readView(view), manifests, urlPolicy);\n}\n","/**\n * `<astl-player>`: mounts a view, attaches component elements, renders the chrome (pages, actions, results) and\n * drives an AttemptController. It never holds answer logic: verdicts come from a Checker.\n */\nimport {\n type Answers,\n type AttemptPolicy,\n type AttemptState,\n type ChangeDetail,\n type Checker,\n CheckerError,\n type CheckResponse,\n COLUMN_TAG,\n COLUMNS_TAG,\n type ComponentManifest,\n createI18n,\n directionOf,\n type ErrorDetail,\n fitsAnswer,\n type GradeResult,\n type GroupVerdict,\n type I18n,\n isSnapshot,\n type JsonValue,\n negotiateLocale,\n OPEN_SLOT_KIND,\n type PageDetail,\n type PlayerElementApi,\n PlayerEvent,\n PRACTICE_POLICY,\n type ReadyDetail,\n roundScore,\n type SlotVerdict,\n type Snapshot,\n STYLE_TEMPLATE_ATTRIBUTE,\n type StateDetail,\n type SubmitResponse,\n type Translate,\n} from '@astl/core';\nimport type { ThemeSetting } from '@astl/tokens';\nimport {\n type CSSResultGroup,\n html,\n LitElement,\n nothing,\n type PropertyDeclarations,\n type PropertyValues,\n supportsAdoptingStyleSheets,\n type TemplateResult,\n} from 'lit';\nimport { announce, verdictIcon } from '../a11y.js';\nimport { type AttemptChange, AttemptController } from '../attempt/controller.js';\nimport { httpChecker } from '../checker/http.js';\nimport { elementTranslator, PLAYER_NAMESPACE, playerMessages } from '../messages.js';\nimport { loadElements, runtime } from '../runtime.js';\nimport type { Help } from './help.js';\nimport { playerStyles } from './styles.js';\nimport { refreshStyleTemplateSheet, styleTemplateSheet } from './templates.js';\nimport {\n cleanView,\n hasHelp,\n isBook,\n isStyled,\n isView,\n LoadError,\n readView,\n sha256Hex,\n viewTags,\n} from './view.js';\n\ntype PlayerElement = HTMLElement & PlayerElementApi;\n\ninterface Mounted {\n readonly element: PlayerElement;\n readonly manifest: ComponentManifest;\n /** Page index. */\n readonly page: number;\n}\n\n/** What `load()` accepts; omitted fields keep the player's current properties. */\nexport interface LoadInput {\n readonly view: string;\n readonly policy?: AttemptPolicy;\n readonly checker?: Checker | null;\n readonly snapshot?: Snapshot | null;\n}\n\ntype PageState = 'done' | 'partial' | 'none';\n\nconst STORAGE_PREFIX = 'astl:snapshot:';\nconst SNAPSHOT_DELAY_MS = 300;\nconst VERDICTS: readonly GroupVerdict[] = ['correct', 'partial', 'incorrect', 'empty'];\n/** Minutes left at which the timer is announced. */\nconst TIMER_ALERTS: readonly number[] = [5, 1];\nconst THEMES: readonly ThemeSetting[] = ['light', 'dark', 'hc', 'auto'];\n\n/**\n * Page progress icons (decorative: the visually hidden text says the same): how full a page is, a circle filled from\n * the bottom, half or whole. Never a verdict glyph (a tick, or the half circle split down the middle): answering says\n * nothing about right or wrong.\n */\nconst PROGRESS_ICONS: Readonly<Record<PageState, TemplateResult | typeof nothing>> = {\n done: html`<svg class=\"segment-icon\" data-icon=\"done\" viewBox=\"0 0 20 20\" aria-hidden=\"true\" focusable=\"false\">\n <circle cx=\"10\" cy=\"10\" r=\"7\" fill=\"currentColor\" stroke=\"currentColor\" stroke-width=\"2.5\" />\n </svg>`,\n partial: html`<svg class=\"segment-icon\" data-icon=\"partial\" viewBox=\"0 0 20 20\" aria-hidden=\"true\" focusable=\"false\">\n <circle cx=\"10\" cy=\"10\" r=\"7\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.5\" />\n <path d=\"M3 10a7 7 0 0 0 14 0z\" fill=\"currentColor\" />\n </svg>`,\n none: nothing,\n};\n\nfunction pick(values: Readonly<Record<string, string>>, ids: readonly string[]): Record<string, string> {\n const out: Record<string, string> = {};\n for (const id of ids) {\n const value = values[id];\n if (value !== undefined) out[id] = value;\n }\n return out;\n}\n\nfunction codeOf(error: unknown, fallback: string): string {\n if (error instanceof CheckerError) return error.problem.code;\n if (error instanceof LoadError) return error.code;\n const code = (error as { code?: unknown } | null)?.code;\n return typeof code === 'string' && code !== '' ? code : fallback;\n}\n\nfunction clock(ms: number): string {\n const seconds = Math.ceil(ms / 1000);\n const pad = (n: number) => String(n).padStart(2, '0');\n return `${pad(Math.floor(seconds / 60))}:${pad(seconds % 60)}`;\n}\n\nexport class AstlPlayer extends LitElement {\n static override properties: PropertyDeclarations = {\n view: { attribute: false },\n policy: { attribute: false },\n checker: { attribute: false },\n snapshot: { attribute: false },\n locale: {},\n src: {},\n integrity: {},\n endpoint: {},\n theme: {},\n styleTemplate: { attribute: STYLE_TEMPLATE_ATTRIBUTE, reflect: true },\n persist: { type: Boolean },\n };\n\n static override styles: CSSResultGroup = playerStyles;\n\n /** View HTML to play (compiled, no answers). Setting it loads it. */\n declare view: string;\n declare policy: AttemptPolicy;\n /** Grades checks and submits. Default: an HTTP checker for `endpoint`, if set. */\n declare checker: Checker | null;\n /** Restored on load when its viewHash matches the view (or is null). */\n declare snapshot: Snapshot | null;\n /** UI locale; default: the `lang` attribute, else the browser languages. */\n declare locale: string | null;\n /** URL of a view to fetch when no view is given. */\n declare src: string | null;\n /** Lowercase hex SHA-256 the fetched `src` must match. */\n declare integrity: string | null;\n /** Grading endpoint (protocol 1) of this attempt. */\n declare endpoint: string | null;\n declare theme: ThemeSetting | null;\n /**\n * The host's default style template (a registered template with the `document` scope), used when the view's\n * `<astl-doc>` names none that this player knows.\n */\n declare styleTemplate: string | null;\n /** Keep snapshots in localStorage (per view hash) and restore them on load. */\n declare persist: boolean;\n\n #state: AttemptState = 'loading';\n #generation = 0;\n /** The view string being mounted or mounted. */\n #source: string | null = null;\n #viewHash: string | null = null;\n /** `style-template` of the mounted view's `<astl-doc>`. */\n #documentTemplate: string | null = null;\n #mountedLocale: string | null = null;\n #controller: AttemptController | null = null;\n #unsubscribe: (() => void) | null = null;\n /** The rows of hints, feedback and explanations, when the view offers help. */\n #help: Help | null = null;\n #mounted: Mounted[] = [];\n #pages: HTMLElement[] = [];\n /** The mounted view's `astl-doc`. */\n #doc: HTMLElement | null = null;\n /** A book's module (`kind=\"book\"`, more than one page), loaded with it (player/book.ts); null for anything else. */\n #book: typeof import('./book.js') | null = null;\n /** Whether the book shows two pages side by side now: its module says the player is wide enough. */\n #spread = false;\n #resize: ResizeObserver | null = null;\n /** Page headings, null where a page has none (a single page without a label). */\n #headings: (HTMLElement | null)[] = [];\n #sourceChecker: Checker | null = null;\n #endpointChecker: { readonly endpoint: string; readonly checker: Checker } | null = null;\n #loadError: string | null = null;\n /** Plain-text details of a failed source compile, for the author. */\n #loadDetails: string | null = null;\n /** Problem code of the last failed check or submit, shown until the next one. */\n #problem: string | null = null;\n #confirming = false;\n #snapshotTimer: ReturnType<typeof setTimeout> | undefined;\n #clock: ReturnType<typeof setInterval> | undefined;\n #alerted = new Set<number>();\n #autoSubmitted = false;\n #i18nCache: { readonly version: number; readonly i18n: I18n } | null = null;\n\n /** The controller's checker: resolves the effective checker on every call. */\n #checkerProxy: Checker = {\n check: (request) => this.#requireChecker().check(request),\n submit: (request) => this.#requireChecker().submit(request),\n };\n\n constructor() {\n super();\n this.view = '';\n this.policy = PRACTICE_POLICY;\n this.checker = null;\n this.snapshot = null;\n this.locale = null;\n this.src = null;\n this.integrity = null;\n this.endpoint = null;\n this.theme = 'auto';\n this.styleTemplate = null;\n this.persist = false;\n }\n\n /** `loading`, `ready`, `active`, `checking`, `submitting`, `submitted`, `review` or `error`. */\n get state(): AttemptState {\n return this.#state;\n }\n\n /** Lowercase hex SHA-256 of the mounted view; null before mounting or without WebCrypto. */\n get viewHash(): string | null {\n return this.#viewHash;\n }\n\n /** 0-based index of the current page. */\n get page(): number {\n return this.#controller?.page ?? 0;\n }\n\n /** Plays a view. Resolves when it is mounted (`astl-ready`); rejects with the error code when it cannot. */\n async load(input: LoadInput): Promise<void> {\n if (input.policy !== undefined) this.policy = input.policy;\n if (input.checker !== undefined) this.checker = input.checker;\n if (input.snapshot !== undefined) this.snapshot = input.snapshot;\n this.view = input.view;\n await this.#loadView(input.view);\n }\n\n /**\n * Practice: grades the answers and shows verdicts; with `element` (a view element id, under a policy with\n * `checkScope: 'interaction'`) that interaction only, which is not an `astl-result`. Failures are shown and emitted,\n * never thrown.\n */\n async check(element?: string): Promise<CheckResponse | null> {\n const controller = this.#controller;\n if (controller === null) return null;\n this.#problem = null;\n if (this.#effectiveChecker() === null) {\n this.#showProblem('no_checker');\n return null;\n }\n try {\n return await (element === undefined ? controller.check() : controller.checkElement(element));\n } catch (error) {\n this.#showProblem(codeOf(error, 'internal_error'));\n return null;\n }\n }\n\n /** Hands the answers in (final). Failures are shown and emitted, never thrown. */\n async submit(): Promise<SubmitResponse | null> {\n const controller = this.#controller;\n if (controller === null) return null;\n this.#problem = null;\n this.#confirming = false;\n if (this.#effectiveChecker() === null) {\n this.#showProblem('no_checker');\n return null;\n }\n try {\n const response = await controller.submit();\n await this.updateComplete;\n this.#query('.result')?.focus();\n return response;\n } catch (error) {\n this.#showProblem(codeOf(error, 'internal_error'));\n return null;\n }\n }\n\n goTo(index: number): boolean {\n return this.#controller?.goTo(index) ?? false;\n }\n\n /** The next page, or in a spread the next spread. */\n next(): boolean {\n return this.#controller?.goTo(this.#step(1)) ?? false;\n }\n\n /** The previous page, or in a spread the previous spread. */\n previous(): boolean {\n return this.#controller?.goTo(this.#step(-1)) ?? false;\n }\n\n /** Clears answers and results and goes back to the first page (not after submitting). */\n reset(): boolean {\n return this.#controller?.reset() ?? false;\n }\n\n getAnswers(): Answers {\n return this.#controller?.answers ?? {};\n }\n\n /**\n * Sets answers programmatically (`''` clears); no change events from elements. The attempt keeps what the\n * elements accept (an unknown option id or a flag other than \"true\" is dropped), so what is checked and handed\n * in is always what the student sees.\n */\n setAnswers(answers: Answers): void {\n const controller = this.#controller;\n if (controller === null || controller.readOnly) return;\n const accepted: Record<string, string> = {};\n const touched: PlayerElement[] = [];\n for (const { element } of this.#mounted) {\n const own = pick(answers, element.slotIds);\n if (Object.keys(own).length === 0) continue;\n element.setAnswers(own);\n const shown = element.getAnswers();\n for (const id of element.slotIds) accepted[id] = shown[id] ?? '';\n touched.push(element);\n }\n const changed = controller.setAnswers(accepted);\n for (const element of touched) {\n if (element.slotIds.some((id) => id in changed)) element.feedback = null;\n }\n this.requestUpdate();\n }\n\n getSnapshot(): Snapshot | null {\n return this.#controller?.snapshot(this.#uiState()) ?? null;\n }\n\n override connectedCallback(): void {\n super.connectedCallback();\n this.#syncClock();\n this.#resize?.observe(this);\n void this.#autoload();\n }\n\n /** The shadow root also adopts the style template stylesheet, shared by every player and kept up to date. */\n protected override createRenderRoot(): HTMLElement | DocumentFragment {\n const root = super.createRenderRoot();\n if (supportsAdoptingStyleSheets && root instanceof ShadowRoot) {\n root.adoptedStyleSheets = [...root.adoptedStyleSheets, styleTemplateSheet()];\n }\n return root;\n }\n\n override disconnectedCallback(): void {\n super.disconnectedCallback();\n this.#flushSnapshot();\n this.#syncClock();\n this.#resize?.disconnect();\n }\n\n protected override firstUpdated(): void {\n this.#query('.canvas')?.addEventListener(PlayerEvent.change, (event) => {\n const detail = (event as CustomEvent<ChangeDetail>).detail;\n if (detail?.answers) this.#controller?.setAnswers(detail.answers);\n this.requestUpdate();\n });\n }\n\n protected override updated(changed: PropertyValues<this>): void {\n if (changed.has('theme')) this.dataset.theme = this.#theme();\n if (changed.has('view') && this.view !== '' && this.view !== this.#source) {\n void this.#loadView(this.view).catch(() => undefined);\n return;\n }\n if (changed.has('src') && changed.get('src') !== undefined && this.src && this.view === '') {\n void this.#loadSrc(this.src).catch(() => undefined);\n return;\n }\n const controller = this.#controller;\n const policyChanged = changed.has('policy') && controller !== null && controller.policy !== this.policy;\n const localeChanged =\n changed.has('locale') && controller !== null && this.#mountedLocale !== this.#uiLocale();\n if ((policyChanged || localeChanged) && this.#source !== null) {\n void this.#loadView(this.#source, this.getSnapshot(), this.#sourceChecker).catch(() => undefined);\n }\n }\n\n protected override render(): TemplateResult {\n const locale = this.#uiLocale();\n const t = this.#i18n().translator(locale, PLAYER_NAMESPACE);\n const controller = this.#controller;\n return html`<div\n class=\"root\"\n part=\"player\"\n lang=${locale}\n dir=${directionOf(locale)}\n data-style-template=${this.#documentTemplate ?? nothing}\n ?data-spread=${this.#spread}\n aria-busy=${this.#state === 'loading' ? 'true' : 'false'}\n >\n ${this.#state === 'loading' ? html`<p class=\"status\">${t('loading')}</p>` : nothing}\n ${this.#loadError === null ? nothing : html`<p class=\"problem\">${this.#errorMessage(t, this.#loadError)}</p>`}\n ${\n this.#loadDetails === null\n ? nothing\n : html`<div class=\"problem-details\" part=\"problem-details\" role=\"alert\">${this.#loadDetails}</div>`\n }\n ${controller === null ? nothing : this.#renderHeader(controller, t)}\n <div class=\"canvas\" part=\"canvas\" tabindex=\"-1\" ?hidden=${controller === null}></div>\n ${controller === null ? nothing : this.#renderResult(controller, t)}\n ${this.#problem === null ? nothing : html`<p class=\"problem\">${this.#errorMessage(t, this.#problem)}</p>`}\n ${controller === null ? nothing : this.#renderFooter(controller, t)}\n <div class=\"astl-vh live\" aria-live=\"polite\"></div>\n </div>`;\n }\n\n #renderHeader(c: AttemptController, t: Translate): TemplateResult | typeof nothing {\n const pages = c.pageCount > 1;\n const left = c.readOnly ? null : c.timeLeft();\n if (!pages && left === null) return nothing;\n return html`<div class=\"header\" part=\"header\">\n ${\n pages\n ? html`<p class=\"counter\">${this.#counter(c, t)}</p>\n <nav aria-label=${t('progress.label')}>\n <ol class=\"progress\">\n ${c.pages.map((_, index) => this.#renderSegment(c, t, index))}\n </ol>\n </nav>`\n : nothing\n }\n ${\n left === null\n ? nothing\n : html`<p class=\"timer\">\n <span class=\"timer-label\" id=\"timer-label\">${t('timer.label')}</span>\n <span role=\"timer\" aria-labelledby=\"timer-label\">${clock(left)}</span>\n </p>`\n }\n </div>`;\n }\n\n /** \"Strona 2 z 4\", or in a spread \"Strony 1-2 z 4\". */\n #counter(c: AttemptController, t: Translate): string {\n const [first, last] = this.#shown(c.page);\n return last > first\n ? t('page.counter.spread', { from: first + 1, to: last + 1, total: c.pageCount })\n : t('page.counter', { n: first + 1, total: c.pageCount });\n }\n\n #renderSegment(c: AttemptController, t: Translate, index: number): TemplateResult {\n const state = this.#pageState(index);\n const [first, last] = this.#shown(c.page);\n // Both pages of a spread are on screen: both are current.\n const current = index >= first && index <= last ? 'step' : nothing;\n const label = html`<span aria-hidden=\"true\">${index + 1}</span>${PROGRESS_ICONS[state]}<span class=\"astl-vh\"\n >${t('progress.item', { n: index + 1, state })}</span\n >`;\n // Linear attempts show progress only: there is nowhere to jump to.\n const linear = c.policy.navigation === 'linear' && !c.readOnly;\n return html`<li>\n ${\n linear\n ? html`<span class=\"segment\" data-state=${state} aria-current=${current}>${label}</span>`\n : html`<button\n type=\"button\"\n class=\"segment\"\n data-state=${state}\n aria-current=${current}\n @click=${() => this.goTo(index)}\n >\n ${label}\n </button>`\n }\n </li>`;\n }\n\n #renderResult(c: AttemptController, t: Translate): TemplateResult | typeof nothing {\n const response = c.response;\n if (response === null) return nothing;\n const result = response.result;\n const passed = 'passed' in response ? response.passed : null;\n const scored = result !== null && this.#scored(result);\n const teacher = this.#teacherText(t, response);\n // Nothing graded and nothing for the teacher (flash cards alone): practice only, instead of a score.\n const practice = result !== null && !scored && teacher === null;\n return html`<section class=\"result\" part=\"result\" tabindex=\"-1\" aria-labelledby=\"result-title\">\n <h2 class=\"result-title\" id=\"result-title\">${t('result.title')}</h2>\n ${\n result === null\n ? html`<p>${t('result.submitted')} ${t('result.later')}</p>`\n : html`${\n scored\n ? html`<p class=\"score\">${this.#scoreText(t, result)}</p>\n <ul class=\"counts\">\n ${VERDICTS.filter((v) => result.counts[v] > 0).map(\n (v) =>\n html`<li class=\"astl-verdict\" data-verdict=${v}>\n ${verdictIcon(v)}<span>${t('result.count', { verdict: t(`verdict.${v}`), count: result.counts[v] })}</span>\n </li>`,\n )}\n </ul>`\n : nothing\n }\n ${teacher === null ? nothing : html`<p class=\"teacher\">${teacher}</p>`}\n ${practice ? html`<p class=\"practice\">${t('result.practice')}</p>` : nothing}\n ${passed === null || !scored ? nothing : html`<p class=\"passed\">${t(passed ? 'result.passed' : 'result.notPassed')}</p>`}`\n }\n </section>`;\n }\n\n /** Whether a result has a score to show: something graded. */\n #scored(result: GradeResult): boolean {\n return result.max > 0;\n }\n\n /**\n * The line about the answers of ungraded components (open answers, for the teacher), or null without any: sent to\n * the teacher by a submit (how many, next to a score), not checked by a check.\n */\n #teacherText(t: Translate, response: CheckResponse | SubmitResponse): string | null {\n const open = this.#openAnswers();\n if (open.slots === 0 || response.result === null) return null;\n if (!('submittedAt' in response)) return t('result.teacher.unchecked');\n return response.result.max === 0\n ? t('result.teacher.sent')\n : t('result.teacher.count', { count: open.answered });\n }\n\n /**\n * Slots of ungraded components (open answers: optional, never graded), and how many hold an answer the server keeps:\n * one longer than its kind allows is never stored, so it never counts as sent.\n */\n #openAnswers(): { readonly slots: number; readonly answered: number } {\n const answers = this.#controller?.answers ?? {};\n let slots = 0;\n let answered = 0;\n for (const { element, manifest } of this.#mounted) {\n if (manifest.graded) continue;\n const kind = manifest.slotKinds[0] ?? OPEN_SLOT_KIND;\n for (const id of element.slotIds) {\n slots++;\n const value = answers[id] ?? '';\n if (value !== '' && fitsAnswer(value, kind)) answered++;\n }\n }\n return { slots, answered };\n }\n\n #renderFooter(c: AttemptController, t: Translate): TemplateResult | typeof nothing {\n const pages = c.pageCount > 1;\n const actions = this.#renderActions(c, t);\n if (!pages && actions === nothing) return nothing;\n const linear = c.policy.navigation === 'linear' && !c.readOnly;\n return html`<div class=\"footer\" part=\"footer\">\n ${\n pages\n ? html`<div class=\"nav\">\n ${\n linear\n ? nothing\n : html`<button\n type=\"button\"\n class=\"button\"\n ?disabled=${!c.canGoTo(this.#step(-1))}\n @click=${() => this.previous()}\n >\n ${t('nav.previous')}\n </button>`\n }\n <button type=\"button\" class=\"button\" ?disabled=${!c.canGoTo(this.#step(1))} @click=${() => this.next()}>\n ${t('nav.next')}\n </button>\n </div>`\n : nothing\n }\n ${actions}\n </div>`;\n }\n\n #renderActions(c: AttemptController, t: Translate): TemplateResult | typeof nothing {\n if (c.readOnly) return nothing;\n if (this.#confirming) {\n return html`<div\n class=\"confirm\"\n role=\"group\"\n tabindex=\"-1\"\n aria-labelledby=\"confirm-text\"\n @keydown=${(event: KeyboardEvent) => {\n if (event.key === 'Escape') this.#cancelConfirm();\n }}\n >\n <p id=\"confirm-text\">${t('confirm.empty', { count: this.#emptyCount() })}</p>\n <div class=\"actions\">\n <button type=\"button\" class=\"button\" @click=${() => this.#cancelConfirm()}>${t('confirm.cancel')}</button>\n <button type=\"button\" class=\"button primary\" @click=${() => void this.submit()}>\n ${t('confirm.submit')}\n </button>\n </div>\n </div>`;\n }\n if (c.policy.mode === 'practice') {\n // Nothing to answer (flash cards, media, text alone): no Check and no Start over, which would lead nowhere, but\n // the practice-only line from the start (once a result shows, it says so).\n if (!this.#mounted.some(({ element }) => element.slotIds.length > 0)) {\n return c.result === null ? html`<p class=\"practice-only\">${t('result.practice')}</p>` : nothing;\n }\n const left = c.checksLeft;\n return html`<div class=\"actions\">\n ${left === null ? nothing : html`<span class=\"hint\">${t('checks.left', { count: left })}</span>`}\n ${\n c.result === null\n ? nothing\n : html`<button type=\"button\" class=\"button\" @click=${() => this.reset()}>${t('action.reset')}</button>`\n }\n <button\n type=\"button\"\n class=\"button primary\"\n aria-disabled=${c.canCheck() ? nothing : 'true'}\n @click=${() => {\n if (c.canCheck()) void this.check();\n }}\n >\n ${t('action.check')}\n </button>\n </div>`;\n }\n if (c.policy.mode === 'test') {\n return html`<div class=\"actions\">\n <button\n type=\"button\"\n class=\"button primary\"\n aria-disabled=${c.canSubmit() ? nothing : 'true'}\n @click=${() => this.#onSubmit()}\n >\n ${t('action.submit')}\n </button>\n </div>`;\n }\n return nothing;\n }\n\n #onSubmit(): void {\n if (!this.#controller?.canSubmit()) return;\n if (this.#emptyCount() === 0) {\n void this.submit();\n return;\n }\n this.#confirming = true;\n this.requestUpdate();\n void this.updateComplete.then(() => this.#query('.confirm')?.focus());\n }\n\n #cancelConfirm(): void {\n this.#confirming = false;\n this.requestUpdate();\n void this.updateComplete.then(() => this.#query('.actions .primary')?.focus());\n }\n\n #scoreText(t: Translate, result: GradeResult): string {\n return t('result.score', { score: roundScore(result.score), max: roundScore(result.max) });\n }\n\n #resultAnnouncement(t: Translate): string | null {\n const response = this.#controller?.response ?? null;\n if (response === null) return null;\n const result = response.result;\n if (result === null) return `${t('result.submitted')} ${t('result.later')}`;\n const scored = this.#scored(result);\n const parts = scored ? [t('result.announce', { score: this.#scoreText(t, result) })] : [];\n for (const v of VERDICTS) {\n const count = result.counts[v];\n if (count > 0) parts.push(t('result.countAnnounce', { verdict: t(`verdict.${v}`), count }));\n }\n const teacher = this.#teacherText(t, response);\n if (teacher !== null) parts.push(teacher);\n else if (!scored) parts.push(t('result.practice'));\n const passed = 'passed' in response ? response.passed : null;\n if (passed !== null && scored) parts.push(t(passed ? 'result.passed' : 'result.notPassed'));\n return parts.join(' ');\n }\n\n #errorMessage(t: Translate, code: string): string {\n const key = `error.${code}`;\n const message = t(key);\n return message === key ? t('error.internal_error') : message;\n }\n\n // Loading\n\n async #autoload(): Promise<void> {\n if (document.readyState === 'loading') {\n await new Promise((resolve) => document.addEventListener('DOMContentLoaded', resolve, { once: true }));\n }\n await this.updateComplete;\n if (this.#generation > 0 || this.view !== '') return;\n const doc = this.querySelector('astl-doc');\n if (doc !== null) await this.#loadLightDom(doc).catch(() => undefined);\n else if (this.src) await this.#loadSrc(this.src).catch(() => undefined);\n }\n\n /** Light-DOM content: a view plays directly, a source (author ids, answers) goes through `compileSource`. */\n async #loadLightDom(doc: Element): Promise<void> {\n if (isView(doc)) return this.#loadView(doc.outerHTML);\n const generation = this.#begin();\n const compile = runtime.compileSource;\n if (compile === null) throw this.#fail('source_needs_compiler');\n const lang =\n doc.getAttribute('lang') ||\n doc.parentElement?.closest('[lang]')?.getAttribute('lang') ||\n document.documentElement.lang ||\n '';\n // Serialise through an inert template: the page's own DOM stays untouched.\n const template = document.createElement('template');\n template.innerHTML = doc.outerHTML;\n const copy = template.content.firstElementChild;\n if (lang !== '' && copy !== null && !copy.getAttribute('lang')) copy.setAttribute('lang', lang);\n let compiled: Awaited<ReturnType<typeof compile>>;\n try {\n compiled = await compile(template.innerHTML, { lang, locale: this.#uiLocale() });\n } catch (error) {\n // The compiler's message lists the issues for the author; text only, never parsed as HTML.\n const details = error instanceof Error ? error.message : typeof error === 'string' ? error : '';\n if (generation === this.#generation)\n throw this.#fail(codeOf(error, 'source_invalid'), details.trim() || null);\n return;\n }\n if (generation !== this.#generation) return;\n await this.#loadView(compiled.view, undefined, compiled.checker);\n }\n\n async #loadSrc(src: string): Promise<void> {\n const generation = this.#begin();\n let text: string;\n try {\n const response = await fetch(src);\n if (!response.ok) throw new LoadError('load_failed');\n text = await response.text();\n } catch {\n if (generation === this.#generation) throw this.#fail('load_failed');\n return;\n }\n if (generation !== this.#generation) return;\n if (this.integrity !== null) {\n const actual = await sha256Hex(text).catch(() => null);\n if (generation !== this.#generation) return;\n if (actual === null || actual !== this.integrity.trim().toLowerCase())\n throw this.#fail('integrity_mismatch');\n }\n await this.#loadView(text);\n }\n\n async #loadView(view: string, snapshot?: Snapshot | null, sourceChecker?: Checker | null): Promise<void> {\n const generation = this.#begin();\n this.#source = view;\n this.#sourceChecker = sourceChecker ?? null;\n try {\n await this.#mount(view, generation, snapshot);\n } catch (error) {\n if (generation === this.#generation) throw this.#fail(codeOf(error, 'view_invalid'));\n }\n }\n\n /** Tears the current attempt down and starts a new load generation (older loads then stop). */\n #begin(): number {\n this.#flushSnapshot();\n this.#unsubscribe?.();\n this.#unsubscribe = null;\n this.#help?.destroy();\n this.#help = null;\n this.#controller = null;\n this.#mounted = [];\n this.#pages = [];\n this.#doc = null;\n this.#book = null;\n this.#spread = false;\n this.#resize?.disconnect();\n this.#resize = null;\n this.#headings = [];\n this.#source = null;\n this.#viewHash = null;\n this.#documentTemplate = null;\n this.#loadError = null;\n this.#loadDetails = null;\n this.#problem = null;\n this.#confirming = false;\n this.#alerted.clear();\n this.#autoSubmitted = false;\n this.#query('.canvas')?.replaceChildren();\n this.#syncClock();\n this.#setState('loading');\n return ++this.#generation;\n }\n\n async #mount(\n view: string,\n generation: number,\n snapshotOverride: Snapshot | null | undefined,\n ): Promise<void> {\n await this.updateComplete;\n const fragment = readView(view);\n // Never fails the view: without its styles the exercise still plays, unstyled.\n const styling = isStyled(fragment)\n ? import('./styled.js').catch((error) => {\n console.error(error);\n return null;\n })\n : null;\n // The same for help: without its module the exercise plays without hints and feedback texts.\n const helping = hasHelp(fragment)\n ? import('./help.js').catch((error) => {\n console.error(error);\n return null;\n })\n : null;\n // And for a book: without its module it plays one page at a time, as an exercise.\n const booking = isBook(fragment)\n ? import('./book.js').catch((error) => {\n console.error(error);\n return null;\n })\n : null;\n try {\n await loadElements(viewTags(fragment));\n } catch (error) {\n // A missing chunk (offline, a new deployment) fails the whole view: without it, its questions would show as\n // notices and grade as unanswered. The cause is for the developer.\n console.error(error);\n throw new LoadError('load_failed');\n }\n const styled = await styling;\n if (generation !== this.#generation) return;\n refreshStyleTemplateSheet();\n const styles = styled?.takeStyles(fragment);\n styled?.adoptStyledSheet(this.renderRoot);\n cleanView(\n fragment,\n new Map([...runtime.elements].map(([tag, registration]) => [tag, registration.manifest])),\n runtime.urlPolicy,\n );\n const viewHash = await sha256Hex(view).catch(() => null);\n if (generation !== this.#generation) return;\n const locale = this.#uiLocale();\n const i18n = this.#i18n();\n const t = i18n.translator(locale, PLAYER_NAMESPACE);\n const content = document.importNode(fragment, true);\n if (styles !== undefined) styled?.applyStyles(styles, fragment, content);\n customElements.upgrade(content);\n const doc = content.firstElementChild as HTMLElement;\n if (!doc.dir) doc.dir = directionOf(doc.lang || locale);\n const pages = Array.from(doc.children).filter((el): el is HTMLElement => el.localName === 'astl-page');\n if (pages.length === 0) pages.push(doc);\n\n const found: { element: PlayerElement; manifest: ComponentManifest }[] = [];\n this.#collect(doc, found, () => {\n const note = document.createElement('span');\n note.className = 'astl-notice';\n note.setAttribute('role', 'note');\n note.lang = locale;\n note.dir = directionOf(locale);\n note.textContent = t('unsupported');\n return note;\n });\n\n // A single page without a label gets no \"Page 1\" heading on top of its own content (the canvas is the focus\n // target then); labelled pages and pages of a multi-page view always have one. The generated \"Page n\" is for\n // screen readers and for the focus after a page change, not for the eyes: visually hidden, still a heading.\n const headings = pages.map((page, index) => {\n if (pages.length === 1 && !page.getAttribute('label')) return null;\n const heading = document.createElement('h2');\n heading.className = 'astl-page-heading';\n heading.tabIndex = -1;\n // The heading follows the content's direction, so it starts where the text starts. An authored label is\n // content. The generated \"Page n\" is UI text: the UI language on the heading, and a <bdi> that takes its\n // direction from the text itself.\n const label = page.getAttribute('label');\n if (label) {\n heading.textContent = label;\n } else {\n heading.lang = locale;\n heading.classList.add('astl-vh');\n const generated = document.createElement('bdi');\n generated.textContent = t('page.heading', { n: index + 1 });\n heading.append(generated);\n }\n page.prepend(heading);\n return heading;\n });\n\n let inline = 0;\n const mounted: Mounted[] = found.map(({ element, manifest }) => {\n element.attach({\n locale,\n t: elementTranslator(i18n, locale, manifest.messages),\n announce: (message) => this.#announce(message),\n number: manifest.display === 'inline' ? ++inline : 0,\n seed: this.policy.seed,\n });\n const page = pages.findIndex((p) => p.contains(element));\n return { element, manifest, page: Math.max(0, page) };\n });\n\n const canvas = this.#query('.canvas');\n if (canvas === null) throw new LoadError('view_invalid');\n canvas.replaceChildren(content);\n\n const candidate =\n snapshotOverride !== undefined ? snapshotOverride : (this.snapshot ?? this.#storedSnapshot(viewHash));\n let snapshot = AttemptController.restorable(candidate, viewHash);\n if (snapshot !== null) {\n // A restored answer is what the elements accept (e.g. option ids of an earlier compilation are dropped).\n const accepted: Record<string, string> = {};\n for (const { element } of mounted) {\n const own = pick(snapshot.answers, element.slotIds);\n if (Object.keys(own).length > 0) element.setAnswers(own);\n Object.assign(accepted, pick(element.getAnswers(), element.slotIds));\n }\n snapshot = { ...snapshot, answers: accepted };\n }\n const controller = new AttemptController({\n policy: this.policy,\n checker: this.#checkerProxy,\n pages: pages.map((page, index) => ({\n id: page.id || `page-${index + 1}`,\n slotIds: mounted.filter((m) => m.page === index).flatMap((m) => [...m.element.slotIds]),\n })),\n snapshot,\n viewHash,\n });\n this.#controller = controller;\n this.#mounted = mounted;\n this.#pages = pages;\n this.#doc = doc;\n this.#headings = headings;\n this.#viewHash = viewHash;\n this.#documentTemplate = doc.getAttribute(STYLE_TEMPLATE_ATTRIBUTE);\n this.#mountedLocale = locale;\n\n for (const { element } of mounted) {\n const ui = controller.restored ? snapshot?.ui[element.id] : undefined;\n if (ui !== undefined) element.setUiState?.(ui);\n element.disabled = controller.readOnly;\n }\n this.#unsubscribe = controller.subscribe((change) => this.#onChange(change));\n const help = await helping;\n if (generation !== this.#generation) return;\n this.#help =\n help?.mountHelp({\n controller,\n mounted,\n pages,\n locale,\n urlPolicy: runtime.urlPolicy,\n root: this.renderRoot,\n checker: () => this.#effectiveChecker(),\n check: (id) => this.check(id),\n announce: (message) => this.#announce(message),\n }) ?? null;\n const book = pages.length > 1 ? await booking : null;\n if (generation !== this.#generation) return;\n if (book) {\n this.#book = book;\n book.adoptBookSheet(this.renderRoot);\n this.#resize = book.watchSpread(this, (spread) => this.#setSpread(spread));\n }\n this.#showPage(controller.page, false);\n this.#setState(controller.state);\n this.#syncClock();\n this.requestUpdate();\n // Ready means rendered: the chrome and every Lit-based element have painted their first frame.\n await this.updateComplete;\n await Promise.all(\n mounted.map(({ element }) => (element as { updateComplete?: Promise<unknown> }).updateComplete),\n );\n if (generation !== this.#generation) return;\n const ready: ReadyDetail = {\n viewHash: viewHash ?? '',\n pages: pages.length,\n slots: mounted.reduce((n, { element }) => n + element.slotIds.length, 0),\n };\n this.#dispatch(PlayerEvent.ready, ready);\n }\n\n /** Finds component elements; unknown custom elements and too new versions become notices. */\n #collect(\n parent: Element,\n found: { element: PlayerElement; manifest: ComponentManifest }[],\n notice: () => HTMLElement,\n ): void {\n for (const child of Array.from(parent.children)) {\n const tag = child.localName;\n if (tag === 'astl-page' || tag === COLUMNS_TAG || tag === COLUMN_TAG || !tag.includes('-')) {\n this.#collect(child, found, notice);\n continue;\n }\n const registration = runtime.elements.get(tag);\n const version = Number.parseInt(child.getAttribute('v') ?? '1', 10);\n if (\n registration &&\n child instanceof registration.element &&\n !(version > registration.manifest.version)\n ) {\n found.push({ element: child as PlayerElement, manifest: registration.manifest });\n } else {\n child.replaceWith(notice());\n }\n }\n }\n\n // Attempt changes\n\n #onChange(change: AttemptChange): void {\n switch (change.type) {\n case 'state':\n this.#setState(change.state);\n for (const { element } of this.#mounted) element.disabled = this.#controller?.readOnly ?? true;\n this.#syncClock();\n break;\n case 'answers':\n this.#scheduleSnapshot();\n break;\n case 'page':\n this.#showPage(change.index, true, change.previous);\n this.#dispatch(PlayerEvent.page, {\n index: change.index,\n count: this.#pages.length,\n id: this.#controller?.pages[change.index]?.id ?? '',\n } satisfies PageDetail);\n this.#scheduleSnapshot();\n break;\n case 'result':\n this.#applyResult();\n this.#dispatch(PlayerEvent.result, change.response);\n this.#scheduleSnapshot();\n break;\n case 'element':\n this.#applyResult(change.id, change.response);\n this.#scheduleSnapshot();\n break;\n case 'reset':\n for (const { element } of this.#mounted) {\n element.setAnswers(Object.fromEntries(element.slotIds.map((id) => [id, ''])));\n element.feedback = null;\n element.solution = null;\n }\n this.#removeStored();\n this.#showPage(0, true);\n this.#scheduleSnapshot();\n break;\n }\n this.requestUpdate();\n }\n\n /**\n * Pushes verdicts, the help texts the response brings and solutions after a revealing submit to the elements, then\n * announces the summary. With `only`, the response of a check of that one element: its verdicts, no summary.\n */\n #applyResult(only?: string, checked?: CheckResponse): void {\n const controller = this.#controller;\n if (controller === null) return;\n const response = checked ?? controller.response;\n const result = response?.result ?? null;\n const solution = controller.solution;\n const groups = new Map(result?.groups.map((g) => [g.id, g.verdict]) ?? []);\n for (const { element } of this.#mounted) {\n if (only !== undefined && element.id !== only) continue;\n if (result === null) {\n element.feedback = null;\n } else {\n const slots: Record<string, SlotVerdict> = {};\n for (const id of element.slotIds) {\n const verdict = result.slots[id];\n if (verdict !== undefined) slots[id] = verdict;\n }\n const group = groups.get(element.id) ?? null;\n // An element graded in parts gets the verdicts of the groups it names.\n const named = element.groupIds?.flatMap((id) => {\n const verdict = groups.get(id);\n return verdict === undefined ? [] : [[id, verdict] as const];\n });\n const help = {\n message: response?.feedback?.[element.id] ?? null,\n explanation: response?.explanations?.[element.id] ?? null,\n };\n element.feedback =\n named === undefined\n ? { slots, group, ...help }\n : { slots, group, groups: Object.fromEntries(named), ...help };\n }\n if (only !== undefined) continue;\n element.solution = solution === null ? null : pick(solution, element.slotIds);\n element.disabled = controller.readOnly;\n }\n const text =\n only === undefined\n ? this.#resultAnnouncement(this.#i18n().translator(this.#uiLocale(), PLAYER_NAMESPACE))\n : null;\n if (text !== null) this.#announce(text);\n }\n\n /** Shows page `index`, in a spread with its neighbour; `from`, the page before, turns the spread when it changes. */\n #showPage(index: number, focus: boolean, from?: number): void {\n const [first, last] = this.#shown(index);\n this.#pages.forEach((page, i) => {\n if (page.localName === 'astl-page') page.hidden = i < first || i > last;\n });\n if (from !== undefined && this.#spread && this.#shown(from)[0] !== first) {\n this.#book?.turn(this.#pages.slice(first, last + 1), from < index ? 1 : -1, this.#doc?.dir === 'rtl');\n }\n if (focus) (this.#headings[index] ?? this.#query('.canvas'))?.focus();\n }\n\n /** First and last page shown with page `index`: its spread in a spread (the last one may hold one page), else it. */\n #shown(index: number): readonly [number, number] {\n if (!this.#spread) return [index, index];\n const first = index - (index % 2);\n return [first, Math.min(first + 1, this.#pages.length - 1)];\n }\n\n /** The page \"Dalej\" (1) or \"Wstecz\" (-1) goes to: the first page of the next or previous spread in a spread. */\n #step(direction: 1 | -1): number {\n const page = this.#controller?.page ?? 0;\n return this.#spread ? this.#shown(page)[0] + 2 * direction : page + direction;\n }\n\n /** The book's module says whether the player is wide enough for a spread: switching keeps the page, without focus. */\n #setSpread(spread: boolean): void {\n if (spread === this.#spread) return;\n this.#spread = spread;\n this.#showPage(this.#controller?.page ?? 0, false);\n this.requestUpdate();\n }\n\n #setState(state: AttemptState): void {\n const previous = this.#state;\n if (state === previous) return;\n this.#state = state;\n this.#dispatch(PlayerEvent.state, { state, previous } satisfies StateDetail);\n this.requestUpdate();\n }\n\n #fail(code: string, details: string | null = null): LoadError {\n this.#loadError = code;\n this.#loadDetails = details;\n this.#setState('error');\n const message = this.#errorMessage(this.#i18n().translator(this.#uiLocale(), PLAYER_NAMESPACE), code);\n this.#announce(message);\n this.#dispatch(PlayerEvent.error, { code, message } satisfies ErrorDetail);\n return new LoadError(code);\n }\n\n #showProblem(code: string): void {\n this.#problem = code;\n const message = this.#errorMessage(this.#i18n().translator(this.#uiLocale(), PLAYER_NAMESPACE), code);\n this.#announce(message);\n this.#dispatch(PlayerEvent.error, { code, message } satisfies ErrorDetail);\n this.requestUpdate();\n }\n\n // Snapshots and storage\n\n #uiState(): Record<string, JsonValue> {\n const ui: Record<string, JsonValue> = {};\n for (const { element } of this.#mounted) {\n const state = element.getUiState?.();\n if (state !== undefined) ui[element.id] = state;\n }\n return ui;\n }\n\n #scheduleSnapshot(): void {\n clearTimeout(this.#snapshotTimer);\n this.#snapshotTimer = setTimeout(() => this.#emitSnapshot(), SNAPSHOT_DELAY_MS);\n }\n\n #flushSnapshot(): void {\n if (this.#snapshotTimer === undefined) return;\n clearTimeout(this.#snapshotTimer);\n this.#emitSnapshot();\n }\n\n #emitSnapshot(): void {\n this.#snapshotTimer = undefined;\n const snapshot = this.getSnapshot();\n if (snapshot === null) return;\n this.#store(snapshot);\n this.#dispatch(PlayerEvent.snapshot, snapshot);\n }\n\n #storageKey(viewHash: string | null): string | null {\n return this.persist && viewHash !== null ? `${STORAGE_PREFIX}${viewHash}` : null;\n }\n\n // Storage can be missing or blocked (private mode, sandboxed frames): persistence is best effort.\n #storedSnapshot(viewHash: string | null): Snapshot | null {\n const key = this.#storageKey(viewHash);\n if (key === null) return null;\n try {\n const raw = localStorage.getItem(key);\n const value: unknown = raw === null ? null : JSON.parse(raw);\n return isSnapshot(value) && value.viewHash === viewHash ? value : null;\n } catch {\n return null;\n }\n }\n\n #store(snapshot: Snapshot): void {\n const key = this.#storageKey(snapshot.viewHash);\n if (key === null) return;\n // Nothing worth restoring: keep storage clean (also what reset leaves behind).\n const empty = Object.keys(snapshot.answers).length === 0 && snapshot.page === 0 && !snapshot.submitted;\n try {\n if (empty) localStorage.removeItem(key);\n else localStorage.setItem(key, JSON.stringify(snapshot));\n } catch {\n // Best effort.\n }\n }\n\n #removeStored(): void {\n const key = this.#storageKey(this.#viewHash);\n if (key === null) return;\n try {\n localStorage.removeItem(key);\n } catch {\n // Best effort.\n }\n }\n\n // Deadline\n\n #syncClock(): void {\n const state = this.#state;\n const running =\n this.isConnected &&\n this.#controller?.policy.deadline != null &&\n (state === 'ready' || state === 'active' || state === 'checking');\n if (running && this.#clock === undefined) this.#clock = setInterval(() => this.#tick(), 1000);\n if (!running && this.#clock !== undefined) {\n clearInterval(this.#clock);\n this.#clock = undefined;\n }\n }\n\n #tick(): void {\n const controller = this.#controller;\n const left = controller?.timeLeft() ?? null;\n if (controller === null || left === null) return;\n const t = this.#i18n().translator(this.#uiLocale(), PLAYER_NAMESPACE);\n const due = TIMER_ALERTS.filter((minutes) => left <= minutes * 60_000);\n if (left > 0 && due.length > 0 && !this.#alerted.has(Math.min(...due))) {\n for (const minutes of due) this.#alerted.add(minutes);\n this.#announce(t('timer.minutes', { minutes: Math.ceil(left / 60_000) }));\n }\n if (left === 0 && !this.#autoSubmitted && controller.canSubmit()) {\n this.#autoSubmitted = true;\n this.#announce(t('timer.expired'));\n void this.submit();\n }\n this.requestUpdate();\n }\n\n // Helpers\n\n #effectiveChecker(): Checker | null {\n if (this.#sourceChecker !== null) return this.#sourceChecker;\n if (this.checker !== null) return this.checker;\n if (this.endpoint) {\n if (this.#endpointChecker?.endpoint !== this.endpoint) {\n this.#endpointChecker = {\n endpoint: this.endpoint,\n checker: httpChecker({ endpoint: this.endpoint }),\n };\n }\n return this.#endpointChecker.checker;\n }\n return null;\n }\n\n #requireChecker(): Checker {\n const checker = this.#effectiveChecker();\n if (checker === null) throw new LoadError('no_checker');\n return checker;\n }\n\n /** Units left empty before a hand-in; answers of ungraded components (open answers) are optional. */\n #emptyCount(): number {\n let empty = 0;\n for (const { element, manifest } of this.#mounted) {\n if (!manifest.graded) continue;\n const units = element.units();\n empty += Math.max(0, units.total - units.answered);\n }\n return empty;\n }\n\n #pageState(index: number): PageState {\n let answered = 0;\n let total = 0;\n for (const { element, page } of this.#mounted) {\n if (page !== index) continue;\n const units = element.units();\n answered += units.answered;\n total += units.total;\n }\n if (answered >= total) return 'done';\n return answered === 0 ? 'none' : 'partial';\n }\n\n #i18n(): I18n {\n if (this.#i18nCache?.version !== runtime.version) {\n const catalogs = [\n ...playerMessages,\n ...[...runtime.elements.values()].flatMap((r) => r.messages),\n ...runtime.catalogs,\n ];\n this.#i18nCache = { version: runtime.version, i18n: createI18n({ catalogs }) };\n }\n return this.#i18nCache.i18n;\n }\n\n #uiLocale(): string {\n const requested = this.locale\n ? [this.locale]\n : this.lang\n ? [this.lang]\n : [...(navigator.languages ?? []), navigator.language].filter((l) => !!l);\n return negotiateLocale(requested, this.#i18n().locales(PLAYER_NAMESPACE), 'en');\n }\n\n #theme(): ThemeSetting {\n const theme = this.theme;\n return theme !== null && THEMES.includes(theme) ? theme : 'auto';\n }\n\n #announce(message: string): void {\n const region = this.#query('.live');\n if (region !== null) announce(region, message);\n }\n\n #query(selector: string): HTMLElement | null {\n return this.renderRoot?.querySelector<HTMLElement>(selector) ?? null;\n }\n\n #dispatch(type: string, detail: unknown): void {\n this.dispatchEvent(new CustomEvent(type, { detail, bubbles: true, composed: true }));\n }\n}\n\ndeclare global {\n interface HTMLElementTagNameMap {\n 'astl-player': AstlPlayer;\n }\n}\n","import {\n ELEMENT_TAG_PATTERN,\n isStyleTemplate,\n type MessageCatalog,\n type SourceCompiler,\n STYLE_TEMPLATE_NAME,\n type StyleTemplate,\n strictUrlPolicy,\n type UrlPolicy,\n} from '@astl/core';\nimport { AstlPlayer } from './player/player.js';\nimport { refreshStyleTemplateSheet } from './player/templates.js';\nimport {\n type ElementEntry,\n type ElementRegistration,\n isLazyElement,\n type LazyElement,\n runtime,\n} from './runtime.js';\n\nexport interface DefinePlayerOptions {\n /**\n * Component elements: a registration is defined right away, a `LazyElement` the first time a view contains its\n * tag.\n */\n readonly elements: readonly ElementEntry[];\n /** More or overriding catalogs (any namespace), e.g. another UI locale. */\n readonly catalogs?: readonly MessageCatalog[];\n /** Enables light-DOM sources (HTML with answers). */\n readonly compileSource?: SourceCompiler;\n /**\n * Which URLs of a view stay when the player mounts it (links, pictures, `url` attributes): the same policy as the\n * engine that compiled the views (`createEngine({ urlPolicy })`), or the player removes what the engine kept.\n * Default `isSafeUrl`. One policy for every player of the page: the last call that passes one sets it. An address\n * stays only when the policy answers `true` (one that throws blocks it).\n */\n readonly urlPolicy?: UrlPolicy;\n /**\n * Looks that exercises can pick with `style-template` on `<astl-doc>` or on a component, and hosts with\n * `<astl-player style-template>` (trusted, like the host's own CSS).\n */\n readonly styleTemplates?: readonly StyleTemplate[];\n /** Default: the global `customElements`. */\n readonly registry?: CustomElementRegistry;\n}\n\nconst PLAYER_TAG = 'astl-player';\n\n/**\n * Defines `<astl-player>` and the given elements, and registers style templates. Safe to call again: a tag already\n * defined by the same class, a lazy element with the same `load`, or a template already registered as the same\n * object is skipped. A tag taken by another class, by another loader or by the other kind of entry (eager or lazy),\n * or a template name taken by another template, throws (two copies of a bundle would otherwise mix silently).\n */\nexport function definePlayer(options: DefinePlayerOptions): void {\n const registry = options.registry ?? customElements;\n const classes = new Map<string, CustomElementConstructor>();\n const claim = (tag: string, element: CustomElementConstructor): void => {\n const existing = classes.get(tag) ?? registry.get(tag);\n if (existing !== undefined && existing !== element) {\n throw new Error(`<${tag}> is already defined by another class`);\n }\n classes.set(tag, element);\n };\n const taken = (tag: string) => new Error(`<${tag}> is already registered by another entry`);\n claim(PLAYER_TAG, AstlPlayer);\n const eager: ElementRegistration[] = [];\n const lazy = new Map<string, LazyElement['load']>();\n for (const entry of options.elements) {\n if (isLazyElement(entry)) {\n const tag = String(entry.tag);\n if (!ELEMENT_TAG_PATTERN.test(tag) || tag === PLAYER_TAG) {\n throw new TypeError(`Lazy element <${tag}>: the tag must be a lowercase custom element name`);\n }\n const known = lazy.get(tag) ?? runtime.lazy.get(tag)?.load;\n if (known === entry.load) continue;\n if (known !== undefined || classes.has(tag) || runtime.elements.has(tag)) throw taken(tag);\n lazy.set(tag, entry.load);\n } else {\n const tag = entry.manifest.tag;\n if (lazy.has(tag) || runtime.lazy.has(tag)) throw taken(tag);\n claim(tag, entry.element);\n eager.push(entry);\n }\n }\n const templates = new Map<string, StyleTemplate>();\n for (const template of options.styleTemplates ?? []) {\n const name = String(template?.name);\n if (!STYLE_TEMPLATE_NAME.test(name)) {\n throw new TypeError(`Style template \"${name}\": the name must be lowercase kebab-case`);\n }\n // Checked before anything is registered: one broken template must not stop every player from rendering.\n if (!isStyleTemplate(template)) {\n throw new TypeError(`Style template \"${name}\" needs a version, scopes, messages and string values`);\n }\n const existing = templates.get(template.name) ?? runtime.styleTemplates.get(template.name);\n if (existing !== undefined && existing !== template) {\n throw new Error(`Style template \"${template.name}\" is already registered`);\n }\n templates.set(template.name, template);\n }\n if (options.urlPolicy !== undefined && typeof options.urlPolicy !== 'function') {\n throw new TypeError('urlPolicy must be a function');\n }\n for (const [tag, element] of classes) if (registry.get(tag) === undefined) registry.define(tag, element);\n for (const registration of eager) runtime.elements.set(registration.manifest.tag, registration);\n for (const [tag, load] of lazy) runtime.lazy.set(tag, { load, registry });\n for (const [name, template] of templates) runtime.styleTemplates.set(name, template);\n if (options.catalogs) runtime.catalogs.push(...options.catalogs);\n if (options.compileSource) runtime.compileSource = options.compileSource;\n if (options.urlPolicy) runtime.urlPolicy = strictUrlPolicy(options.urlPolicy);\n runtime.version++;\n refreshStyleTemplateSheet();\n}\n","/**\n * Base classes for component elements. They implement the parts of PlayerElementApi every element shares, so an\n * component author writes rendering and answer mapping only. Elements also work outside a player: until\n * `attach()` is called they use an English context built from their own catalogs.\n */\nimport {\n type Answers,\n type AttributeSpec,\n allAttributes,\n type ChangeDetail,\n type ComponentManifest,\n createI18n,\n type Direction,\n directionOf,\n type ElementContext,\n type ElementFeedback,\n type GroupVerdict,\n type MessageCatalog,\n type MessageParams,\n type PlayerElementApi,\n PlayerEvent,\n type SlotId,\n type SlotVerdict,\n type Solution,\n type Translate,\n type Units,\n} from '@astl/core';\nimport { html, LitElement, nothing, type PropertyDeclarations, type TemplateResult } from 'lit';\nimport { announce, documentLiveRegion, renderVerdict, type VerdictOptions } from '../a11y.js';\nimport { elementTranslator, PLAYER_NAMESPACE, playerMessages } from '../messages.js';\n\nfunction defaultContext(type: typeof AstlElement): ElementContext {\n const i18n = createI18n({ catalogs: [...playerMessages, ...type.messages] });\n return {\n locale: 'en',\n t: elementTranslator(i18n, 'en', type.manifest?.messages ?? PLAYER_NAMESPACE),\n announce: (message) => announce(documentLiveRegion(), message),\n number: 0,\n seed: null,\n };\n}\n\n/** 32-bit FNV-1a hash of a string. */\nfunction hash(value: string): number {\n let h = 0x811c9dc5;\n for (let i = 0; i < value.length; i++) {\n h ^= value.charCodeAt(i);\n h = Math.imul(h, 0x01000193);\n }\n return h >>> 0;\n}\n\n/** mulberry32: a small, good-enough PRNG for UI shuffles (not for anything secret). */\nfunction random(seed: number): () => number {\n let a = seed;\n return () => {\n a = (a + 0x6d2b79f5) | 0;\n let t = Math.imul(a ^ (a >>> 15), 1 | a);\n t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;\n return ((t ^ (t >>> 14)) >>> 0) / 4294967296;\n };\n}\n\n/** Deterministic Fisher-Yates shuffle: the same seed always gives the same order. */\nexport function seededShuffle<T>(items: readonly T[], seed: string): T[] {\n const next = random(hash(seed));\n const out = [...items];\n for (let i = out.length - 1; i > 0; i--) {\n const j = Math.floor(next() * (i + 1));\n [out[i], out[j]] = [out[j] as T, out[i] as T];\n }\n return out;\n}\n\nexport abstract class AstlElement extends LitElement implements PlayerElementApi {\n /** The element type's manifest: drives the typed attribute getters and the default message namespace. */\n static manifest: ComponentManifest | null = null;\n /** Catalogs of the manifest's namespace, used until a player attaches its own context. */\n static messages: readonly MessageCatalog[] = [];\n\n static override properties: PropertyDeclarations = {\n feedback: { attribute: false },\n solution: { attribute: false },\n disabled: { type: Boolean },\n };\n\n /** Verdicts to show; null clears them. Editing a slot clears its own verdict and the group verdict. */\n declare feedback: ElementFeedback | null;\n /** Correct answers to show next to the student's; null hides them. */\n declare solution: Solution | null;\n declare disabled: boolean;\n #context: ElementContext | null = null;\n /** `t` as a value, for `renderVerdict`. */\n readonly #t: Translate = (key, params) => this.t(key, params);\n\n constructor() {\n super();\n this.feedback = null;\n this.solution = null;\n this.disabled = false;\n // A controller runs after every render, before the element's own `updated()`, which need not call super.\n this.addController({ hostUpdated: () => this.#assignSlots() });\n }\n\n /**\n * Source content in a player's light DOM (HTML with answers) is input for the compiler and never shown: such\n * elements stay inert, with no shadow root and no render. The player mounts its own copy of the compiled view.\n */\n override connectedCallback(): void {\n if (this.closest('astl-player') !== null) return;\n super.connectedCallback();\n }\n\n abstract get slotIds(): readonly SlotId[];\n abstract getAnswers(): Answers;\n abstract setAnswers(answers: Answers): void;\n abstract units(): Units;\n\n /** The player's context, or the default English one. */\n get context(): ElementContext {\n this.#context ??= defaultContext(this.constructor as typeof AstlElement);\n return this.#context;\n }\n\n attach(context: ElementContext): void {\n this.#context = context;\n this.requestUpdate();\n }\n\n /** A message in the UI locale: the element's namespace first, then the shared `astl.player` one. */\n protected t(key: string, params?: MessageParams): string {\n return this.context.t(key, params);\n }\n\n protected announce(message: string): void {\n this.context.announce(message);\n }\n\n /** UI language and direction (the context locale), for UI strings rendered inside content. */\n protected get uiLanguage(): { readonly lang: string; readonly dir: Direction } {\n const lang = this.context.locale;\n return { lang, dir: directionOf(lang) };\n }\n\n /** Content language at this element (closest `lang`), for inputs and spell checking. */\n protected get contentLang(): string {\n return this.closest('[lang]')?.getAttribute('lang') ?? '';\n }\n\n /** Reports changed slots (`''` = cleared) to the player and clears their verdicts. */\n protected emitChange(answers: Answers): void {\n const feedback = this.feedback;\n if (feedback) {\n const slots = { ...feedback.slots };\n for (const id of Object.keys(answers)) delete slots[id];\n this.feedback = { slots, group: null };\n }\n this.dispatchEvent(\n new CustomEvent<ChangeDetail>(PlayerEvent.change, {\n detail: { answers },\n bubbles: true,\n composed: true,\n }),\n );\n }\n\n protected slotVerdict(id: SlotId): SlotVerdict | null {\n return this.feedback?.slots[id] ?? null;\n }\n\n protected get groupVerdict(): GroupVerdict | null {\n return this.feedback?.group ?? null;\n }\n\n /** A verdict's icon and word (`renderVerdict`) in the UI language, as part `verdict`; nothing without a verdict. */\n protected renderVerdict(\n verdict: GroupVerdict | null,\n options: VerdictOptions = {},\n ): TemplateResult | typeof nothing {\n return verdict === null\n ? nothing\n : renderVerdict(verdict, this.#t, { part: 'verdict', ...this.uiLanguage, ...options });\n }\n\n /** The group verdict line of a block (`p.group-verdict`, part `verdict`); nothing without a verdict. */\n protected renderGroupVerdict(\n verdict: GroupVerdict | null = this.groupVerdict,\n ): TemplateResult | typeof nothing {\n return verdict === null\n ? nothing\n : html`<p class=\"group-verdict\" part=\"verdict\" data-verdict=${verdict}>\n ${renderVerdict(verdict, this.#t, this.uiLanguage)}\n </p>`;\n }\n\n /** The light-DOM children with this tag and an id, in view order. */\n protected childElements(tag: string): HTMLElement[] {\n return Array.from(this.children).filter(\n (child): child is HTMLElement => child.localName === tag && child.id !== '',\n );\n }\n\n /**\n * Manual slot assignment (a shadow root with `slotAssignment: 'manual'`): the light DOM is projected as it is, never\n * moved or rewritten. `<slot data-tag=\"astl-prompt\">` shows the first child with that tag; any other\n * `<slot data-<name>=\"<id>\">` (`data-option`, `data-card`) the child with that id (child ids are unique in an element).\n */\n #assignSlots(): void {\n const root = this.shadowRoot;\n if (root?.slotAssignment !== 'manual') return;\n const children = Array.from(this.children);\n for (const slot of root.querySelectorAll('slot')) {\n const { tag, ...named } = slot.dataset;\n const [id] = Object.values(named);\n const child = children.find((c) =>\n tag === undefined ? id !== '' && c.id === id : c.localName === tag,\n );\n slot.assign(...(child === undefined ? [] : [child]));\n }\n }\n\n /** `items` in view order, or shuffled per attempt when the context has a seed (stable per seed and id). */\n protected shuffled<T>(items: readonly T[]): readonly T[] {\n const seed = this.context.seed;\n return seed === null ? items : seededShuffle(items, `${seed}:${this.id}`);\n }\n\n protected attributeSpec(name: string): AttributeSpec | undefined {\n const manifest = (this.constructor as typeof AstlElement).manifest;\n return manifest ? allAttributes(manifest).find((a) => a.name === name) : undefined;\n }\n\n /** A string, id or enum attribute; enum values outside the manifest's list give the default. */\n protected stringAttribute(name: string): string | null {\n const spec = this.attributeSpec(name);\n const value = this.getAttribute(name);\n const fallback = spec?.default === undefined ? null : String(spec.default);\n if (value === null) return fallback;\n if (spec?.type === 'enum' && !(spec.values ?? []).includes(value)) return fallback;\n return value;\n }\n\n /** An integer or number attribute within the manifest's bounds, else the default (or null). */\n protected numberAttribute(name: string): number | null {\n const spec = this.attributeSpec(name);\n const fallback = typeof spec?.default === 'number' ? spec.default : null;\n const raw = this.getAttribute(name);\n if (raw === null || raw.trim() === '') return fallback;\n const value = Number(raw);\n if (!Number.isFinite(value) || (spec?.type === 'integer' && !Number.isInteger(value))) return fallback;\n if ((spec?.min !== undefined && value < spec.min) || (spec?.max !== undefined && value > spec.max)) {\n return fallback;\n }\n return value;\n }\n\n /** An HTML boolean attribute: present = true. */\n protected booleanAttribute(name: string): boolean {\n return this.hasAttribute(name);\n }\n}\n\n/** An element with exactly one slot whose id is the element id (a gap, a single choice, a slider). */\nexport abstract class SingleSlotElement extends AstlElement {\n static override properties: PropertyDeclarations = {\n value: { state: true },\n };\n\n /** The current answer; `''` = unanswered. */\n declare protected value: string;\n\n constructor() {\n super();\n this.value = '';\n }\n\n get slotIds(): readonly SlotId[] {\n return this.id === '' ? [] : [this.id];\n }\n\n getAnswers(): Answers {\n return this.id === '' || this.value === '' ? {} : { [this.id]: this.value };\n }\n\n setAnswers(answers: Answers): void {\n const value = answers[this.id];\n if (value !== undefined) this.value = value;\n }\n\n units(): Units {\n return { answered: this.value.trim() === '' ? 0 : 1, total: 1 };\n }\n\n /** Sets the answer from student input and reports it. */\n protected updateValue(value: string): void {\n if (value === this.value) return;\n this.value = value;\n this.emitChange({ [this.id]: value });\n }\n\n /** The slot verdict, else the group verdict (e.g. `empty`). */\n protected get verdict(): GroupVerdict | null {\n return this.slotVerdict(this.id) ?? this.groupVerdict;\n }\n\n /** The correct answer for this slot, when shown. */\n protected get solutionValue(): string | null {\n return this.solution?.[this.id] ?? null;\n }\n}\n","/**\n * `@astl/astrolabe/player`: `<astl-player>` with the built-in elements and looks. Player side only: nothing\n * here may import the engine, the server, a definition or the editor (the student bundle carries no answer logic).\n *\n * For HTML with answers through a bundler: `definePlayer({ compileSource: createSourceCompiler() })`, with\n * `createSourceCompiler` from `@astl/astrolabe/engine`.\n */\nimport { builtInElements } from '@astl/components/elements';\nimport { type DefinePlayerOptions, definePlayer as defineBasePlayer } from '@astl/player';\nimport { builtInStyleTemplates, tokensCss } from '@astl/tokens';\n\nexport * from '@astl/core';\nexport * from '@astl/player';\n// `tokensCss`: the --astl-* tokens for the page around the player, with the same themes.\nexport { builtInElements, builtInStyleTemplates, tokensCss };\n\n/**\n * Defines `<astl-player>` with `elements: builtInElements` and `styleTemplates: builtInStyleTemplates`. An option\n * replaces its default (extend with `[...builtInElements, mine]`); a second call adds.\n */\nexport function definePlayer(options: Partial<DefinePlayerOptions> = {}): void {\n defineBasePlayer({ elements: builtInElements, styleTemplates: builtInStyleTemplates, ...options });\n}\n"],"ignoreList":[27,28,29,30,31],"mappings":"AAgBA,IAAakD,EAAoB,IAGpBC,EAAiB,OAGjBC,EAAyB,IAGzBC,EAAmB,IAEnBC,EAAgB,OAG7B,SAAgBC,EAAgB,EAAkC,CAChE,OAAOC,IAAA,OAA0BJ,EAAA,GACnC,CAGA,SAAgBK,EAAW,EAAe,EAAwB,CAChE,IAAMC,EAAMH,EAAgBC,CAAI,EAEhC,GAAIG,EAAM,QAAUD,EAAK,MAAO,GAChC,GAAIC,EAAM,OAAS,EAAID,EAAK,MAAO,GACnC,IAAIE,EAAQ,EACZ,IAAK,IAAMC,KAAKF,EAAO,GAAI,EAAEC,EAAQF,EAAK,MAAO,GACjD,MAAO,EACT,CAGA,SAAgBI,EAAU,EAAkC,CAC1D,GAAI,OAAOH,GAAU,WAAYA,GAAkB,MAAM,QAAQA,CAAK,EAAG,MAAO,GAChF,IAAMI,EAAU,OAAO,QAAQJ,CAAK,EAEpC,OADII,EAAQ,OAAA,IAAkC,GACvCA,EAAQ,OAAO,CAACC,EAAGC,KAAOD,EAAE,OAAS,GAAKA,EAAE,QAAU,KAAO,OAAOC,GAAM,QAAQ,CAC3F,CC9BA,SAAgBC,EACd,EACA,EAA0C,CAAC,EAC3C,EAA4B,CAAC,EAChB,CACb,MAAO,CAAE,KAAM,UAAW,MAAK,QAAO,UAAS,CACjD,CAEA,SAAgBC,EAAK,EAAyB,CAC5C,MAAO,CAAE,KAAM,OAAQ,OAAM,CAC/B,CAEA,SAAgBC,EAAU,EAAwB,EAAmC,CACnF,OAAOC,IAAS,IAAA,IAAaA,EAAK,OAAS,YAAcC,IAAQ,IAAA,IAAaD,EAAK,MAAQC,EAC7F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