@pie-qti/item-player 0.1.22 → 0.1.24

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.
@@ -1,2 +1,2 @@
1
- import { t as e } from "./element-class-DWoLXp_r.js";
1
+ import { t as e } from "./element-class-DQy2cIPM.js";
2
2
  export { e as PieQtiItemPlayerElement };
package/dist/element.js CHANGED
@@ -1,4 +1,4 @@
1
- import { t as e } from "./element-class-DWoLXp_r.js";
1
+ import { t as e } from "./element-class-DQy2cIPM.js";
2
2
  //#region src/element.ts
3
3
  var t = "pie-qti-item-player";
4
4
  globalThis.customElements && !customElements.get(t) && customElements.define(t, e);
package/dist/index.d.ts CHANGED
@@ -26,6 +26,8 @@ export type { ResolvedItemDeliveryContext } from '@pie-qti/ims-cp-core';
26
26
  export type { ExtractedPci, PciBoundTo, PciConfiguration, PciHostController, PciHostOptions, PciModule, PciModulePathKind, PciModuleResolutionContext, PciModuleResolver, } from './pci/types.js';
27
27
  export { PciLoadError, PciModuleResolverRequiredError } from './pci/types.js';
28
28
  export { PciHost } from './pci/PciHost.js';
29
+ export { createAllowlistPciModuleResolver, PciModuleNotAllowedError, } from './pci/allowlistResolver.js';
30
+ export type { AllowlistPciResolverOptions } from './pci/allowlistResolver.js';
29
31
  export { normalizeHeuristicsConfig, applyFeedbackTextHeuristics, shouldUseLenientImagePaths, shouldAutoPopulateFeedbackOutcome, DEFAULT_HEURISTICS_CONFIG, STRICT_QTI_CONFIG, FEEDBACK_TEXT_TRANSFORMS, type QtiHeuristicsConfig, type TextTransform, } from '@pie-qti/ims-cp-core';
30
32
  /**
31
33
  * NOTE (SSR safety):
package/dist/index.js CHANGED
@@ -25,6 +25,7 @@ export { extractCatalog, extractCatalogFromItemXml, mergeCatalogs } from './cata
25
25
  export { getCatalogEntry } from './catalog/catalogLookup.js';
26
26
  export { PciLoadError, PciModuleResolverRequiredError } from './pci/types.js';
27
27
  export { PciHost } from './pci/PciHost.js';
28
+ export { createAllowlistPciModuleResolver, PciModuleNotAllowedError, } from './pci/allowlistResolver.js';
28
29
  // Re-export QTI heuristics from @pie-qti/ims-cp-core for convenience
29
30
  // (heuristics are now in the shared ingestion layer)
30
31
  export { normalizeHeuristicsConfig, applyFeedbackTextHeuristics, shouldUseLenientImagePaths, shouldAutoPopulateFeedbackOutcome, DEFAULT_HEURISTICS_CONFIG, STRICT_QTI_CONFIG, FEEDBACK_TEXT_TRANSFORMS, } from '@pie-qti/ims-cp-core';
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,4DAA4D;AAC5D,OAAO,EAGN,iBAAiB,EACjB,uBAAuB,GACvB,MAAM,6BAA6B,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,2BAA2B;AAC3B,cAAc,yBAAyB,CAAC;AACxC,OAAO,EACN,8BAA8B,GAI9B,MAAM,oCAAoC,CAAC;AAiB5C,OAAO,EAAE,mBAAmB,EAAyB,MAAM,sBAAsB,CAAC;AAGlF,OAAO,EACN,+BAA+B,EAC/B,0BAA0B,EAC1B,gCAAgC,EAChC,6BAA6B,GAG7B,MAAM,0CAA0C,CAAC;AAalD,OAAO,EACN,uBAAuB,EACvB,wBAAwB,EACxB,qBAAqB,EACrB,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,aAAa,EACb,eAAe,EACf,QAAQ,GACR,MAAM,uBAAuB,CAAC;AAC/B,QAAQ;AACR,qGAAqG;AACrG,mGAAmG;AACnG,iDAAiD;AACjD,cAAc,kBAAkB,CAAC;AACjC,mBAAmB;AACnB,OAAO,EACN,wBAAwB,EAExB,kBAAkB,GAGlB,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAI3D,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAInD,OAAO,EAAE,cAAc,EAAE,yBAAyB,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACzG,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAe7D,OAAO,EAAE,YAAY,EAAE,8BAA8B,EAAE,MAAM,gBAAgB,CAAC;AAC9E,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAE3C,qEAAqE;AACrE,qDAAqD;AACrD,OAAO,EACN,yBAAyB,EACzB,2BAA2B,EAC3B,0BAA0B,EAC1B,iCAAiC,EACjC,yBAAyB,EACzB,iBAAiB,EACjB,wBAAwB,GAGxB,MAAM,sBAAsB,CAAC;AAE9B;;;;;;;;GAQG","sourcesContent":["/**\n * @pie-qti/item-player\n * Modern QTI player (2.2/3.0) - Framework-agnostic with web components\n */\n\n\n// Export web component registry for pluggable UI components\nexport {\n\ttype ComponentConfig,\n\ttype ComponentPlugin,\n\tComponentRegistry,\n\tcreateComponentRegistry,\n} from './core/ComponentRegistry.js';\nexport * from './core/constants.js';\n// Export drawing utilities\nexport * from './utils/drawingUtils.js';\nexport {\n\tcreateAssessmentItemDefinition,\n\ttype AssessmentItemDefinition,\n\ttype AssessmentItemDefinitionConfig,\n\ttype AssessmentItemDefinitionPlugin,\n} from './core/AssessmentItemDefinition.js';\nexport {\n\ttype ItemPresentationView,\n\ttype ItemSession,\n\ttype ItemSessionCommand,\n\ttype ItemSessionEventCommand,\n\ttype ItemSessionListener,\n\ttype ItemSessionTransition,\n\ttype ItemSessionView,\n\ttype OpenItemSessionOptions,\n} from './core/ItemSession.js';\nexport type {\n\tFinalItemBodyHtml,\n\tItemInteractionMount,\n\tItemPresentation,\n\tItemPresentationFlowNode,\n} from './presentation/itemPresentationPlan.js';\nexport { getRoleCapabilities, type RoleCapabilities } from './core/rolePolicy.js';\n// Render-facing interaction contracts. Standard extractors remain implementation details.\nexport type * from './interactions/shared/types.js';\nexport {\n\tcreateExtendedTextNumericRecord,\n\tcreateExtendedTextResponse,\n\tcreateExtendedTextStringResponse,\n\textendedTextResponseToStrings,\n\ttype ExtendedTextNumericRecord,\n\ttype ExtendedTextRecordField,\n} from './interactions/extended-text/response.js';\nexport type {\n\tElementExtractor,\n\tExtractionContext,\n\tExtractionDispatchResult,\n\tExtractionResult,\n\tExtractionUtils,\n\tInteractionDeliveryField,\n\tInteractionDeliveryPathSegment,\n\tInteractionDeliverySchema,\n\tValidationResult,\n\tVariableDeclaration,\n} from './extraction/index.js';\nexport {\n\tcreateExtractionContext,\n\tcreateExtractionRegistry,\n\tcreateExtractionUtils,\n\tExtractionError,\n\tExtractionRegistry,\n\thtmlField,\n\tisErrorResult,\n\tisSuccessResult,\n\turlField,\n} from './extraction/index.js';\n// NOTE:\n// The player’s primary rendering contract is via web components and the Svelte component entrypoint.\n// If you need non-web-component rendering, build it externally against the public extraction APIs.\n// Export all types including adaptive item types\nexport * from './types/index.js';\n// Export utilities\nexport {\n\tglobalPerformanceMonitor,\n\ttype PerformanceEntry,\n\tPerformanceMonitor,\n\ttype PerformanceMonitorConfig,\n\ttype PerformanceReport,\n} from './utils/PerformanceMonitor.js';\n\nexport { isResponseEmpty } from './utils/responseUtils.js';\n\n// PNP profile (QTI 3.0 §6.2)\nexport type { PnpProfile } from './pnp/types.js';\nexport { applyPnpToRoot } from './pnp/applyPnp.js';\nexport { parsePnpXml } from './pnp/parsePnpXml.js';\n\n// Catalog (QTI 3.0 §6.3)\nexport type { CatalogIndex, CatalogCard, CatalogEntry } from './catalog/types.js';\nexport { extractCatalog, extractCatalogFromItemXml, mergeCatalogs } from './catalog/catalogExtractor.js';\nexport { getCatalogEntry } from './catalog/catalogLookup.js';\nexport type { ResolvedItemDeliveryContext } from '@pie-qti/ims-cp-core';\n\n// PCI — Portable Custom Interaction (QTI 3.0 §6.1)\nexport type {\n\tExtractedPci,\n\tPciBoundTo,\n\tPciConfiguration,\n\tPciHostController,\n\tPciHostOptions,\n\tPciModule,\n\tPciModulePathKind,\n\tPciModuleResolutionContext,\n\tPciModuleResolver,\n} from './pci/types.js';\nexport { PciLoadError, PciModuleResolverRequiredError } from './pci/types.js';\nexport { PciHost } from './pci/PciHost.js';\n\n// Re-export QTI heuristics from @pie-qti/ims-cp-core for convenience\n// (heuristics are now in the shared ingestion layer)\nexport {\n\tnormalizeHeuristicsConfig,\n\tapplyFeedbackTextHeuristics,\n\tshouldUseLenientImagePaths,\n\tshouldAutoPopulateFeedbackOutcome,\n\tDEFAULT_HEURISTICS_CONFIG,\n\tSTRICT_QTI_CONFIG,\n\tFEEDBACK_TEXT_TRANSFORMS,\n\ttype QtiHeuristicsConfig,\n\ttype TextTransform,\n} from '@pie-qti/ims-cp-core';\n\n/**\n * NOTE (SSR safety):\n * Web component base classes depend on DOM globals like `HTMLElement` and must not be\n * re-exported from the main entrypoint. Item ownership flows through\n * AssessmentItemDefinition and ItemSession in every deployment.\n *\n * Import web-components from the subpath entry instead:\n * - `@pie-qti/item-player/web-components`\n */\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAGH,4DAA4D;AAC5D,OAAO,EAGN,iBAAiB,EACjB,uBAAuB,GACvB,MAAM,6BAA6B,CAAC;AACrC,cAAc,qBAAqB,CAAC;AACpC,2BAA2B;AAC3B,cAAc,yBAAyB,CAAC;AACxC,OAAO,EACN,8BAA8B,GAI9B,MAAM,oCAAoC,CAAC;AAiB5C,OAAO,EAAE,mBAAmB,EAAyB,MAAM,sBAAsB,CAAC;AAGlF,OAAO,EACN,+BAA+B,EAC/B,0BAA0B,EAC1B,gCAAgC,EAChC,6BAA6B,GAG7B,MAAM,0CAA0C,CAAC;AAalD,OAAO,EACN,uBAAuB,EACvB,wBAAwB,EACxB,qBAAqB,EACrB,eAAe,EACf,kBAAkB,EAClB,SAAS,EACT,aAAa,EACb,eAAe,EACf,QAAQ,GACR,MAAM,uBAAuB,CAAC;AAC/B,QAAQ;AACR,qGAAqG;AACrG,mGAAmG;AACnG,iDAAiD;AACjD,cAAc,kBAAkB,CAAC;AACjC,mBAAmB;AACnB,OAAO,EACN,wBAAwB,EAExB,kBAAkB,GAGlB,MAAM,+BAA+B,CAAC;AAEvC,OAAO,EAAE,eAAe,EAAE,MAAM,0BAA0B,CAAC;AAI3D,OAAO,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AACnD,OAAO,EAAE,WAAW,EAAE,MAAM,sBAAsB,CAAC;AAInD,OAAO,EAAE,cAAc,EAAE,yBAAyB,EAAE,aAAa,EAAE,MAAM,+BAA+B,CAAC;AACzG,OAAO,EAAE,eAAe,EAAE,MAAM,4BAA4B,CAAC;AAe7D,OAAO,EAAE,YAAY,EAAE,8BAA8B,EAAE,MAAM,gBAAgB,CAAC;AAC9E,OAAO,EAAE,OAAO,EAAE,MAAM,kBAAkB,CAAC;AAC3C,OAAO,EACN,gCAAgC,EAChC,wBAAwB,GACxB,MAAM,4BAA4B,CAAC;AAGpC,qEAAqE;AACrE,qDAAqD;AACrD,OAAO,EACN,yBAAyB,EACzB,2BAA2B,EAC3B,0BAA0B,EAC1B,iCAAiC,EACjC,yBAAyB,EACzB,iBAAiB,EACjB,wBAAwB,GAGxB,MAAM,sBAAsB,CAAC;AAE9B;;;;;;;;GAQG","sourcesContent":["/**\n * @pie-qti/item-player\n * Modern QTI player (2.2/3.0) - Framework-agnostic with web components\n */\n\n\n// Export web component registry for pluggable UI components\nexport {\n\ttype ComponentConfig,\n\ttype ComponentPlugin,\n\tComponentRegistry,\n\tcreateComponentRegistry,\n} from './core/ComponentRegistry.js';\nexport * from './core/constants.js';\n// Export drawing utilities\nexport * from './utils/drawingUtils.js';\nexport {\n\tcreateAssessmentItemDefinition,\n\ttype AssessmentItemDefinition,\n\ttype AssessmentItemDefinitionConfig,\n\ttype AssessmentItemDefinitionPlugin,\n} from './core/AssessmentItemDefinition.js';\nexport {\n\ttype ItemPresentationView,\n\ttype ItemSession,\n\ttype ItemSessionCommand,\n\ttype ItemSessionEventCommand,\n\ttype ItemSessionListener,\n\ttype ItemSessionTransition,\n\ttype ItemSessionView,\n\ttype OpenItemSessionOptions,\n} from './core/ItemSession.js';\nexport type {\n\tFinalItemBodyHtml,\n\tItemInteractionMount,\n\tItemPresentation,\n\tItemPresentationFlowNode,\n} from './presentation/itemPresentationPlan.js';\nexport { getRoleCapabilities, type RoleCapabilities } from './core/rolePolicy.js';\n// Render-facing interaction contracts. Standard extractors remain implementation details.\nexport type * from './interactions/shared/types.js';\nexport {\n\tcreateExtendedTextNumericRecord,\n\tcreateExtendedTextResponse,\n\tcreateExtendedTextStringResponse,\n\textendedTextResponseToStrings,\n\ttype ExtendedTextNumericRecord,\n\ttype ExtendedTextRecordField,\n} from './interactions/extended-text/response.js';\nexport type {\n\tElementExtractor,\n\tExtractionContext,\n\tExtractionDispatchResult,\n\tExtractionResult,\n\tExtractionUtils,\n\tInteractionDeliveryField,\n\tInteractionDeliveryPathSegment,\n\tInteractionDeliverySchema,\n\tValidationResult,\n\tVariableDeclaration,\n} from './extraction/index.js';\nexport {\n\tcreateExtractionContext,\n\tcreateExtractionRegistry,\n\tcreateExtractionUtils,\n\tExtractionError,\n\tExtractionRegistry,\n\thtmlField,\n\tisErrorResult,\n\tisSuccessResult,\n\turlField,\n} from './extraction/index.js';\n// NOTE:\n// The player’s primary rendering contract is via web components and the Svelte component entrypoint.\n// If you need non-web-component rendering, build it externally against the public extraction APIs.\n// Export all types including adaptive item types\nexport * from './types/index.js';\n// Export utilities\nexport {\n\tglobalPerformanceMonitor,\n\ttype PerformanceEntry,\n\tPerformanceMonitor,\n\ttype PerformanceMonitorConfig,\n\ttype PerformanceReport,\n} from './utils/PerformanceMonitor.js';\n\nexport { isResponseEmpty } from './utils/responseUtils.js';\n\n// PNP profile (QTI 3.0 §6.2)\nexport type { PnpProfile } from './pnp/types.js';\nexport { applyPnpToRoot } from './pnp/applyPnp.js';\nexport { parsePnpXml } from './pnp/parsePnpXml.js';\n\n// Catalog (QTI 3.0 §6.3)\nexport type { CatalogIndex, CatalogCard, CatalogEntry } from './catalog/types.js';\nexport { extractCatalog, extractCatalogFromItemXml, mergeCatalogs } from './catalog/catalogExtractor.js';\nexport { getCatalogEntry } from './catalog/catalogLookup.js';\nexport type { ResolvedItemDeliveryContext } from '@pie-qti/ims-cp-core';\n\n// PCI — Portable Custom Interaction (QTI 3.0 §6.1)\nexport type {\n\tExtractedPci,\n\tPciBoundTo,\n\tPciConfiguration,\n\tPciHostController,\n\tPciHostOptions,\n\tPciModule,\n\tPciModulePathKind,\n\tPciModuleResolutionContext,\n\tPciModuleResolver,\n} from './pci/types.js';\nexport { PciLoadError, PciModuleResolverRequiredError } from './pci/types.js';\nexport { PciHost } from './pci/PciHost.js';\nexport {\n\tcreateAllowlistPciModuleResolver,\n\tPciModuleNotAllowedError,\n} from './pci/allowlistResolver.js';\nexport type { AllowlistPciResolverOptions } from './pci/allowlistResolver.js';\n\n// Re-export QTI heuristics from @pie-qti/ims-cp-core for convenience\n// (heuristics are now in the shared ingestion layer)\nexport {\n\tnormalizeHeuristicsConfig,\n\tapplyFeedbackTextHeuristics,\n\tshouldUseLenientImagePaths,\n\tshouldAutoPopulateFeedbackOutcome,\n\tDEFAULT_HEURISTICS_CONFIG,\n\tSTRICT_QTI_CONFIG,\n\tFEEDBACK_TEXT_TRANSFORMS,\n\ttype QtiHeuristicsConfig,\n\ttype TextTransform,\n} from '@pie-qti/ims-cp-core';\n\n/**\n * NOTE (SSR safety):\n * Web component base classes depend on DOM globals like `HTMLElement` and must not be\n * re-exported from the main entrypoint. Item ownership flows through\n * AssessmentItemDefinition and ItemSession in every deployment.\n *\n * Import web-components from the subpath entry instead:\n * - `@pie-qti/item-player/web-components`\n */\n"]}
@@ -18,13 +18,35 @@ export declare class PciHost implements PciHostController {
18
18
  private loadGeneration;
19
19
  private _response;
20
20
  private _hasResponse;
21
+ /**
22
+ * True once a mounted module has reported a response. While set, the module
23
+ * is the source of truth and `offerResponse()` will not overwrite it.
24
+ */
25
+ private _moduleOwnsResponse;
26
+ /**
27
+ * True between an authoritative `restore()` and the rebuild that applies it.
28
+ * The mounted module still holds the superseded value during that window, so
29
+ * `getResponse()` must report the held one.
30
+ */
31
+ private _restorePending;
21
32
  private readonly _responseChangeListeners;
33
+ private readonly _remountRequestListeners;
22
34
  constructor(data: ExtractedPci, options?: PciHostOptions | string);
23
35
  /**
24
36
  * Register a callback to fire when the PCI's response changes.
25
37
  * The player calls this to wire the PCI into its internal response map.
26
38
  */
27
39
  onResponseChange(callback: (responseId: string, value: unknown) => void): () => void;
40
+ /**
41
+ * Register a callback fired when an authoritative `restore()` lands on a
42
+ * mounted module and the module must be rebuilt from the restored value.
43
+ *
44
+ * The renderer owns the DOM scaffold and its sanitization, so it performs the
45
+ * rebuild: reset the sanitized markup into the mount node, then call
46
+ * `remount(node)`. A host with no renderer wired here still gets the restored
47
+ * value applied — see `restore()`.
48
+ */
49
+ onRemountRequest(callback: () => void): () => void;
28
50
  /**
29
51
  * Load the PCI module from primaryPath, falling back to fallbackPath.
30
52
  * Throws PciLoadError if both fail.
@@ -37,8 +59,45 @@ export declare class PciHost implements PciHostController {
37
59
  initialize(dom: HTMLElement): void;
38
60
  /** Return the current response value from the PCI module. */
39
61
  getResponse(): unknown;
40
- /** Restore a response value into the PCI module (e.g. from session state). */
41
- setResponse(value: unknown): void;
62
+ /**
63
+ * Offer a response the player believes to be current.
64
+ *
65
+ * Declined once a mounted module has reported a response of its own. The
66
+ * player's response map echoes every change back through `setResponses`, so
67
+ * an unconditional push would hand the module its own value mid-interaction
68
+ * and rebuild whatever internal state — selection, cursor, undo history —
69
+ * the module derives from it. Use `restore()` when the player's value must
70
+ * win regardless.
71
+ *
72
+ * @returns `false` when the module retained ownership and the value was not applied.
73
+ */
74
+ offerResponse(value: unknown): boolean;
75
+ /**
76
+ * Authoritatively replace the response, discarding in-progress candidate
77
+ * state and returning ownership to the player.
78
+ *
79
+ * A mounted module is rebuilt from the restored value rather than mutated
80
+ * where a renderer is wired to `onRemountRequest`: "discard candidate state"
81
+ * is what re-instantiation means, and it is the only form the QTI 3.0 PCI
82
+ * contract offers, since state is injected at `getInstance` and there is no
83
+ * setter. Until the rebuild lands, `getResponse()` reports the restored value
84
+ * rather than the module's superseded one.
85
+ *
86
+ * With no rebuild path wired, the value is pushed into the module directly.
87
+ * That mutates rather than discards candidate state, which is all a host
88
+ * without a scaffold owner can do, and it keeps reset-to-default and session
89
+ * restore effective for consumers driving `PciHost` themselves. Before mount,
90
+ * the value is held and applied by `initialize()`.
91
+ */
92
+ restore(value: unknown): void;
93
+ /**
94
+ * Rebuild the module in place from the currently held response.
95
+ *
96
+ * The caller must reset the sanitized DOM scaffold into `dom` first: this
97
+ * discards the previous module instance, resolves a fresh one through the
98
+ * host resolver, and initializes it, which seeds the held response.
99
+ */
100
+ remount(dom: HTMLElement): Promise<void>;
42
101
  /** Disable the PCI (e.g. when role is not candidate, or after final submission). */
43
102
  disable(): void;
44
103
  /** Re-enable the PCI. */
@@ -16,7 +16,19 @@ export class PciHost {
16
16
  this.loadGeneration = 0;
17
17
  this._response = null;
18
18
  this._hasResponse = false;
19
+ /**
20
+ * True once a mounted module has reported a response. While set, the module
21
+ * is the source of truth and `offerResponse()` will not overwrite it.
22
+ */
23
+ this._moduleOwnsResponse = false;
24
+ /**
25
+ * True between an authoritative `restore()` and the rebuild that applies it.
26
+ * The mounted module still holds the superseded value during that window, so
27
+ * `getResponse()` must report the held one.
28
+ */
29
+ this._restorePending = false;
19
30
  this._responseChangeListeners = new Set();
31
+ this._remountRequestListeners = new Set();
20
32
  this.data = data;
21
33
  this.baseUrl = typeof options === 'string' ? options : (options.baseUrl ?? '');
22
34
  this.moduleResolver = typeof options === 'string' ? undefined : options.moduleResolver;
@@ -29,6 +41,19 @@ export class PciHost {
29
41
  this._responseChangeListeners.add(callback);
30
42
  return () => this._responseChangeListeners.delete(callback);
31
43
  }
44
+ /**
45
+ * Register a callback fired when an authoritative `restore()` lands on a
46
+ * mounted module and the module must be rebuilt from the restored value.
47
+ *
48
+ * The renderer owns the DOM scaffold and its sanitization, so it performs the
49
+ * rebuild: reset the sanitized markup into the mount node, then call
50
+ * `remount(node)`. A host with no renderer wired here still gets the restored
51
+ * value applied — see `restore()`.
52
+ */
53
+ onRemountRequest(callback) {
54
+ this._remountRequestListeners.add(callback);
55
+ return () => this._remountRequestListeners.delete(callback);
56
+ }
32
57
  /**
33
58
  * Load the PCI module from primaryPath, falling back to fallbackPath.
34
59
  * Throws PciLoadError if both fail.
@@ -77,6 +102,8 @@ export class PciHost {
77
102
  onResponseChange: (value) => {
78
103
  this._response = value;
79
104
  this._hasResponse = true;
105
+ this._moduleOwnsResponse = true;
106
+ this._restorePending = false;
80
107
  for (const listener of this._responseChangeListeners) {
81
108
  listener(this.data.responseIdentifier, value);
82
109
  }
@@ -87,6 +114,8 @@ export class PciHost {
87
114
  if (this._hasResponse) {
88
115
  this.module.setResponse(this._response);
89
116
  }
117
+ // The module now holds the held value, however it got there.
118
+ this._restorePending = false;
90
119
  }
91
120
  catch (error) {
92
121
  const failedModule = this.module;
@@ -97,13 +126,78 @@ export class PciHost {
97
126
  }
98
127
  /** Return the current response value from the PCI module. */
99
128
  getResponse() {
129
+ if (this._restorePending)
130
+ return this._response;
100
131
  return this.module ? this.module.getResponse() : this._response;
101
132
  }
102
- /** Restore a response value into the PCI module (e.g. from session state). */
103
- setResponse(value) {
133
+ /**
134
+ * Offer a response the player believes to be current.
135
+ *
136
+ * Declined once a mounted module has reported a response of its own. The
137
+ * player's response map echoes every change back through `setResponses`, so
138
+ * an unconditional push would hand the module its own value mid-interaction
139
+ * and rebuild whatever internal state — selection, cursor, undo history —
140
+ * the module derives from it. Use `restore()` when the player's value must
141
+ * win regardless.
142
+ *
143
+ * @returns `false` when the module retained ownership and the value was not applied.
144
+ */
145
+ offerResponse(value) {
146
+ if (this._moduleOwnsResponse)
147
+ return false;
148
+ this._response = value;
149
+ this._hasResponse = true;
150
+ if (this.module) {
151
+ this.module.setResponse(value);
152
+ this._restorePending = false;
153
+ }
154
+ return true;
155
+ }
156
+ /**
157
+ * Authoritatively replace the response, discarding in-progress candidate
158
+ * state and returning ownership to the player.
159
+ *
160
+ * A mounted module is rebuilt from the restored value rather than mutated
161
+ * where a renderer is wired to `onRemountRequest`: "discard candidate state"
162
+ * is what re-instantiation means, and it is the only form the QTI 3.0 PCI
163
+ * contract offers, since state is injected at `getInstance` and there is no
164
+ * setter. Until the rebuild lands, `getResponse()` reports the restored value
165
+ * rather than the module's superseded one.
166
+ *
167
+ * With no rebuild path wired, the value is pushed into the module directly.
168
+ * That mutates rather than discards candidate state, which is all a host
169
+ * without a scaffold owner can do, and it keeps reset-to-default and session
170
+ * restore effective for consumers driving `PciHost` themselves. Before mount,
171
+ * the value is held and applied by `initialize()`.
172
+ */
173
+ restore(value) {
104
174
  this._response = value;
105
175
  this._hasResponse = true;
106
- this.module?.setResponse(value);
176
+ this._moduleOwnsResponse = false;
177
+ if (!this.module)
178
+ return;
179
+ if (this._remountRequestListeners.size === 0) {
180
+ this.module.setResponse(value);
181
+ return;
182
+ }
183
+ this._restorePending = true;
184
+ for (const listener of this._remountRequestListeners)
185
+ listener();
186
+ }
187
+ /**
188
+ * Rebuild the module in place from the currently held response.
189
+ *
190
+ * The caller must reset the sanitized DOM scaffold into `dom` first: this
191
+ * discards the previous module instance, resolves a fresh one through the
192
+ * host resolver, and initializes it, which seeds the held response.
193
+ */
194
+ async remount(dom) {
195
+ if (this.destroyed)
196
+ throw new Error('Cannot remount a destroyed PciHost');
197
+ this.module?.destroy();
198
+ this.module = null;
199
+ await this.load();
200
+ this.initialize(dom);
107
201
  }
108
202
  /** Disable the PCI (e.g. when role is not candidate, or after final submission). */
109
203
  disable() {
@@ -120,6 +214,7 @@ export class PciHost {
120
214
  this.module?.destroy();
121
215
  this.module = null;
122
216
  this._responseChangeListeners.clear();
217
+ this._remountRequestListeners.clear();
123
218
  }
124
219
  // ---------------------------------------------------------------------------
125
220
  // Private helpers
@@ -158,6 +253,8 @@ export class PciHost {
158
253
  }
159
254
  this.module?.destroy();
160
255
  this.module = candidate;
256
+ // A freshly adopted module has reported nothing yet.
257
+ this._moduleOwnsResponse = false;
161
258
  }
162
259
  /**
163
260
  * Extract a PciModule from the host resolver's result.
@@ -1 +1 @@
1
- {"version":3,"file":"PciHost.js","sourceRoot":"","sources":["../../src/pci/PciHost.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,YAAY,EAAE,8BAA8B,EAAE,MAAM,YAAY,CAAC;AAE1E;;;;;;;;;GASG;AACH,MAAM,OAAO,OAAO;IAanB,YAAY,IAAkB,EAAE,UAAmC,EAAE;QAT7D,WAAM,GAAqB,IAAI,CAAC;QAChC,cAAS,GAAG,KAAK,CAAC;QAClB,mBAAc,GAAG,CAAC,CAAC;QACnB,cAAS,GAAY,IAAI,CAAC;QAC1B,iBAAY,GAAG,KAAK,CAAC;QACZ,6BAAwB,GAAG,IAAI,GAAG,EAEhD,CAAC;QAGH,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,OAAO,IAAI,EAAE,CAAC,CAAC;QAC/E,IAAI,CAAC,cAAc,GAAG,OAAO,OAAO,KAAK,QAAQ,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,OAAO,CAAC,cAAc,CAAC;IACxF,CAAC;IAED;;;OAGG;IACI,gBAAgB,CAAC,QAAsD;QAC7E,IAAI,CAAC,wBAAwB,CAAC,GAAG,CAAC,QAAQ,CAAC,CAAC;QAC5C,OAAO,GAAG,EAAE,CAAC,IAAI,CAAC,wBAAwB,CAAC,MAAM,CAAC,QAAQ,CAAC,CAAC;IAC7D,CAAC;IAED;;;OAGG;IACI,KAAK,CAAC,IAAI;QAChB,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACpB,MAAM,IAAI,KAAK,CAAC,iCA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;SACA,CAAC;QACX,MAAM,cAAc,GAAG,eAAe,CAAC,MAAM,CAC5C,CAAC,MAAM,EAAE,EAAE,CAAC,OAAO,SAAS,EAAE,CAAC,MAAM,CAAC,KAAK,UAAU,CACrD,CAAC;QACF,IAAI,cAAc,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC/B,MAAM,IAAI,KAAK,CACd,kBAAkB,YAAY,iDAAiD;gBAC9E,YAAY,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CACxC,CAAC;QACH,CAAC;QACD,OAAO,SAAsB,CAAC;IAC/B,CAAC;CACD","sourcesContent":["import type {\n\tExtractedPci,\n\tPciBoundTo,\n\tPciHostController,\n\tPciHostOptions,\n\tPciModule,\n\tPciModulePathKind,\n\tPciModuleResolver,\n} from './types.js';\nimport { PciLoadError, PciModuleResolverRequiredError } from './types.js';\n\n/**\n * Loads, initializes, and manages the lifecycle of a single PCI module.\n *\n * Usage:\n * const host = new PciHost(extractedData, { baseUrl, moduleResolver });\n * await host.load();\n * host.initialize(domNode);\n * host.getResponse(); // returns current response\n * host.destroy(); // cleanup on player teardown\n */\nexport class PciHost implements PciHostController {\n\tprivate readonly data: ExtractedPci;\n\tprivate readonly baseUrl: string;\n\tprivate readonly moduleResolver: PciModuleResolver | undefined;\n\tprivate module: PciModule | null = null;\n\tprivate destroyed = false;\n\tprivate loadGeneration = 0;\n\tprivate _response: unknown = null;\n\tprivate _hasResponse = false;\n\tprivate readonly _responseChangeListeners = new Set<\n\t\t(responseId: string, value: unknown) => void\n\t>();\n\n\tconstructor(data: ExtractedPci, options: PciHostOptions | string = {}) {\n\t\tthis.data = data;\n\t\tthis.baseUrl = typeof options === 'string' ? options : (options.baseUrl ?? '');\n\t\tthis.moduleResolver = typeof options === 'string' ? undefined : options.moduleResolver;\n\t}\n\n\t/**\n\t * Register a callback to fire when the PCI's response changes.\n\t * The player calls this to wire the PCI into its internal response map.\n\t */\n\tpublic onResponseChange(callback: (responseId: string, value: unknown) => void): () => void {\n\t\tthis._responseChangeListeners.add(callback);\n\t\treturn () => this._responseChangeListeners.delete(callback);\n\t}\n\n\t/**\n\t * Load the PCI module from primaryPath, falling back to fallbackPath.\n\t * Throws PciLoadError if both fail.\n\t */\n\tpublic async load(): Promise<void> {\n\t\tif (this.destroyed) {\n\t\t\tthrow new Error('Cannot load a destroyed PciHost');\n\t\t}\n\t\tif (!this.moduleResolver) {\n\t\t\tthrow new PciModuleResolverRequiredError(\n\t\t\t\tthis.data.responseIdentifier,\n\t\t\t\tthis.data.primaryPath\n\t\t\t);\n\t\t}\n\t\tconst generation = ++this.loadGeneration;\n\n\t\tconst primary = this.resolveUrl(this.data.primaryPath);\n\t\ttry {\n\t\t\tconst mod = await this.resolveModule(primary, this.data.primaryPath, 'primary');\n\t\t\tthis.adoptResolvedModule(mod, this.data.primaryPath, generation);\n\t\t\treturn;\n\t\t} catch (primaryErr) {\n\t\t\tif (!this.isCurrentLoad(generation)) throw primaryErr;\n\t\t\tif (!this.data.fallbackPath) {\n\t\t\t\tthrow new PciLoadError(this.data.primaryPath, undefined, primaryErr as Error);\n\t\t\t}\n\t\t}\n\n\t\tconst fallback = this.resolveUrl(this.data.fallbackPath!);\n\t\ttry {\n\t\t\tconst mod = await this.resolveModule(fallback, this.data.fallbackPath!, 'fallback');\n\t\t\tthis.adoptResolvedModule(mod, this.data.fallbackPath!, generation);\n\t\t} catch (fallbackErr) {\n\t\t\tif (!this.isCurrentLoad(generation)) throw fallbackErr;\n\t\t\tthrow new PciLoadError(\n\t\t\t\tthis.data.primaryPath,\n\t\t\t\tthis.data.fallbackPath,\n\t\t\t\tfallbackErr as Error\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Initialize the PCI inside the given DOM element.\n\t * Must be called after load() resolves.\n\t */\n\tpublic initialize(dom: HTMLElement): void {\n\t\tif (!this.module) return;\n\n\t\tconst boundTo: PciBoundTo = {\n\t\t\tonReady: () => {},\n\t\t\tonResponseChange: (value: unknown) => {\n\t\t\t\tthis._response = value;\n\t\t\t\tthis._hasResponse = true;\n\t\t\t\tfor (const listener of this._responseChangeListeners) {\n\t\t\t\t\tlistener(this.data.responseIdentifier, value);\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\n\t\ttry {\n\t\t\tthis.module.initialize(dom, this.data.config, boundTo);\n\t\t\tif (this._hasResponse) {\n\t\t\t\tthis.module.setResponse(this._response);\n\t\t\t}\n\t\t} catch (error) {\n\t\t\tconst failedModule = this.module;\n\t\t\tthis.module = null;\n\t\t\tfailedModule.destroy();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/** Return the current response value from the PCI module. */\n\tpublic getResponse(): unknown {\n\t\treturn this.module ? this.module.getResponse() : this._response;\n\t}\n\n\t/** Restore a response value into the PCI module (e.g. from session state). */\n\tpublic setResponse(value: unknown): void {\n\t\tthis._response = value;\n\t\tthis._hasResponse = true;\n\t\tthis.module?.setResponse(value);\n\t}\n\n\t/** Disable the PCI (e.g. when role is not candidate, or after final submission). */\n\tpublic disable(): void {\n\t\tthis.module?.disable();\n\t}\n\n\t/** Re-enable the PCI. */\n\tpublic enable(): void {\n\t\tthis.module?.enable();\n\t}\n\n\t/** Tear down the PCI and release all resources. */\n\tpublic destroy(): void {\n\t\tthis.destroyed = true;\n\t\tthis.loadGeneration++;\n\t\tthis.module?.destroy();\n\t\tthis.module = null;\n\t\tthis._responseChangeListeners.clear();\n\t}\n\n\t// ---------------------------------------------------------------------------\n\t// Private helpers\n\t// ---------------------------------------------------------------------------\n\n\tprivate resolveModule(\n\t\tresolvedUrl: string,\n\t\tauthoredPath: string,\n\t\tkind: PciModulePathKind\n\t): Promise<unknown> {\n\t\treturn Promise.resolve(\n\t\t\tthis.moduleResolver!(resolvedUrl, {\n\t\t\t\tauthoredPath,\n\t\t\t\tkind,\n\t\t\t\tresponseIdentifier: this.data.responseIdentifier,\n\t\t\t\tcustomInteractionTypeIdentifier: this.data.customInteractionTypeIdentifier,\n\t\t\t})\n\t\t);\n\t}\n\n\tprivate resolveUrl(path: string): string {\n\t\tif (/^[a-z][a-z\\d+.-]*:/i.test(path) || path.startsWith('//') || path.startsWith('/')) {\n\t\t\treturn path;\n\t\t}\n\t\tif (!this.baseUrl) return path;\n\t\t// Relative path: resolve against baseUrl\n\t\tconst base = this.baseUrl.endsWith('/') ? this.baseUrl : this.baseUrl + '/';\n\t\ttry {\n\t\t\treturn new URL(path, base).href;\n\t\t} catch {\n\t\t\treturn base + path;\n\t\t}\n\t}\n\n\tprivate isCurrentLoad(generation: number): boolean {\n\t\treturn !this.destroyed && generation === this.loadGeneration;\n\t}\n\n\tprivate adoptResolvedModule(mod: unknown, authoredPath: string, generation: number): void {\n\t\tconst candidate = this.extractPciInterface(mod, authoredPath);\n\t\tif (!this.isCurrentLoad(generation)) {\n\t\t\tcandidate.destroy();\n\t\t\tthrow new Error('PciHost was destroyed before its module finished loading');\n\t\t}\n\t\tthis.module?.destroy();\n\t\tthis.module = candidate;\n\t}\n\n\t/**\n\t * Extract a PciModule from the host resolver's result.\n\t * Supports: default export, named `getInstance` export, or the module itself.\n\t */\n\tprivate extractPciInterface(mod: any, authoredPath: string): PciModule {\n\t\tconst candidate = mod?.default ?? mod?.getInstance?.() ?? mod;\n\t\tconst requiredMethods = [\n\t\t\t'initialize',\n\t\t\t'getResponse',\n\t\t\t'setResponse',\n\t\t\t'disable',\n\t\t\t'enable',\n\t\t\t'destroy',\n\t\t] as const;\n\t\tconst missingMethods = requiredMethods.filter(\n\t\t\t(method) => typeof candidate?.[method] !== 'function'\n\t\t);\n\t\tif (missingMethods.length > 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`PCI module at '${authoredPath}' does not export a valid PciModule interface; ` +\n\t\t\t\t\t`missing: ${missingMethods.join(', ')}`\n\t\t\t);\n\t\t}\n\t\treturn candidate as PciModule;\n\t}\n}\n"]}
1
+ {"version":3,"file":"PciHost.js","sourceRoot":"","sources":["../../src/pci/PciHost.ts"],"names":[],"mappings":"AASA,OAAO,EAAE,YAAY,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AQ,EAAE,YAAoB;QACzD,MAAM,SAAS,GAAG,GAAG,EAAE,OAAO,IAAI,GAAG,EAAE,WAAW,EAAE,EAAE,IAAI,GAAG,CAAC;QAC9D,MAAM,eAAe,GAAG;YACvB,YAAY;YACZ,aAAa;YACb,aAAa;YACb,SAAS;YACT,QAAQ;YACR,SAAS;SACA,CAAC;QACX,MAAM,cAAc,GAAG,eAAe,CAAC,MAAM,CAC5C,CAAC,MAAM,EAAE,EAAE,CAAC,OAAO,SAAS,EAAE,CAAC,MAAM,CAAC,KAAK,UAAU,CACrD,CAAC;QACF,IAAI,cAAc,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YAC/B,MAAM,IAAI,KAAK,CACd,kBAAkB,YAAY,iDAAiD;gBAC9E,YAAY,cAAc,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CACxC,CAAC;QACH,CAAC;QACD,OAAO,SAAsB,CAAC;IAC/B,CAAC;CACD","sourcesContent":["import type {\n\tExtractedPci,\n\tPciBoundTo,\n\tPciHostController,\n\tPciHostOptions,\n\tPciModule,\n\tPciModulePathKind,\n\tPciModuleResolver,\n} from './types.js';\nimport { PciLoadError, PciModuleResolverRequiredError } from './types.js';\n\n/**\n * Loads, initializes, and manages the lifecycle of a single PCI module.\n *\n * Usage:\n * const host = new PciHost(extractedData, { baseUrl, moduleResolver });\n * await host.load();\n * host.initialize(domNode);\n * host.getResponse(); // returns current response\n * host.destroy(); // cleanup on player teardown\n */\nexport class PciHost implements PciHostController {\n\tprivate readonly data: ExtractedPci;\n\tprivate readonly baseUrl: string;\n\tprivate readonly moduleResolver: PciModuleResolver | undefined;\n\tprivate module: PciModule | null = null;\n\tprivate destroyed = false;\n\tprivate loadGeneration = 0;\n\tprivate _response: unknown = null;\n\tprivate _hasResponse = false;\n\t/**\n\t * True once a mounted module has reported a response. While set, the module\n\t * is the source of truth and `offerResponse()` will not overwrite it.\n\t */\n\tprivate _moduleOwnsResponse = false;\n\t/**\n\t * True between an authoritative `restore()` and the rebuild that applies it.\n\t * The mounted module still holds the superseded value during that window, so\n\t * `getResponse()` must report the held one.\n\t */\n\tprivate _restorePending = false;\n\tprivate readonly _responseChangeListeners = new Set<\n\t\t(responseId: string, value: unknown) => void\n\t>();\n\tprivate readonly _remountRequestListeners = new Set<() => void>();\n\n\tconstructor(data: ExtractedPci, options: PciHostOptions | string = {}) {\n\t\tthis.data = data;\n\t\tthis.baseUrl = typeof options === 'string' ? options : (options.baseUrl ?? '');\n\t\tthis.moduleResolver = typeof options === 'string' ? undefined : options.moduleResolver;\n\t}\n\n\t/**\n\t * Register a callback to fire when the PCI's response changes.\n\t * The player calls this to wire the PCI into its internal response map.\n\t */\n\tpublic onResponseChange(callback: (responseId: string, value: unknown) => void): () => void {\n\t\tthis._responseChangeListeners.add(callback);\n\t\treturn () => this._responseChangeListeners.delete(callback);\n\t}\n\n\t/**\n\t * Register a callback fired when an authoritative `restore()` lands on a\n\t * mounted module and the module must be rebuilt from the restored value.\n\t *\n\t * The renderer owns the DOM scaffold and its sanitization, so it performs the\n\t * rebuild: reset the sanitized markup into the mount node, then call\n\t * `remount(node)`. A host with no renderer wired here still gets the restored\n\t * value applied — see `restore()`.\n\t */\n\tpublic onRemountRequest(callback: () => void): () => void {\n\t\tthis._remountRequestListeners.add(callback);\n\t\treturn () => this._remountRequestListeners.delete(callback);\n\t}\n\n\t/**\n\t * Load the PCI module from primaryPath, falling back to fallbackPath.\n\t * Throws PciLoadError if both fail.\n\t */\n\tpublic async load(): Promise<void> {\n\t\tif (this.destroyed) {\n\t\t\tthrow new Error('Cannot load a destroyed PciHost');\n\t\t}\n\t\tif (!this.moduleResolver) {\n\t\t\tthrow new PciModuleResolverRequiredError(\n\t\t\t\tthis.data.responseIdentifier,\n\t\t\t\tthis.data.primaryPath\n\t\t\t);\n\t\t}\n\t\tconst generation = ++this.loadGeneration;\n\n\t\tconst primary = this.resolveUrl(this.data.primaryPath);\n\t\ttry {\n\t\t\tconst mod = await this.resolveModule(primary, this.data.primaryPath, 'primary');\n\t\t\tthis.adoptResolvedModule(mod, this.data.primaryPath, generation);\n\t\t\treturn;\n\t\t} catch (primaryErr) {\n\t\t\tif (!this.isCurrentLoad(generation)) throw primaryErr;\n\t\t\tif (!this.data.fallbackPath) {\n\t\t\t\tthrow new PciLoadError(this.data.primaryPath, undefined, primaryErr as Error);\n\t\t\t}\n\t\t}\n\n\t\tconst fallback = this.resolveUrl(this.data.fallbackPath!);\n\t\ttry {\n\t\t\tconst mod = await this.resolveModule(fallback, this.data.fallbackPath!, 'fallback');\n\t\t\tthis.adoptResolvedModule(mod, this.data.fallbackPath!, generation);\n\t\t} catch (fallbackErr) {\n\t\t\tif (!this.isCurrentLoad(generation)) throw fallbackErr;\n\t\t\tthrow new PciLoadError(\n\t\t\t\tthis.data.primaryPath,\n\t\t\t\tthis.data.fallbackPath,\n\t\t\t\tfallbackErr as Error\n\t\t\t);\n\t\t}\n\t}\n\n\t/**\n\t * Initialize the PCI inside the given DOM element.\n\t * Must be called after load() resolves.\n\t */\n\tpublic initialize(dom: HTMLElement): void {\n\t\tif (!this.module) return;\n\n\t\tconst boundTo: PciBoundTo = {\n\t\t\tonReady: () => {},\n\t\t\tonResponseChange: (value: unknown) => {\n\t\t\t\tthis._response = value;\n\t\t\t\tthis._hasResponse = true;\n\t\t\t\tthis._moduleOwnsResponse = true;\n\t\t\t\tthis._restorePending = false;\n\t\t\t\tfor (const listener of this._responseChangeListeners) {\n\t\t\t\t\tlistener(this.data.responseIdentifier, value);\n\t\t\t\t}\n\t\t\t},\n\t\t};\n\n\t\ttry {\n\t\t\tthis.module.initialize(dom, this.data.config, boundTo);\n\t\t\tif (this._hasResponse) {\n\t\t\t\tthis.module.setResponse(this._response);\n\t\t\t}\n\t\t\t// The module now holds the held value, however it got there.\n\t\t\tthis._restorePending = false;\n\t\t} catch (error) {\n\t\t\tconst failedModule = this.module;\n\t\t\tthis.module = null;\n\t\t\tfailedModule.destroy();\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/** Return the current response value from the PCI module. */\n\tpublic getResponse(): unknown {\n\t\tif (this._restorePending) return this._response;\n\t\treturn this.module ? this.module.getResponse() : this._response;\n\t}\n\n\t/**\n\t * Offer a response the player believes to be current.\n\t *\n\t * Declined once a mounted module has reported a response of its own. The\n\t * player's response map echoes every change back through `setResponses`, so\n\t * an unconditional push would hand the module its own value mid-interaction\n\t * and rebuild whatever internal state — selection, cursor, undo history —\n\t * the module derives from it. Use `restore()` when the player's value must\n\t * win regardless.\n\t *\n\t * @returns `false` when the module retained ownership and the value was not applied.\n\t */\n\tpublic offerResponse(value: unknown): boolean {\n\t\tif (this._moduleOwnsResponse) return false;\n\t\tthis._response = value;\n\t\tthis._hasResponse = true;\n\t\tif (this.module) {\n\t\t\tthis.module.setResponse(value);\n\t\t\tthis._restorePending = false;\n\t\t}\n\t\treturn true;\n\t}\n\n\t/**\n\t * Authoritatively replace the response, discarding in-progress candidate\n\t * state and returning ownership to the player.\n\t *\n\t * A mounted module is rebuilt from the restored value rather than mutated\n\t * where a renderer is wired to `onRemountRequest`: \"discard candidate state\"\n\t * is what re-instantiation means, and it is the only form the QTI 3.0 PCI\n\t * contract offers, since state is injected at `getInstance` and there is no\n\t * setter. Until the rebuild lands, `getResponse()` reports the restored value\n\t * rather than the module's superseded one.\n\t *\n\t * With no rebuild path wired, the value is pushed into the module directly.\n\t * That mutates rather than discards candidate state, which is all a host\n\t * without a scaffold owner can do, and it keeps reset-to-default and session\n\t * restore effective for consumers driving `PciHost` themselves. Before mount,\n\t * the value is held and applied by `initialize()`.\n\t */\n\tpublic restore(value: unknown): void {\n\t\tthis._response = value;\n\t\tthis._hasResponse = true;\n\t\tthis._moduleOwnsResponse = false;\n\t\tif (!this.module) return;\n\t\tif (this._remountRequestListeners.size === 0) {\n\t\t\tthis.module.setResponse(value);\n\t\t\treturn;\n\t\t}\n\t\tthis._restorePending = true;\n\t\tfor (const listener of this._remountRequestListeners) listener();\n\t}\n\n\t/**\n\t * Rebuild the module in place from the currently held response.\n\t *\n\t * The caller must reset the sanitized DOM scaffold into `dom` first: this\n\t * discards the previous module instance, resolves a fresh one through the\n\t * host resolver, and initializes it, which seeds the held response.\n\t */\n\tpublic async remount(dom: HTMLElement): Promise<void> {\n\t\tif (this.destroyed) throw new Error('Cannot remount a destroyed PciHost');\n\t\tthis.module?.destroy();\n\t\tthis.module = null;\n\t\tawait this.load();\n\t\tthis.initialize(dom);\n\t}\n\n\t/** Disable the PCI (e.g. when role is not candidate, or after final submission). */\n\tpublic disable(): void {\n\t\tthis.module?.disable();\n\t}\n\n\t/** Re-enable the PCI. */\n\tpublic enable(): void {\n\t\tthis.module?.enable();\n\t}\n\n\t/** Tear down the PCI and release all resources. */\n\tpublic destroy(): void {\n\t\tthis.destroyed = true;\n\t\tthis.loadGeneration++;\n\t\tthis.module?.destroy();\n\t\tthis.module = null;\n\t\tthis._responseChangeListeners.clear();\n\t\tthis._remountRequestListeners.clear();\n\t}\n\n\t// ---------------------------------------------------------------------------\n\t// Private helpers\n\t// ---------------------------------------------------------------------------\n\n\tprivate resolveModule(\n\t\tresolvedUrl: string,\n\t\tauthoredPath: string,\n\t\tkind: PciModulePathKind\n\t): Promise<unknown> {\n\t\treturn Promise.resolve(\n\t\t\tthis.moduleResolver!(resolvedUrl, {\n\t\t\t\tauthoredPath,\n\t\t\t\tkind,\n\t\t\t\tresponseIdentifier: this.data.responseIdentifier,\n\t\t\t\tcustomInteractionTypeIdentifier: this.data.customInteractionTypeIdentifier,\n\t\t\t})\n\t\t);\n\t}\n\n\tprivate resolveUrl(path: string): string {\n\t\tif (/^[a-z][a-z\\d+.-]*:/i.test(path) || path.startsWith('//') || path.startsWith('/')) {\n\t\t\treturn path;\n\t\t}\n\t\tif (!this.baseUrl) return path;\n\t\t// Relative path: resolve against baseUrl\n\t\tconst base = this.baseUrl.endsWith('/') ? this.baseUrl : this.baseUrl + '/';\n\t\ttry {\n\t\t\treturn new URL(path, base).href;\n\t\t} catch {\n\t\t\treturn base + path;\n\t\t}\n\t}\n\n\tprivate isCurrentLoad(generation: number): boolean {\n\t\treturn !this.destroyed && generation === this.loadGeneration;\n\t}\n\n\tprivate adoptResolvedModule(mod: unknown, authoredPath: string, generation: number): void {\n\t\tconst candidate = this.extractPciInterface(mod, authoredPath);\n\t\tif (!this.isCurrentLoad(generation)) {\n\t\t\tcandidate.destroy();\n\t\t\tthrow new Error('PciHost was destroyed before its module finished loading');\n\t\t}\n\t\tthis.module?.destroy();\n\t\tthis.module = candidate;\n\t\t// A freshly adopted module has reported nothing yet.\n\t\tthis._moduleOwnsResponse = false;\n\t}\n\n\t/**\n\t * Extract a PciModule from the host resolver's result.\n\t * Supports: default export, named `getInstance` export, or the module itself.\n\t */\n\tprivate extractPciInterface(mod: any, authoredPath: string): PciModule {\n\t\tconst candidate = mod?.default ?? mod?.getInstance?.() ?? mod;\n\t\tconst requiredMethods = [\n\t\t\t'initialize',\n\t\t\t'getResponse',\n\t\t\t'setResponse',\n\t\t\t'disable',\n\t\t\t'enable',\n\t\t\t'destroy',\n\t\t] as const;\n\t\tconst missingMethods = requiredMethods.filter(\n\t\t\t(method) => typeof candidate?.[method] !== 'function'\n\t\t);\n\t\tif (missingMethods.length > 0) {\n\t\t\tthrow new Error(\n\t\t\t\t`PCI module at '${authoredPath}' does not export a valid PciModule interface; ` +\n\t\t\t\t\t`missing: ${missingMethods.join(', ')}`\n\t\t\t);\n\t\t}\n\t\treturn candidate as PciModule;\n\t}\n}\n"]}
@@ -0,0 +1,45 @@
1
+ import type { PciModuleResolutionContext, PciModuleResolver } from './types.js';
2
+ /**
3
+ * Raised when an authored PCI module path falls outside the configured allow-list.
4
+ */
5
+ export declare class PciModuleNotAllowedError extends Error {
6
+ readonly resolvedUrl: string;
7
+ readonly reason: string;
8
+ constructor(resolvedUrl: string, reason: string);
9
+ }
10
+ export interface AllowlistPciResolverOptions {
11
+ /**
12
+ * Origins permitted to serve PCI modules, compared against `URL.origin`
13
+ * (for example `https://cdn.example.com`).
14
+ */
15
+ allowedOrigins?: readonly string[];
16
+ /**
17
+ * Absolute URL prefixes permitted. Checked against the normalized href, so a
18
+ * traversal such as `/pci/../../evil.js` cannot escape its prefix.
19
+ */
20
+ allowedPathPrefixes?: readonly string[];
21
+ /**
22
+ * Module import hook. Defaults to a dynamic `import()`. Supply a different
23
+ * loader to import through a package reader, a cache, or a test double.
24
+ */
25
+ importModule?: (resolvedUrl: string, context: PciModuleResolutionContext) => Promise<unknown>;
26
+ }
27
+ /**
28
+ * Build a `moduleResolver` that imports PCI modules only from an explicit
29
+ * allow-list.
30
+ *
31
+ * PCI code executes with the authority of the realm that imports it, so the
32
+ * player never resolves an authored path on its own. This factory does not
33
+ * remove that gate: a host still has to pass the returned resolver as
34
+ * `PciConfiguration.moduleResolver`, and doing so remains a trust decision. It
35
+ * exists so hosts opt into a reviewed check rather than writing the
36
+ * security-critical part themselves.
37
+ *
38
+ * At least one of `allowedOrigins` or `allowedPathPrefixes` must be non-empty;
39
+ * an empty allow-list would deny everything and is treated as a configuration
40
+ * error rather than silently disabling PCI. When both are given, both must match.
41
+ *
42
+ * Non-http(s) URLs are always refused, which rules out `data:`, `blob:` and
43
+ * `javascript:` module paths regardless of configuration.
44
+ */
45
+ export declare function createAllowlistPciModuleResolver(options: AllowlistPciResolverOptions): PciModuleResolver;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Raised when an authored PCI module path falls outside the configured allow-list.
3
+ */
4
+ export class PciModuleNotAllowedError extends Error {
5
+ constructor(resolvedUrl, reason) {
6
+ super(`PCI module '${resolvedUrl}' is not allowed: ${reason}`);
7
+ this.resolvedUrl = resolvedUrl;
8
+ this.reason = reason;
9
+ this.name = 'PciModuleNotAllowedError';
10
+ }
11
+ }
12
+ /** Parse one allow-list entry, rejecting anything not an absolute http(s) URL. */
13
+ function parseAllowlistUrl(kind, value) {
14
+ let url;
15
+ try {
16
+ url = new URL(value);
17
+ }
18
+ catch {
19
+ throw new Error(`PCI allow-list ${kind} must be an absolute URL: '${value}'`);
20
+ }
21
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
22
+ throw new Error(`PCI allow-list ${kind} must be http(s): '${value}'`);
23
+ }
24
+ return url;
25
+ }
26
+ /**
27
+ * Build a `moduleResolver` that imports PCI modules only from an explicit
28
+ * allow-list.
29
+ *
30
+ * PCI code executes with the authority of the realm that imports it, so the
31
+ * player never resolves an authored path on its own. This factory does not
32
+ * remove that gate: a host still has to pass the returned resolver as
33
+ * `PciConfiguration.moduleResolver`, and doing so remains a trust decision. It
34
+ * exists so hosts opt into a reviewed check rather than writing the
35
+ * security-critical part themselves.
36
+ *
37
+ * At least one of `allowedOrigins` or `allowedPathPrefixes` must be non-empty;
38
+ * an empty allow-list would deny everything and is treated as a configuration
39
+ * error rather than silently disabling PCI. When both are given, both must match.
40
+ *
41
+ * Non-http(s) URLs are always refused, which rules out `data:`, `blob:` and
42
+ * `javascript:` module paths regardless of configuration.
43
+ */
44
+ export function createAllowlistPciModuleResolver(options) {
45
+ const origins = (options.allowedOrigins ?? []).map((origin) => parseAllowlistUrl('origin', origin).origin);
46
+ const prefixes = (options.allowedPathPrefixes ?? []).map((prefix) => parseAllowlistUrl('path prefix', prefix).href);
47
+ if (origins.length === 0 && prefixes.length === 0) {
48
+ throw new Error('createAllowlistPciModuleResolver requires allowedOrigins or allowedPathPrefixes; ' +
49
+ 'an empty allow-list would refuse every module');
50
+ }
51
+ const importModule = options.importModule ?? ((resolvedUrl) => import(/* @vite-ignore */ resolvedUrl));
52
+ return async (resolvedUrl, context) => {
53
+ let url;
54
+ try {
55
+ url = new URL(resolvedUrl);
56
+ }
57
+ catch {
58
+ throw new PciModuleNotAllowedError(resolvedUrl, 'the authored path did not resolve to an absolute URL; set PciConfiguration.baseUrl');
59
+ }
60
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
61
+ throw new PciModuleNotAllowedError(resolvedUrl, `scheme '${url.protocol}' is not http(s)`);
62
+ }
63
+ if (origins.length > 0 && !origins.includes(url.origin)) {
64
+ throw new PciModuleNotAllowedError(resolvedUrl, `origin '${url.origin}' is not allow-listed`);
65
+ }
66
+ if (prefixes.length > 0 && !prefixes.some((prefix) => url.href.startsWith(prefix))) {
67
+ throw new PciModuleNotAllowedError(resolvedUrl, 'no allow-listed path prefix matches');
68
+ }
69
+ return importModule(url.href, context);
70
+ };
71
+ }
72
+ //# sourceMappingURL=allowlistResolver.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"allowlistResolver.js","sourceRoot":"","sources":["../../src/pci/allowlistResolver.ts"],"names":[],"mappings":"AAEA;;GAEG;AACH,MAAM,OAAO,wBAAyB,SAAQ,KAAK;IAClD,YACiB,WAAmB,EACnB,MAAc;QAE9B,KAAK,CAAC,eAAe,WAAW,qBAAqB,MAAM,EAAE,CAAC,CAAC;QAH/C,gBAAW,GAAX,WAAW,CAAQ;QACnB,WAAM,GAAN,MAAM,CAAQ;QAG9B,IAAI,CAAC,IAAI,GAAG,0BAA0B,CAAC;IACxC,CAAC;CACD;AAoBD,kFAAkF;AAClF,SAAS,iBAAiB,CAAC,IAA8B,EAAE,KAAa;IACvE,IAAI,GAAQ,CAAC;IACb,IAAI,CAAC;QACJ,GAAG,GAAG,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC;IACtB,CAAC;IAAC,MAAM,CAAC;QACR,MAAM,IAAI,KAAK,CAAC,kBAAkB,IAAI,8BAA8B,KAAK,GAAG,CAAC,CAAC;IAC/E,CAAC;IACD,IAAI,GAAG,CAAC,QAAQ,KAAK,QAAQ,IAAI,GAAG,CAAC,QAAQ,KAAK,OAAO,EAAE,CAAC;QAC3D,MAAM,IAAI,KAAK,CAAC,kBAAkB,IAAI,sBAAsB,KAAK,GAAG,CAAC,CAAC;IACvE,CAAC;IACD,OAAO,GAAG,CAAC;AACZ,CAAC;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,UAAU,gCAAgC,CAC/C,OAAoC;IAEpC,MAAM,OAAO,GAAG,CAAC,OAAO,CAAC,cAAc,I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G,CAAC,MAAM,uBAAuB,CAAC,CAAC;QAC/F,CAAC;QACD,IAAI,QAAQ,CAAC,MAAM,GAAG,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC,GAAG,CAAC,IAAI,CAAC,UAAU,CAAC,MAAM,CAAC,CAAC,EAAE,CAAC;YACpF,MAAM,IAAI,wBAAwB,CAAC,WAAW,EAAE,qCAAqC,CAAC,CAAC;QACxF,CAAC;QACD,OAAO,YAAY,CAAC,GAAG,CAAC,IAAI,EAAE,OAAO,CAAC,CAAC;IACxC,CAAC,CAAC;AACH,CAAC","sourcesContent":["import type { PciModuleResolutionContext, PciModuleResolver } from './types.js';\n\n/**\n * Raised when an authored PCI module path falls outside the configured allow-list.\n */\nexport class PciModuleNotAllowedError extends Error {\n\tconstructor(\n\t\tpublic readonly resolvedUrl: string,\n\t\tpublic readonly reason: string\n\t) {\n\t\tsuper(`PCI module '${resolvedUrl}' is not allowed: ${reason}`);\n\t\tthis.name = 'PciModuleNotAllowedError';\n\t}\n}\n\nexport interface AllowlistPciResolverOptions {\n\t/**\n\t * Origins permitted to serve PCI modules, compared against `URL.origin`\n\t * (for example `https://cdn.example.com`).\n\t */\n\tallowedOrigins?: readonly string[];\n\t/**\n\t * Absolute URL prefixes permitted. Checked against the normalized href, so a\n\t * traversal such as `/pci/../../evil.js` cannot escape its prefix.\n\t */\n\tallowedPathPrefixes?: readonly string[];\n\t/**\n\t * Module import hook. Defaults to a dynamic `import()`. Supply a different\n\t * loader to import through a package reader, a cache, or a test double.\n\t */\n\timportModule?: (resolvedUrl: string, context: PciModuleResolutionContext) => Promise<unknown>;\n}\n\n/** Parse one allow-list entry, rejecting anything not an absolute http(s) URL. */\nfunction parseAllowlistUrl(kind: 'origin' | 'path prefix', value: string): URL {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(value);\n\t} catch {\n\t\tthrow new Error(`PCI allow-list ${kind} must be an absolute URL: '${value}'`);\n\t}\n\tif (url.protocol !== 'https:' && url.protocol !== 'http:') {\n\t\tthrow new Error(`PCI allow-list ${kind} must be http(s): '${value}'`);\n\t}\n\treturn url;\n}\n\n/**\n * Build a `moduleResolver` that imports PCI modules only from an explicit\n * allow-list.\n *\n * PCI code executes with the authority of the realm that imports it, so the\n * player never resolves an authored path on its own. This factory does not\n * remove that gate: a host still has to pass the returned resolver as\n * `PciConfiguration.moduleResolver`, and doing so remains a trust decision. It\n * exists so hosts opt into a reviewed check rather than writing the\n * security-critical part themselves.\n *\n * At least one of `allowedOrigins` or `allowedPathPrefixes` must be non-empty;\n * an empty allow-list would deny everything and is treated as a configuration\n * error rather than silently disabling PCI. When both are given, both must match.\n *\n * Non-http(s) URLs are always refused, which rules out `data:`, `blob:` and\n * `javascript:` module paths regardless of configuration.\n */\nexport function createAllowlistPciModuleResolver(\n\toptions: AllowlistPciResolverOptions\n): PciModuleResolver {\n\tconst origins = (options.allowedOrigins ?? []).map(\n\t\t(origin) => parseAllowlistUrl('origin', origin).origin\n\t);\n\tconst prefixes = (options.allowedPathPrefixes ?? []).map(\n\t\t(prefix) => parseAllowlistUrl('path prefix', prefix).href\n\t);\n\tif (origins.length === 0 && prefixes.length === 0) {\n\t\tthrow new Error(\n\t\t\t'createAllowlistPciModuleResolver requires allowedOrigins or allowedPathPrefixes; ' +\n\t\t\t\t'an empty allow-list would refuse every module'\n\t\t);\n\t}\n\tconst importModule =\n\t\toptions.importModule ?? ((resolvedUrl: string) => import(/* @vite-ignore */ resolvedUrl));\n\n\treturn async (resolvedUrl: string, context: PciModuleResolutionContext) => {\n\t\tlet url: URL;\n\t\ttry {\n\t\t\turl = new URL(resolvedUrl);\n\t\t} catch {\n\t\t\tthrow new PciModuleNotAllowedError(\n\t\t\t\tresolvedUrl,\n\t\t\t\t'the authored path did not resolve to an absolute URL; set PciConfiguration.baseUrl'\n\t\t\t);\n\t\t}\n\t\tif (url.protocol !== 'https:' && url.protocol !== 'http:') {\n\t\t\tthrow new PciModuleNotAllowedError(resolvedUrl, `scheme '${url.protocol}' is not http(s)`);\n\t\t}\n\t\tif (origins.length > 0 && !origins.includes(url.origin)) {\n\t\t\tthrow new PciModuleNotAllowedError(resolvedUrl, `origin '${url.origin}' is not allow-listed`);\n\t\t}\n\t\tif (prefixes.length > 0 && !prefixes.some((prefix) => url.href.startsWith(prefix))) {\n\t\t\tthrow new PciModuleNotAllowedError(resolvedUrl, 'no allow-listed path prefix matches');\n\t\t}\n\t\treturn importModule(url.href, context);\n\t};\n}\n"]}
@@ -1,3 +1,5 @@
1
1
  export { PciHost } from './PciHost.js';
2
+ export { createAllowlistPciModuleResolver, PciModuleNotAllowedError, } from './allowlistResolver.js';
3
+ export type { AllowlistPciResolverOptions } from './allowlistResolver.js';
2
4
  export type { ExtractedPci, PciBoundTo, PciConfiguration, PciHostController, PciHostOptions, PciModule, PciModulePathKind, PciModuleResolutionContext, PciModuleResolver, } from './types.js';
3
5
  export { PciLoadError, PciModuleResolverRequiredError } from './types.js';
package/dist/pci/index.js CHANGED
@@ -1,3 +1,4 @@
1
1
  export { PciHost } from './PciHost.js';
2
+ export { createAllowlistPciModuleResolver, PciModuleNotAllowedError, } from './allowlistResolver.js';
2
3
  export { PciLoadError, PciModuleResolverRequiredError } from './types.js';
3
4
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/pci/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AAYvC,OAAO,EAAE,YAAY,EAAE,8BAA8B,EAAE,MAAM,YAAY,CAAC","sourcesContent":["export { PciHost } from './PciHost.js';\nexport type {\n\tExtractedPci,\n\tPciBoundTo,\n\tPciConfiguration,\n\tPciHostController,\n\tPciHostOptions,\n\tPciModule,\n\tPciModulePathKind,\n\tPciModuleResolutionContext,\n\tPciModuleResolver,\n} from './types.js';\nexport { PciLoadError, PciModuleResolverRequiredError } from './types.js';\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/pci/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,OAAO,EAAE,MAAM,cAAc,CAAC;AACvC,OAAO,EACN,gCAAgC,EAChC,wBAAwB,GACxB,MAAM,wBAAwB,CAAC;AAahC,OAAO,EAAE,YAAY,EAAE,8BAA8B,EAAE,MAAM,YAAY,CAAC","sourcesContent":["export { PciHost } from './PciHost.js';\nexport {\n\tcreateAllowlistPciModuleResolver,\n\tPciModuleNotAllowedError,\n} from './allowlistResolver.js';\nexport type { AllowlistPciResolverOptions } from './allowlistResolver.js';\nexport type {\n\tExtractedPci,\n\tPciBoundTo,\n\tPciConfiguration,\n\tPciHostController,\n\tPciHostOptions,\n\tPciModule,\n\tPciModulePathKind,\n\tPciModuleResolutionContext,\n\tPciModuleResolver,\n} from './types.js';\nexport { PciLoadError, PciModuleResolverRequiredError } from './types.js';\n"]}
@@ -84,10 +84,31 @@ export interface PciHostOptions {
84
84
  */
85
85
  export interface PciHostController {
86
86
  onResponseChange(callback: (responseId: string, value: unknown) => void): () => void;
87
+ /**
88
+ * Fired when an authoritative `restore()` lands on a mounted module. The
89
+ * renderer owns scaffold sanitization, so it resets the markup and calls
90
+ * `remount()`.
91
+ */
92
+ onRemountRequest(callback: () => void): () => void;
87
93
  load(): Promise<void>;
88
94
  initialize(dom: HTMLElement): void;
95
+ /** Rebuild the module in place from the held response, after a scaffold reset. */
96
+ remount(dom: HTMLElement): Promise<void>;
89
97
  getResponse(): unknown;
90
- setResponse(value: unknown): void;
98
+ /**
99
+ * Offer a response the player believes to be current. Declined, returning
100
+ * `false`, once a mounted module has reported a response of its own: a live
101
+ * interaction owns its response until something authoritative replaces it.
102
+ */
103
+ offerResponse(value: unknown): boolean;
104
+ /**
105
+ * Authoritatively replace the response, discarding in-progress candidate
106
+ * state and returning ownership to the player. Session restore, reset to
107
+ * declaration default, and explicit host overrides use this. A mounted module
108
+ * is rebuilt through `onRemountRequest` where a renderer is wired to it, and
109
+ * otherwise receives the value directly.
110
+ */
111
+ restore(value: unknown): void;
91
112
  disable(): void;
92
113
  enable(): void;
93
114
  destroy(): void;
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/pci/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA0HH;;GAEG;AACH,MAAM,OAAO,8BAA+B,SAAQ,KAAK;IACxD,YACiB,kBAA0B,EAC1B,YAAoB;QAEpC,KAAK,CACJ,gDAAgD,kBAAkB,KAAK;YACtE,4DAA4D,YAAY,IAAI,CAC7E,CAAC;QANc,uBAAkB,GAAlB,kBAAkB,CAAQ;QAC1B,iBAAY,GAAZ,YAAY,CAAQ;QAMpC,IAAI,CAAC,IAAI,GAAG,gCAAgC,CAAC;IAC9C,CAAC;CACD;AAED;;GAEG;AACH,MAAM,OAAO,YAAa,SAAQ,KAAK;IACtC,YACiB,WAAmB,EACnB,YAAgC,EAChD,KAAa;QAEb,KAAK,CACJ,YAAY;YACX,CAAC,CAAC,mCAAmC,WAAW,mBAAmB,YAAY,GAAG;YAClF,CAAC,CAAC,mCAAmC,WAAW,GAAG,CACpD,CAAC;QARc,gBAAW,GAAX,WAAW,CAAQ;QACnB,iBAAY,GAAZ,YAAY,CAAoB;QAQhD,IAAI,CAAC,IAAI,GAAG,cAAc,CAAC;QAC3B,IAAI,KAAK;YAAE,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC;IACvG,CAAC;CACD","sourcesContent":["/**\n * QTI 3.0 Portable Custom Interaction (PCI) types.\n * Based on IMS QTI 3.0 Portable Custom Interaction specification.\n */\n\nimport type { HtmlContent } from '../types/index.js';\n\n/**\n * Callbacks the player provides to a PCI module so it can signal state changes.\n */\nexport interface PciBoundTo {\n\t/** Called when the PCI has finished initializing and is ready to accept responses. */\n\tonReady(): void;\n\t/** Called whenever the candidate's response changes. */\n\tonResponseChange(value: unknown): void;\n}\n\n/**\n * Contract that every PCI module must fulfill.\n * The module's default export (or named `getInstance` export) must implement this interface.\n */\nexport interface PciModule {\n\t/** Initialize the PCI inside the given DOM element. */\n\tinitialize(dom: HTMLElement, config: Record<string, string>, boundTo: PciBoundTo): void;\n\t/** Return the current response value. */\n\tgetResponse(): unknown;\n\t/** Restore a previously-captured response value. */\n\tsetResponse(value: unknown): void;\n\t/** Disable candidate interaction (e.g. after submission or when role is not candidate). */\n\tdisable(): void;\n\t/** Re-enable candidate interaction. */\n\tenable(): void;\n\t/** Tear down: remove event listeners, cancel timers, free resources. */\n\tdestroy(): void;\n}\n\n/** Identifies which authored module path is currently being resolved. */\nexport type PciModulePathKind = 'primary' | 'fallback';\n\n/**\n * Context supplied to a host-owned PCI module resolver.\n *\n * PCI code executes with the authority of the page that loads it. The player therefore\n * never imports an authored URL by itself; an embedding host must decide which URLs or\n * package resources are trusted and return the loaded module explicitly.\n */\nexport interface PciModuleResolutionContext {\n\t/** Original path exactly as authored in the item. */\n\tauthoredPath: string;\n\t/** Whether this is the primary module or the authored fallback. */\n\tkind: PciModulePathKind;\n\t/** Response variable bound to the interaction. */\n\tresponseIdentifier: string;\n\t/** Portable interaction type identifier/URN. */\n\tcustomInteractionTypeIdentifier: string;\n}\n\n/**\n * Host-controlled PCI module resolution hook.\n *\n * The resolver may import an allow-listed URL, read a module from a verified content\n * package, or return a pre-registered module. Its return value may be a PciModule,\n * an ES-module namespace with a default export, or a namespace exposing getInstance().\n */\nexport type PciModuleResolver = (\n\tresolvedUrl: string,\n\tcontext: PciModuleResolutionContext\n) => Promise<unknown> | unknown;\n\n/** Secure-by-default PCI runtime configuration. */\nexport interface PciConfiguration {\n\t/** Directory URL used to resolve relative authored module paths. */\n\tbaseUrl?: string;\n\t/** Required host trust decision for loading/executing a PCI module. */\n\tmoduleResolver: PciModuleResolver;\n}\n\n/**\n * Low-level options accepted by PciHost.\n *\n * `moduleResolver` remains optional here so an unconfigured host can report the\n * secure-default error at load time. Public player configuration requires it.\n */\nexport interface PciHostOptions {\n\tbaseUrl?: string;\n\tmoduleResolver?: PciModuleResolver;\n}\n\n/**\n * Public, structural contract exposed by a PCI host.\n *\n * Keep component boundaries typed against this interface rather than the concrete\n * PciHost class. That allows consumers to combine source and published package\n * entrypoints without TypeScript treating the class's private state as part of\n * the compatibility check.\n */\nexport interface PciHostController {\n\tonResponseChange(callback: (responseId: string, value: unknown) => void): () => void;\n\tload(): Promise<void>;\n\tinitialize(dom: HTMLElement): void;\n\tgetResponse(): unknown;\n\tsetResponse(value: unknown): void;\n\tdisable(): void;\n\tenable(): void;\n\tdestroy(): void;\n}\n\n/**\n * Extracted data from a <qti-portable-custom-interaction> element.\n */\nexport interface ExtractedPci {\n\t/** responseIdentifier attribute value. */\n\tresponseIdentifier: string;\n\t/** customInteractionTypeIdentifier attribute value (URN identifying the PCI type). */\n\tcustomInteractionTypeIdentifier: string;\n\t/** Primary JS module path (required). */\n\tprimaryPath: string;\n\t/** Fallback JS module path (optional). */\n\tfallbackPath?: string;\n\t/** Inner HTML of the <qti-interaction-markup> element. */\n\tmarkup: HtmlContent;\n\t/** Key/value pairs from <qti-pci-properties>/<qti-pci-property>. */\n\tconfig: Record<string, string>;\n}\n\n/**\n * Raised when PCI content is present but the embedding host has not opted into executing it.\n */\nexport class PciModuleResolverRequiredError extends Error {\n\tconstructor(\n\t\tpublic readonly responseIdentifier: string,\n\t\tpublic readonly authoredPath: string\n\t) {\n\t\tsuper(\n\t\t\t`PCI module loading is disabled for response '${responseIdentifier}'. ` +\n\t\t\t\t`Provide a host-controlled moduleResolver before loading '${authoredPath}'.`\n\t\t);\n\t\tthis.name = 'PciModuleResolverRequiredError';\n\t}\n}\n\n/**\n * Thrown when a PCI module fails to load from both primary and fallback paths.\n */\nexport class PciLoadError extends Error {\n\tconstructor(\n\t\tpublic readonly primaryPath: string,\n\t\tpublic readonly fallbackPath: string | undefined,\n\t\tcause?: Error\n\t) {\n\t\tsuper(\n\t\t\tfallbackPath\n\t\t\t\t? `PCI module failed to load from '${primaryPath}' and fallback '${fallbackPath}'`\n\t\t\t\t: `PCI module failed to load from '${primaryPath}'`\n\t\t);\n\t\tthis.name = 'PciLoadError';\n\t\tif (cause) Object.defineProperty(this, 'cause', { value: cause, writable: true, configurable: true });\n\t}\n}\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../src/pci/types.ts"],"names":[],"mappings":"AAAA;;;GAGG;AA+IH;;GAEG;AACH,MAAM,OAAO,8BAA+B,SAAQ,KAAK;IACxD,YACiB,kBAA0B,EAC1B,YAAoB;QAEpC,KAAK,CACJ,gDAAgD,kBAAkB,KAAK;YACtE,4DAA4D,YAAY,IAAI,CAC7E,CAAC;QANc,uBAAkB,GAAlB,kBAAkB,CAAQ;QAC1B,iBAAY,GAAZ,YAAY,CAAQ;QAMpC,IAAI,CAAC,IAAI,GAAG,gCAAgC,CAAC;IAC9C,CAAC;CACD;AAED;;GAEG;AACH,MAAM,OAAO,YAAa,SAAQ,KAAK;IACtC,YACiB,WAAmB,EACnB,YAAgC,EAChD,KAAa;QAEb,KAAK,CACJ,YAAY;YACX,CAAC,CAAC,mCAAmC,WAAW,mBAAmB,YAAY,GAAG;YAClF,CAAC,CAAC,mCAAmC,WAAW,GAAG,CACpD,CAAC;QARc,gBAAW,GAAX,WAAW,CAAQ;QACnB,iBAAY,GAAZ,YAAY,CAAoB;QAQhD,IAAI,CAAC,IAAI,GAAG,cAAc,CAAC;QAC3B,IAAI,KAAK;YAAE,MAAM,CAAC,cAAc,CAAC,IAAI,EAAE,OAAO,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,QAAQ,EAAE,IAAI,EAAE,YAAY,EAAE,IAAI,EAAE,CAAC,CAAC;IACvG,CAAC;CACD","sourcesContent":["/**\n * QTI 3.0 Portable Custom Interaction (PCI) types.\n * Based on IMS QTI 3.0 Portable Custom Interaction specification.\n */\n\nimport type { HtmlContent } from '../types/index.js';\n\n/**\n * Callbacks the player provides to a PCI module so it can signal state changes.\n */\nexport interface PciBoundTo {\n\t/** Called when the PCI has finished initializing and is ready to accept responses. */\n\tonReady(): void;\n\t/** Called whenever the candidate's response changes. */\n\tonResponseChange(value: unknown): void;\n}\n\n/**\n * Contract that every PCI module must fulfill.\n * The module's default export (or named `getInstance` export) must implement this interface.\n */\nexport interface PciModule {\n\t/** Initialize the PCI inside the given DOM element. */\n\tinitialize(dom: HTMLElement, config: Record<string, string>, boundTo: PciBoundTo): void;\n\t/** Return the current response value. */\n\tgetResponse(): unknown;\n\t/** Restore a previously-captured response value. */\n\tsetResponse(value: unknown): void;\n\t/** Disable candidate interaction (e.g. after submission or when role is not candidate). */\n\tdisable(): void;\n\t/** Re-enable candidate interaction. */\n\tenable(): void;\n\t/** Tear down: remove event listeners, cancel timers, free resources. */\n\tdestroy(): void;\n}\n\n/** Identifies which authored module path is currently being resolved. */\nexport type PciModulePathKind = 'primary' | 'fallback';\n\n/**\n * Context supplied to a host-owned PCI module resolver.\n *\n * PCI code executes with the authority of the page that loads it. The player therefore\n * never imports an authored URL by itself; an embedding host must decide which URLs or\n * package resources are trusted and return the loaded module explicitly.\n */\nexport interface PciModuleResolutionContext {\n\t/** Original path exactly as authored in the item. */\n\tauthoredPath: string;\n\t/** Whether this is the primary module or the authored fallback. */\n\tkind: PciModulePathKind;\n\t/** Response variable bound to the interaction. */\n\tresponseIdentifier: string;\n\t/** Portable interaction type identifier/URN. */\n\tcustomInteractionTypeIdentifier: string;\n}\n\n/**\n * Host-controlled PCI module resolution hook.\n *\n * The resolver may import an allow-listed URL, read a module from a verified content\n * package, or return a pre-registered module. Its return value may be a PciModule,\n * an ES-module namespace with a default export, or a namespace exposing getInstance().\n */\nexport type PciModuleResolver = (\n\tresolvedUrl: string,\n\tcontext: PciModuleResolutionContext\n) => Promise<unknown> | unknown;\n\n/** Secure-by-default PCI runtime configuration. */\nexport interface PciConfiguration {\n\t/** Directory URL used to resolve relative authored module paths. */\n\tbaseUrl?: string;\n\t/** Required host trust decision for loading/executing a PCI module. */\n\tmoduleResolver: PciModuleResolver;\n}\n\n/**\n * Low-level options accepted by PciHost.\n *\n * `moduleResolver` remains optional here so an unconfigured host can report the\n * secure-default error at load time. Public player configuration requires it.\n */\nexport interface PciHostOptions {\n\tbaseUrl?: string;\n\tmoduleResolver?: PciModuleResolver;\n}\n\n/**\n * Public, structural contract exposed by a PCI host.\n *\n * Keep component boundaries typed against this interface rather than the concrete\n * PciHost class. That allows consumers to combine source and published package\n * entrypoints without TypeScript treating the class's private state as part of\n * the compatibility check.\n */\nexport interface PciHostController {\n\tonResponseChange(callback: (responseId: string, value: unknown) => void): () => void;\n\t/**\n\t * Fired when an authoritative `restore()` lands on a mounted module. The\n\t * renderer owns scaffold sanitization, so it resets the markup and calls\n\t * `remount()`.\n\t */\n\tonRemountRequest(callback: () => void): () => void;\n\tload(): Promise<void>;\n\tinitialize(dom: HTMLElement): void;\n\t/** Rebuild the module in place from the held response, after a scaffold reset. */\n\tremount(dom: HTMLElement): Promise<void>;\n\tgetResponse(): unknown;\n\t/**\n\t * Offer a response the player believes to be current. Declined, returning\n\t * `false`, once a mounted module has reported a response of its own: a live\n\t * interaction owns its response until something authoritative replaces it.\n\t */\n\tofferResponse(value: unknown): boolean;\n\t/**\n\t * Authoritatively replace the response, discarding in-progress candidate\n\t * state and returning ownership to the player. Session restore, reset to\n\t * declaration default, and explicit host overrides use this. A mounted module\n\t * is rebuilt through `onRemountRequest` where a renderer is wired to it, and\n\t * otherwise receives the value directly.\n\t */\n\trestore(value: unknown): void;\n\tdisable(): void;\n\tenable(): void;\n\tdestroy(): void;\n}\n\n/**\n * Extracted data from a <qti-portable-custom-interaction> element.\n */\nexport interface ExtractedPci {\n\t/** responseIdentifier attribute value. */\n\tresponseIdentifier: string;\n\t/** customInteractionTypeIdentifier attribute value (URN identifying the PCI type). */\n\tcustomInteractionTypeIdentifier: string;\n\t/** Primary JS module path (required). */\n\tprimaryPath: string;\n\t/** Fallback JS module path (optional). */\n\tfallbackPath?: string;\n\t/** Inner HTML of the <qti-interaction-markup> element. */\n\tmarkup: HtmlContent;\n\t/** Key/value pairs from <qti-pci-properties>/<qti-pci-property>. */\n\tconfig: Record<string, string>;\n}\n\n/**\n * Raised when PCI content is present but the embedding host has not opted into executing it.\n */\nexport class PciModuleResolverRequiredError extends Error {\n\tconstructor(\n\t\tpublic readonly responseIdentifier: string,\n\t\tpublic readonly authoredPath: string\n\t) {\n\t\tsuper(\n\t\t\t`PCI module loading is disabled for response '${responseIdentifier}'. ` +\n\t\t\t\t`Provide a host-controlled moduleResolver before loading '${authoredPath}'.`\n\t\t);\n\t\tthis.name = 'PciModuleResolverRequiredError';\n\t}\n}\n\n/**\n * Thrown when a PCI module fails to load from both primary and fallback paths.\n */\nexport class PciLoadError extends Error {\n\tconstructor(\n\t\tpublic readonly primaryPath: string,\n\t\tpublic readonly fallbackPath: string | undefined,\n\t\tcause?: Error\n\t) {\n\t\tsuper(\n\t\t\tfallbackPath\n\t\t\t\t? `PCI module failed to load from '${primaryPath}' and fallback '${fallbackPath}'`\n\t\t\t\t: `PCI module failed to load from '${primaryPath}'`\n\t\t);\n\t\tthis.name = 'PciLoadError';\n\t\tif (cause) Object.defineProperty(this, 'cause', { value: cause, writable: true, configurable: true });\n\t}\n}\n"]}