@pie-qti/item-player 0.1.27 → 1.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (109) hide show
  1. package/README.md +35 -6
  2. package/dist/catalog/applyGlossaryTriggers.js +8 -2
  3. package/dist/catalog/applyGlossaryTriggers.js.map +1 -1
  4. package/dist/catalog/catalogExtractor.js +44 -7
  5. package/dist/catalog/catalogExtractor.js.map +1 -1
  6. package/dist/catalog/catalogLookup.d.ts +8 -0
  7. package/dist/catalog/catalogLookup.js +17 -0
  8. package/dist/catalog/catalogLookup.js.map +1 -1
  9. package/dist/catalog/types.d.ts +3 -3
  10. package/dist/catalog/types.js.map +1 -1
  11. package/dist/components/utils/feedbackUtils.d.ts +9 -4
  12. package/dist/components/utils/feedbackUtils.js +67 -34
  13. package/dist/components/utils/feedbackUtils.js.map +1 -1
  14. package/dist/core/AssessmentItemDefinition.js +35 -0
  15. package/dist/core/AssessmentItemDefinition.js.map +1 -1
  16. package/dist/core/ItemSession.d.ts +19 -1
  17. package/dist/core/ItemSession.js +12 -2
  18. package/dist/core/ItemSession.js.map +1 -1
  19. package/dist/core/Player.d.ts +41 -1
  20. package/dist/core/Player.js +216 -48
  21. package/dist/core/Player.js.map +1 -1
  22. package/dist/core/sanitizer.js +16 -3
  23. package/dist/core/sanitizer.js.map +1 -1
  24. package/dist/document/AssessmentItemDocument.d.ts +12 -5
  25. package/dist/document/AssessmentItemDocument.js +28 -19
  26. package/dist/document/AssessmentItemDocument.js.map +1 -1
  27. package/dist/document/contentPass.d.ts +17 -0
  28. package/dist/document/contentPass.js +40 -0
  29. package/dist/document/contentPass.js.map +1 -0
  30. package/dist/document/printedVariable.d.ts +35 -0
  31. package/dist/document/printedVariable.js +215 -0
  32. package/dist/document/printedVariable.js.map +1 -0
  33. package/dist/{element-class-BzATCyhV.js → element-class-D-kJi_w9.js} +3211 -2125
  34. package/dist/element-class-D-kJi_w9.js.map +1 -0
  35. package/dist/element-class.js +1 -1
  36. package/dist/element.js +1 -1
  37. package/dist/extraction/interactionAccessibility.d.ts +14 -0
  38. package/dist/extraction/interactionAccessibility.js +58 -0
  39. package/dist/extraction/interactionAccessibility.js.map +1 -0
  40. package/dist/extraction/interactionExtractionPipeline.d.ts +4 -1
  41. package/dist/extraction/interactionExtractionPipeline.js +7 -2
  42. package/dist/extraction/interactionExtractionPipeline.js.map +1 -1
  43. package/dist/extraction/utils.js +20 -1
  44. package/dist/extraction/utils.js.map +1 -1
  45. package/dist/index.d.ts +9 -3
  46. package/dist/index.js +4 -0
  47. package/dist/index.js.map +1 -1
  48. package/dist/interactions/order/extractor.js +2 -0
  49. package/dist/interactions/order/extractor.js.map +1 -1
  50. package/dist/interactions/portable-custom/extractor.js +47 -11
  51. package/dist/interactions/portable-custom/extractor.js.map +1 -1
  52. package/dist/interactions/shared/types.d.ts +16 -0
  53. package/dist/interactions/shared/types.js.map +1 -1
  54. package/dist/pci/PciHost.d.ts +85 -43
  55. package/dist/pci/PciHost.js +229 -148
  56. package/dist/pci/PciHost.js.map +1 -1
  57. package/dist/pci/allowlistResolver.d.ts +10 -1
  58. package/dist/pci/allowlistResolver.js +43 -4
  59. package/dist/pci/allowlistResolver.js.map +1 -1
  60. package/dist/pci/amdLoader.d.ts +23 -0
  61. package/dist/pci/amdLoader.js +190 -0
  62. package/dist/pci/amdLoader.js.map +1 -0
  63. package/dist/pci/index.d.ts +14 -3
  64. package/dist/pci/index.js +8 -1
  65. package/dist/pci/index.js.map +1 -1
  66. package/dist/pci/moduleSession.d.ts +41 -0
  67. package/dist/pci/moduleSession.js +2 -0
  68. package/dist/pci/moduleSession.js.map +1 -0
  69. package/dist/pci/pageRealmSession.d.ts +49 -0
  70. package/dist/pci/pageRealmSession.js +193 -0
  71. package/dist/pci/pageRealmSession.js.map +1 -0
  72. package/dist/pci/qtiVariableJson.d.ts +7 -0
  73. package/dist/pci/qtiVariableJson.js +93 -0
  74. package/dist/pci/qtiVariableJson.js.map +1 -0
  75. package/dist/pci/registry.d.ts +15 -0
  76. package/dist/pci/registry.js +77 -0
  77. package/dist/pci/registry.js.map +1 -0
  78. package/dist/pci/resolutionConfig.d.ts +23 -0
  79. package/dist/pci/resolutionConfig.js +63 -0
  80. package/dist/pci/resolutionConfig.js.map +1 -0
  81. package/dist/pci/sandbox/SandboxedPciSession.d.ts +78 -0
  82. package/dist/pci/sandbox/SandboxedPciSession.js +332 -0
  83. package/dist/pci/sandbox/SandboxedPciSession.js.map +1 -0
  84. package/dist/pci/sandbox/iframeConnector.d.ts +13 -0
  85. package/dist/pci/sandbox/iframeConnector.js +94 -0
  86. package/dist/pci/sandbox/iframeConnector.js.map +1 -0
  87. package/dist/pci/sandbox/protocol.d.ts +117 -0
  88. package/dist/pci/sandbox/protocol.js +49 -0
  89. package/dist/pci/sandbox/protocol.js.map +1 -0
  90. package/dist/pci/types.d.ts +213 -30
  91. package/dist/pci/types.js +8 -1
  92. package/dist/pci/types.js.map +1 -1
  93. package/dist/pnp/applyPnp.d.ts +3 -4
  94. package/dist/pnp/applyPnp.js +54 -8
  95. package/dist/pnp/applyPnp.js.map +1 -1
  96. package/dist/pnp/parsePnpXml.d.ts +2 -2
  97. package/dist/pnp/parsePnpXml.js +146 -4
  98. package/dist/pnp/parsePnpXml.js.map +1 -1
  99. package/dist/pnp/types.d.ts +57 -0
  100. package/dist/pnp/types.js.map +1 -1
  101. package/dist/presentation/itemPresentationPlan.d.ts +12 -1
  102. package/dist/presentation/itemPresentationPlan.js +11 -3
  103. package/dist/presentation/itemPresentationPlan.js.map +1 -1
  104. package/dist/server.d.ts +5 -0
  105. package/dist/server.js.map +1 -1
  106. package/dist/types/index.d.ts +5 -0
  107. package/dist/types/index.js.map +1 -1
  108. package/package.json +6 -6
  109. package/dist/element-class-BzATCyhV.js.map +0 -1
@@ -1,24 +1,42 @@
1
- import { PciLoadError, PciModuleResolverRequiredError } from './types.js';
1
+ import { getSharedPciRegistry } from './registry.js';
2
+ import { fromQtiVariableJson, toQtiVariableJson } from './qtiVariableJson.js';
3
+ import { PageRealmPciSession } from './pageRealmSession.js';
4
+ import { SandboxedPciSession } from './sandbox/SandboxedPciSession.js';
2
5
  /**
3
- * Loads, initializes, and manages the lifecycle of a single PCI module.
6
+ * Loads, initializes, and manages the lifecycle of a single PCI module under the
7
+ * QTI 3.0 §6.1 contract.
8
+ *
9
+ * The module-facing contract is engine-independent: a module registers itself
10
+ * against `qtiCustomInteractionContext` as its code evaluates, instantiation
11
+ * goes through the registered `getInstance(dom, configuration, state)` factory
12
+ * — state in, `getResponse()` / `getState()` out, no setter — and an
13
+ * authoritative response change re-instantiates the module. What the host
14
+ * chooses is *where that code runs*: by default the page realm behind a host
15
+ * resolver (`moduleResolver`), or, with `sandbox` configured, a cross-origin
16
+ * runner frame whose document has an opaque origin. The response-ownership
17
+ * state machine below is shared by both engines; only the execution backend
18
+ * (`PciModuleSession`) differs.
4
19
  *
5
20
  * Usage:
6
21
  * const host = new PciHost(extractedData, { baseUrl, moduleResolver });
7
22
  * await host.load();
8
23
  * host.initialize(domNode);
9
- * host.getResponse(); // returns current response
24
+ * host.getResponse(); // current response, in the player's runtime value shape
10
25
  * host.destroy(); // cleanup on player teardown
11
26
  */
12
27
  export class PciHost {
13
28
  constructor(data, options = {}) {
14
- this.module = null;
29
+ this.instance = null;
30
+ this.mountNode = null;
31
+ this.loaded = false;
15
32
  this.destroyed = false;
16
33
  this.loadGeneration = 0;
17
34
  this._response = null;
18
35
  this._hasResponse = false;
19
36
  /**
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.
37
+ * True once a mounted module has reported a response (through its own getResponse
38
+ * captured at `onready`/`ondone`). While set, the module is the source of truth and
39
+ * `offerResponse()` will not overwrite it.
22
40
  */
23
41
  this._moduleOwnsResponse = false;
24
42
  /**
@@ -29,13 +47,50 @@ export class PciHost {
29
47
  this._restorePending = false;
30
48
  this._responseChangeListeners = new Set();
31
49
  this._remountRequestListeners = new Set();
50
+ this._errorListeners = new Set();
32
51
  this.data = data;
33
52
  this.baseUrl = typeof options === 'string' ? options : (options.baseUrl ?? '');
34
53
  this.moduleResolver = typeof options === 'string' ? undefined : options.moduleResolver;
54
+ this.sandboxConfig = typeof options === 'string' ? undefined : options.sandbox;
55
+ this.responseDeclaration =
56
+ typeof options === 'string' ? undefined : options.responseDeclaration;
57
+ this.statusSource = typeof options === 'string' ? undefined : options.status;
58
+ this.registry = typeof options === 'string' ? getSharedPciRegistry() : (options.registry ?? getSharedPciRegistry());
59
+ if (this.sandboxConfig) {
60
+ this.session = new SandboxedPciSession({
61
+ sandbox: this.sandboxConfig,
62
+ data,
63
+ baseUrl: this.baseUrl,
64
+ modulePolicy: typeof options === 'string' ? undefined : options.modulePolicy,
65
+ frameConnector: typeof options === 'string' ? undefined : options.frameConnector,
66
+ parentOrigin: typeof options === 'string' ? undefined : options.parentOrigin,
67
+ });
68
+ }
69
+ else {
70
+ this.session = new PageRealmPciSession({
71
+ data,
72
+ baseUrl: this.baseUrl,
73
+ moduleResolver: this.moduleResolver,
74
+ registry: this.registry,
75
+ ...(typeof options === 'string' ? {} : { registrationTimeoutMs: options.registrationTimeoutMs }),
76
+ });
77
+ }
78
+ this.session.onRemoteReport?.((report) => {
79
+ // The proxy's cache already carries the pushed response; the state
80
+ // joins the instance state and the report counts as the module's own.
81
+ if (report.state !== undefined)
82
+ this._instanceState = report.state;
83
+ this.captureInstanceResponse();
84
+ });
85
+ this.session.onError?.((error) => {
86
+ for (const listener of this._errorListeners)
87
+ listener(error);
88
+ });
35
89
  }
36
90
  /**
37
- * Register a callback to fire when the PCI's response changes.
38
- * The player calls this to wire the PCI into its internal response map.
91
+ * Register a callback to fire when the PCI's response changes. The player calls
92
+ * this to wire the PCI into its internal response map. Values arrive in the
93
+ * player's runtime shape; QTI variable JSON conversion happened at the boundary.
39
94
  */
40
95
  onResponseChange(callback) {
41
96
  this._responseChangeListeners.add(callback);
@@ -47,235 +102,261 @@ export class PciHost {
47
102
  *
48
103
  * The renderer owns the DOM scaffold and its sanitization, so it performs the
49
104
  * 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()`.
105
+ * `remount(node)`. A host with no renderer wired here re-instantiates the
106
+ * module on the last mount node itself.
52
107
  */
53
108
  onRemountRequest(callback) {
54
109
  this._remountRequestListeners.add(callback);
55
110
  return () => this._remountRequestListeners.delete(callback);
56
111
  }
57
112
  /**
58
- * Load the PCI module from primaryPath, falling back to fallbackPath.
59
- * Throws PciLoadError if both fail.
113
+ * Register a callback for asynchronous engine failures: the sandboxed
114
+ * engine's frame handshake, in-frame module load, or instance errors. The
115
+ * page-realm engine rejects `load()` instead and never uses this channel.
116
+ */
117
+ onError(callback) {
118
+ this._errorListeners.add(callback);
119
+ return () => this._errorListeners.delete(callback);
120
+ }
121
+ /**
122
+ * Bring the module's execution backend up: page-realm hosts evaluate the
123
+ * module (primary path, then fallback, through the AMD loader for
124
+ * multi-module declarations) and adopt its registration; the sandboxed
125
+ * engine prepares the init payload and defers the module load to the runner
126
+ * frame, whose failures surface through `onError`. Throws PciLoadError when
127
+ * both page-realm paths fail or the module never registers.
60
128
  */
61
129
  async load() {
62
130
  if (this.destroyed) {
63
131
  throw new Error('Cannot load a destroyed PciHost');
64
132
  }
65
- if (!this.moduleResolver) {
66
- throw new PciModuleResolverRequiredError(this.data.responseIdentifier, this.data.primaryPath);
67
- }
68
133
  const generation = ++this.loadGeneration;
69
- const primary = this.resolveUrl(this.data.primaryPath);
70
- try {
71
- const mod = await this.resolveModule(primary, this.data.primaryPath, 'primary');
72
- this.adoptResolvedModule(mod, this.data.primaryPath, generation);
73
- return;
74
- }
75
- catch (primaryErr) {
76
- if (!this.isCurrentLoad(generation))
77
- throw primaryErr;
78
- if (!this.data.fallbackPath) {
79
- throw new PciLoadError(this.data.primaryPath, undefined, primaryErr);
80
- }
81
- }
82
- const fallback = this.resolveUrl(this.data.fallbackPath);
83
- try {
84
- const mod = await this.resolveModule(fallback, this.data.fallbackPath, 'fallback');
85
- this.adoptResolvedModule(mod, this.data.fallbackPath, generation);
86
- }
87
- catch (fallbackErr) {
88
- if (!this.isCurrentLoad(generation))
89
- throw fallbackErr;
90
- throw new PciLoadError(this.data.primaryPath, this.data.fallbackPath, fallbackErr);
91
- }
134
+ await this.session.load({ isCurrent: () => this.isCurrentLoad(generation) });
135
+ // A freshly adopted module has reported nothing yet; its old instance,
136
+ // from a previous load, is gone with the re-resolution.
137
+ this.destroyInstance();
138
+ this._moduleOwnsResponse = false;
139
+ this.loaded = true;
92
140
  }
93
141
  /**
94
- * Initialize the PCI inside the given DOM element.
95
- * Must be called after load() resolves.
142
+ * Instantiate the PCI inside the given DOM element through the registered
143
+ * `getInstance` factory, seeding it with the held state. Must be called after
144
+ * load() resolves. The sandboxed engine mounts its runner frame here instead:
145
+ * the frame element replaces the scaffold's markup, because the module renders
146
+ * inside the frame, not on the page.
96
147
  */
97
148
  initialize(dom) {
98
- if (!this.module)
149
+ if (!this.loaded)
99
150
  return;
100
- const boundTo = {
101
- onReady: () => { },
102
- onResponseChange: (value) => {
103
- this._response = value;
104
- this._hasResponse = true;
105
- this._moduleOwnsResponse = true;
106
- this._restorePending = false;
107
- for (const listener of this._responseChangeListeners) {
108
- listener(this.data.responseIdentifier, value);
109
- }
110
- },
111
- };
151
+ this.mountNode = dom;
152
+ this._lastSeed = this.seedValue();
112
153
  try {
113
- this.module.initialize(dom, this.data.config, boundTo);
114
- if (this._hasResponse) {
115
- this.module.setResponse(this._response);
116
- }
117
- // The module now holds the held value, however it got there.
154
+ const returned = this.session.instantiate(dom, this.buildConfiguration(), this.seedValue());
155
+ if (returned && typeof returned === 'object')
156
+ this.instance = returned;
118
157
  this._restorePending = false;
119
158
  }
120
159
  catch (error) {
121
- const failedModule = this.module;
122
- this.module = null;
123
- failedModule.destroy();
160
+ this.instance = null;
124
161
  throw error;
125
162
  }
126
163
  }
127
- /** Return the current response value from the PCI module. */
164
+ /** Return the current response value, in the player's runtime value shape. */
128
165
  getResponse() {
129
166
  if (this._restorePending)
130
167
  return this._response;
131
- return this.module ? this.module.getResponse() : this._response;
168
+ if (this.instance) {
169
+ try {
170
+ const value = fromQtiVariableJson(this.instance.getResponse());
171
+ if ((value === null || value === undefined) && this._hasResponse && !this._moduleOwnsResponse) {
172
+ // A freshly instantiated module that has reported nothing yet: the
173
+ // held value is what this instantiation was seeded with (the
174
+ // sandboxed engine's cache stays empty until the frame's first
175
+ // report crosses the bridge).
176
+ return this._response;
177
+ }
178
+ return value;
179
+ }
180
+ catch {
181
+ return this._response;
182
+ }
183
+ }
184
+ return this._response;
185
+ }
186
+ /** The mounted module's state snapshot, when it exposes `getState()`. */
187
+ getState() {
188
+ const live = this.instance?.getState?.();
189
+ return live === undefined ? this._instanceState : live;
132
190
  }
133
191
  /**
134
192
  * Offer a response the player believes to be current.
135
193
  *
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.
194
+ * Declined once a mounted module has reported a response of its own. Under the
195
+ * spec contract there is no setter, so an accepted offer before any report is
196
+ * either held for the next instantiation or, when the value differs from what
197
+ * the mounted module was seeded with, applied by re-instantiating it in place.
142
198
  *
143
199
  * @returns `false` when the module retained ownership and the value was not applied.
144
200
  */
145
201
  offerResponse(value) {
146
202
  if (this._moduleOwnsResponse)
147
203
  return false;
204
+ const unchanged = this.instance !== null && this.valuesEqual(value, this._lastSeed);
148
205
  this._response = value;
149
206
  this._hasResponse = true;
150
- if (this.module) {
151
- this.module.setResponse(value);
152
- this._restorePending = false;
153
- }
207
+ if (!this.instance || unchanged)
208
+ return true;
209
+ this.rebuildInPlace();
154
210
  return true;
155
211
  }
156
212
  /**
157
213
  * Authoritatively replace the response, discarding in-progress candidate
158
214
  * state and returning ownership to the player.
159
215
  *
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()`.
216
+ * "Discard candidate state" is re-instantiation: state is injected at
217
+ * `getInstance` and the contract offers no setter. Where a renderer is wired
218
+ * to `onRemountRequest` it rebuilds through a scaffold reset; otherwise this
219
+ * host re-instantiates the module on the last mount node itself. Until the
220
+ * rebuild lands, `getResponse()` reports the restored value rather than the
221
+ * module's superseded one.
172
222
  */
173
223
  restore(value) {
174
224
  this._response = value;
175
225
  this._hasResponse = true;
176
226
  this._moduleOwnsResponse = false;
177
- if (!this.module)
227
+ if (!this.instance && !this.mountNode)
178
228
  return;
179
- if (this._remountRequestListeners.size === 0) {
180
- this.module.setResponse(value);
229
+ if (this._remountRequestListeners.size > 0) {
230
+ this._restorePending = true;
231
+ for (const listener of this._remountRequestListeners)
232
+ listener();
181
233
  return;
182
234
  }
183
- this._restorePending = true;
184
- for (const listener of this._remountRequestListeners)
185
- listener();
235
+ if (this.instance)
236
+ this.rebuildInPlace();
186
237
  }
187
238
  /**
188
239
  * Rebuild the module in place from the currently held response.
189
240
  *
190
241
  * 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.
242
+ * discards the previous module instance, re-resolves the registration, and
243
+ * instantiates it with the held state.
193
244
  */
194
245
  async remount(dom) {
195
246
  if (this.destroyed)
196
247
  throw new Error('Cannot remount a destroyed PciHost');
197
- this.module?.destroy();
198
- this.module = null;
248
+ this.destroyInstance();
199
249
  await this.load();
200
250
  this.initialize(dom);
201
251
  }
202
- /** Disable the PCI (e.g. when role is not candidate, or after final submission). */
252
+ /**
253
+ * Nudge the module out of interaction, for hosts whose module exposes the
254
+ * optional `disable` method. Conformant modules read their fixed
255
+ * `configuration.status` instead.
256
+ */
203
257
  disable() {
204
- this.module?.disable();
258
+ this.instance?.disable?.();
205
259
  }
206
- /** Re-enable the PCI. */
260
+ /** The counterpart of `disable()`, for modules that expose it. */
207
261
  enable() {
208
- this.module?.enable();
262
+ this.instance?.enable?.();
209
263
  }
210
264
  /** Tear down the PCI and release all resources. */
211
265
  destroy() {
212
266
  this.destroyed = true;
213
267
  this.loadGeneration++;
214
- this.module?.destroy();
215
- this.module = null;
268
+ // Keep the last known module state answerable after teardown.
269
+ this._instanceState = this.instance?.getState?.() ?? this._instanceState;
270
+ this.destroyInstance();
271
+ this.session.dispose();
216
272
  this._responseChangeListeners.clear();
217
273
  this._remountRequestListeners.clear();
274
+ this._errorListeners.clear();
218
275
  }
219
276
  // ---------------------------------------------------------------------------
220
277
  // Private helpers
221
278
  // ---------------------------------------------------------------------------
222
- resolveModule(resolvedUrl, authoredPath, kind) {
223
- return Promise.resolve(this.moduleResolver(resolvedUrl, {
224
- authoredPath,
225
- kind,
279
+ destroyInstance() {
280
+ const instance = this.instance;
281
+ this.instance = null;
282
+ if (!instance)
283
+ return;
284
+ this.session.destroyInstance(instance);
285
+ }
286
+ /**
287
+ * Re-instantiate the current module on the last mount node, discarding the
288
+ * previous instance. The DOM scaffold is not reset here — that is the
289
+ * renderer's job, and this path exists for hosts that wired none.
290
+ */
291
+ rebuildInPlace() {
292
+ if (!this.mountNode || !this.loaded || this.destroyed)
293
+ return;
294
+ this.destroyInstance();
295
+ this._instanceState = undefined;
296
+ this.initialize(this.mountNode);
297
+ }
298
+ buildConfiguration() {
299
+ return {
226
300
  responseIdentifier: this.data.responseIdentifier,
227
- customInteractionTypeIdentifier: this.data.customInteractionTypeIdentifier,
228
- }));
301
+ status: typeof this.statusSource === 'function' ? this.statusSource() : (this.statusSource ?? 'interacting'),
302
+ properties: { ...this.data.config },
303
+ onready: (_instance, state) => {
304
+ if (state !== undefined)
305
+ this._instanceState = state;
306
+ this.captureInstanceResponse();
307
+ },
308
+ ondone: (_instance, state) => {
309
+ if (state !== undefined)
310
+ this._instanceState = state;
311
+ this.captureInstanceResponse();
312
+ },
313
+ };
229
314
  }
230
- resolveUrl(path) {
231
- if (/^[a-z][a-z\d+.-]*:/i.test(path) || path.startsWith('//') || path.startsWith('/')) {
232
- return path;
233
- }
234
- if (!this.baseUrl)
235
- return path;
236
- // Relative path: resolve against baseUrl
237
- const base = this.baseUrl.endsWith('/') ? this.baseUrl : this.baseUrl + '/';
315
+ /** Take the mounted module's response as its own report and publish it. */
316
+ captureInstanceResponse() {
317
+ if (!this.instance)
318
+ return;
238
319
  try {
239
- return new URL(path, base).href;
320
+ const value = fromQtiVariableJson(this.instance.getResponse());
321
+ if (value === null && !this._hasResponse)
322
+ return;
323
+ this._response = value;
324
+ this._hasResponse = true;
325
+ this._moduleOwnsResponse = true;
326
+ this._restorePending = false;
327
+ for (const listener of this._responseChangeListeners) {
328
+ listener(this.data.responseIdentifier, value);
329
+ }
240
330
  }
241
331
  catch {
242
- return base + path;
332
+ // A module whose getResponse() throws has reported nothing yet.
243
333
  }
244
334
  }
245
- isCurrentLoad(generation) {
246
- return !this.destroyed && generation === this.loadGeneration;
335
+ /** The held response as the `state` a fresh instantiation receives. */
336
+ seedValue() {
337
+ if (this._instanceState !== undefined)
338
+ return this._instanceState;
339
+ if (!this._hasResponse)
340
+ return undefined;
341
+ const cardinality = this.responseDeclaration?.cardinality ?? inferCardinality(this._response);
342
+ return toQtiVariableJson(this._response, this.responseDeclaration?.baseType, cardinality);
247
343
  }
248
- adoptResolvedModule(mod, authoredPath, generation) {
249
- const candidate = this.extractPciInterface(mod, authoredPath);
250
- if (!this.isCurrentLoad(generation)) {
251
- candidate.destroy();
252
- throw new Error('PciHost was destroyed before its module finished loading');
344
+ valuesEqual(a, b) {
345
+ if (a === b)
346
+ return true;
347
+ try {
348
+ return JSON.stringify(a) === JSON.stringify(b);
253
349
  }
254
- this.module?.destroy();
255
- this.module = candidate;
256
- // A freshly adopted module has reported nothing yet.
257
- this._moduleOwnsResponse = false;
258
- }
259
- /**
260
- * Extract a PciModule from the host resolver's result.
261
- * Supports: default export, named `getInstance` export, or the module itself.
262
- */
263
- extractPciInterface(mod, authoredPath) {
264
- const candidate = mod?.default ?? mod?.getInstance?.() ?? mod;
265
- const requiredMethods = [
266
- 'initialize',
267
- 'getResponse',
268
- 'setResponse',
269
- 'disable',
270
- 'enable',
271
- 'destroy',
272
- ];
273
- const missingMethods = requiredMethods.filter((method) => typeof candidate?.[method] !== 'function');
274
- if (missingMethods.length > 0) {
275
- throw new Error(`PCI module at '${authoredPath}' does not export a valid PciModule interface; ` +
276
- `missing: ${missingMethods.join(', ')}`);
350
+ catch {
351
+ return false;
277
352
  }
278
- return candidate;
279
353
  }
354
+ isCurrentLoad(generation) {
355
+ return !this.destroyed && generation === this.loadGeneration;
356
+ }
357
+ }
358
+ /** A response's cardinality from its JavaScript shape, when no declaration is known. */
359
+ function inferCardinality(value) {
360
+ return Array.isArray(value) ? 'multiple' : 'single';
280
361
  }
281
362
  //# sourceMappingURL=PciHost.js.map
@@ -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;IAyBnB,YAAY,IAAkB,EAAE,UAAmC,EAAE;QArB7D,WAAM,GAAqB,IAAI,CAAC;QAChC,cAAS,GAAG,KAAK,CAAC;QAClB,mBAAc,GAAG,CAAC,CAAC;QACnB,cAAS,GAAY,IAAI,CAAC;QAC1B,iBAAY,GAAG,KAAK,CAAC;QAC7B;;;WAGG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C,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"]}
1
+ {"version":3,"file":"PciHost.js","sourceRoot":"","sources":["../../src/pci/PciHost.ts"],"names":[],"mappings":"AAUA,OAAO,EAAE,oBAAoB,EAAE,MAAM,eAAe,CAAC;AACrD,OAAO,EAAE,mBAAmB,EAAE,iBAAiB,EAAE,MAAM,sBAAsB,CAAC;AAC9E,OAAO,EAAE,mBAAmB,EAAE,MAAM,uBAAuB,CAAC;AAC5D,OAAO,EAAE,mBAAmB,EAAE,MAAM,kCAAkC,CAAC;AAGvE;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,MAAM,OAAO,OAAO;IAsCnB,YAAY,IAAkB,EAAE,UAAmC,EAAE;QA7B7D,aAAQ,GAA0B,IAAI,CAAC;QACvC,cAAS,GAAuB,IAAI,CAAC;QACrC,WAAM,GAAG,KAAK,CAAC;QACf,cAAS,GAAG,KAAK,CAAC;QAClB,mBAAc,GAAG,CAAC,CAAC;QACnB,cAAS,GAAY,IAAI,CAAC;QAC1B,iBAAY,GAAG,KAAK,CA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PciModuleResolver,\n\tPciRegistryObservation,\n\tQtiPciConfiguration,\n\tQtiPciInstance,\n} from './types.js';\nimport { PciModuleResolverRequiredError } from './types.js';\nimport { getSharedPciRegistry } from './registry.js';\nimport { fromQtiVariableJson, toQtiVariableJson } from './qtiVariableJson.js';\nimport { PageRealmPciSession } from './pageRealmSession.js';\nimport { SandboxedPciSession } from './sandbox/SandboxedPciSession.js';\nimport type { PciModuleSession } from './moduleSession.js';\n\n/**\n * Loads, initializes, and manages the lifecycle of a single PCI module under the\n * QTI 3.0 §6.1 contract.\n *\n * The module-facing contract is engine-independent: a module registers itself\n * against `qtiCustomInteractionContext` as its code evaluates, instantiation\n * goes through the registered `getInstance(dom, configuration, state)` factory\n * — state in, `getResponse()` / `getState()` out, no setter — and an\n * authoritative response change re-instantiates the module. What the host\n * chooses is *where that code runs*: by default the page realm behind a host\n * resolver (`moduleResolver`), or, with `sandbox` configured, a cross-origin\n * runner frame whose document has an opaque origin. The response-ownership\n * state machine below is shared by both engines; only the execution backend\n * (`PciModuleSession`) differs.\n *\n * Usage:\n * const host = new PciHost(extractedData, { baseUrl, moduleResolver });\n * await host.load();\n * host.initialize(domNode);\n * host.getResponse(); // current response, in the player's runtime value shape\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 readonly sandboxConfig: PciHostOptions['sandbox'];\n\tprivate readonly responseDeclaration: PciHostOptions['responseDeclaration'];\n\tprivate readonly statusSource: PciHostOptions['status'];\n\tprivate readonly registry: PciRegistryObservation;\n\tprivate readonly session: PciModuleSession;\n\tprivate instance: QtiPciInstance | null = null;\n\tprivate mountNode: HTMLElement | null = null;\n\tprivate loaded = false;\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 (through its own getResponse\n\t * captured at `onready`/`ondone`). While set, the module is the source of truth and\n\t * `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\t/** The module's own state snapshot, seeded back at the next `getInstance`. */\n\tprivate _instanceState: unknown;\n\t/** The held value the current instantiation was seeded with, for no-op echo detection. */\n\tprivate _lastSeed: unknown;\n\tprivate readonly _responseChangeListeners = new Set<\n\t\t(responseId: string, value: unknown) => void\n\t>();\n\tprivate readonly _remountRequestListeners = new Set<() => void>();\n\tprivate readonly _errorListeners = new Set<(error: Error) => 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\tthis.sandboxConfig = typeof options === 'string' ? undefined : options.sandbox;\n\t\tthis.responseDeclaration =\n\t\t\ttypeof options === 'string' ? undefined : options.responseDeclaration;\n\t\tthis.statusSource = typeof options === 'string' ? undefined : options.status;\n\t\tthis.registry = typeof options === 'string' ? getSharedPciRegistry() : (options.registry ?? getSharedPciRegistry());\n\n\t\tif (this.sandboxConfig) {\n\t\t\tthis.session = new SandboxedPciSession({\n\t\t\t\tsandbox: this.sandboxConfig,\n\t\t\t\tdata,\n\t\t\t\tbaseUrl: this.baseUrl,\n\t\t\t\tmodulePolicy: typeof options === 'string' ? undefined : options.modulePolicy,\n\t\t\t\tframeConnector: typeof options === 'string' ? undefined : options.frameConnector,\n\t\t\t\tparentOrigin: typeof options === 'string' ? undefined : options.parentOrigin,\n\t\t\t});\n\t\t} else {\n\t\t\tthis.session = new PageRealmPciSession({\n\t\t\t\tdata,\n\t\t\t\tbaseUrl: this.baseUrl,\n\t\t\t\tmoduleResolver: this.moduleResolver,\n\t\t\t\tregistry: this.registry,\n\t\t\t\t...(typeof options === 'string' ? {} : { registrationTimeoutMs: options.registrationTimeoutMs }),\n\t\t\t});\n\t\t}\n\t\tthis.session.onRemoteReport?.((report) => {\n\t\t\t// The proxy's cache already carries the pushed response; the state\n\t\t\t// joins the instance state and the report counts as the module's own.\n\t\t\tif (report.state !== undefined) this._instanceState = report.state;\n\t\t\tthis.captureInstanceResponse();\n\t\t});\n\t\tthis.session.onError?.((error) => {\n\t\t\tfor (const listener of this._errorListeners) listener(error);\n\t\t});\n\t}\n\n\t/**\n\t * Register a callback to fire when the PCI's response changes. The player calls\n\t * this to wire the PCI into its internal response map. Values arrive in the\n\t * player's runtime shape; QTI variable JSON conversion happened at the boundary.\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 re-instantiates the\n\t * module on the last mount node itself.\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 * Register a callback for asynchronous engine failures: the sandboxed\n\t * engine's frame handshake, in-frame module load, or instance errors. The\n\t * page-realm engine rejects `load()` instead and never uses this channel.\n\t */\n\tpublic onError(callback: (error: Error) => void): () => void {\n\t\tthis._errorListeners.add(callback);\n\t\treturn () => this._errorListeners.delete(callback);\n\t}\n\n\t/**\n\t * Bring the module's execution backend up: page-realm hosts evaluate the\n\t * module (primary path, then fallback, through the AMD loader for\n\t * multi-module declarations) and adopt its registration; the sandboxed\n\t * engine prepares the init payload and defers the module load to the runner\n\t * frame, whose failures surface through `onError`. Throws PciLoadError when\n\t * both page-realm paths fail or the module never registers.\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\tconst generation = ++this.loadGeneration;\n\t\tawait this.session.load({ isCurrent: () => this.isCurrentLoad(generation) });\n\t\t// A freshly adopted module has reported nothing yet; its old instance,\n\t\t// from a previous load, is gone with the re-resolution.\n\t\tthis.destroyInstance();\n\t\tthis._moduleOwnsResponse = false;\n\t\tthis.loaded = true;\n\t}\n\n\t/**\n\t * Instantiate the PCI inside the given DOM element through the registered\n\t * `getInstance` factory, seeding it with the held state. Must be called after\n\t * load() resolves. The sandboxed engine mounts its runner frame here instead:\n\t * the frame element replaces the scaffold's markup, because the module renders\n\t * inside the frame, not on the page.\n\t */\n\tpublic initialize(dom: HTMLElement): void {\n\t\tif (!this.loaded) return;\n\t\tthis.mountNode = dom;\n\t\tthis._lastSeed = this.seedValue();\n\n\t\ttry {\n\t\t\tconst returned = this.session.instantiate(dom, this.buildConfiguration(), this.seedValue());\n\t\t\tif (returned && typeof returned === 'object') this.instance = returned;\n\t\t\tthis._restorePending = false;\n\t\t} catch (error) {\n\t\t\tthis.instance = null;\n\t\t\tthrow error;\n\t\t}\n\t}\n\n\t/** Return the current response value, in the player's runtime value shape. */\n\tpublic getResponse(): unknown {\n\t\tif (this._restorePending) return this._response;\n\t\tif (this.instance) {\n\t\t\ttry {\n\t\t\t\tconst value = fromQtiVariableJson(this.instance.getResponse());\n\t\t\t\tif ((value === null || value === undefined) && this._hasResponse && !this._moduleOwnsResponse) {\n\t\t\t\t\t// A freshly instantiated module that has reported nothing yet: the\n\t\t\t\t\t// held value is what this instantiation was seeded with (the\n\t\t\t\t\t// sandboxed engine's cache stays empty until the frame's first\n\t\t\t\t\t// report crosses the bridge).\n\t\t\t\t\treturn this._response;\n\t\t\t\t}\n\t\t\t\treturn value;\n\t\t\t} catch {\n\t\t\t\treturn this._response;\n\t\t\t}\n\t\t}\n\t\treturn this._response;\n\t}\n\n\t/** The mounted module's state snapshot, when it exposes `getState()`. */\n\tpublic getState(): unknown {\n\t\tconst live = this.instance?.getState?.();\n\t\treturn live === undefined ? this._instanceState : live;\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. Under the\n\t * spec contract there is no setter, so an accepted offer before any report is\n\t * either held for the next instantiation or, when the value differs from what\n\t * the mounted module was seeded with, applied by re-instantiating it in place.\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\tconst unchanged = this.instance !== null && this.valuesEqual(value, this._lastSeed);\n\t\tthis._response = value;\n\t\tthis._hasResponse = true;\n\t\tif (!this.instance || unchanged) return true;\n\t\tthis.rebuildInPlace();\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 * \"Discard candidate state\" is re-instantiation: state is injected at\n\t * `getInstance` and the contract offers no setter. Where a renderer is wired\n\t * to `onRemountRequest` it rebuilds through a scaffold reset; otherwise this\n\t * host re-instantiates the module on the last mount node itself. Until the\n\t * rebuild lands, `getResponse()` reports the restored value rather than the\n\t * module's superseded one.\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.instance && !this.mountNode) return;\n\t\tif (this._remountRequestListeners.size > 0) {\n\t\t\tthis._restorePending = true;\n\t\t\tfor (const listener of this._remountRequestListeners) listener();\n\t\t\treturn;\n\t\t}\n\t\tif (this.instance) this.rebuildInPlace();\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, re-resolves the registration, and\n\t * instantiates it with the held state.\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.destroyInstance();\n\t\tawait this.load();\n\t\tthis.initialize(dom);\n\t}\n\n\t/**\n\t * Nudge the module out of interaction, for hosts whose module exposes the\n\t * optional `disable` method. Conformant modules read their fixed\n\t * `configuration.status` instead.\n\t */\n\tpublic disable(): void {\n\t\t(this.instance as { disable?: () => void } | null)?.disable?.();\n\t}\n\n\t/** The counterpart of `disable()`, for modules that expose it. */\n\tpublic enable(): void {\n\t\t(this.instance as { enable?: () => void } | null)?.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\t// Keep the last known module state answerable after teardown.\n\t\tthis._instanceState = this.instance?.getState?.() ?? this._instanceState;\n\t\tthis.destroyInstance();\n\t\tthis.session.dispose();\n\t\tthis._responseChangeListeners.clear();\n\t\tthis._remountRequestListeners.clear();\n\t\tthis._errorListeners.clear();\n\t}\n\n\t// ---------------------------------------------------------------------------\n\t// Private helpers\n\t// ---------------------------------------------------------------------------\n\n\tprivate destroyInstance(): void {\n\t\tconst instance = this.instance;\n\t\tthis.instance = null;\n\t\tif (!instance) return;\n\t\tthis.session.destroyInstance(instance);\n\t}\n\n\t/**\n\t * Re-instantiate the current module on the last mount node, discarding the\n\t * previous instance. The DOM scaffold is not reset here — that is the\n\t * renderer's job, and this path exists for hosts that wired none.\n\t */\n\tprivate rebuildInPlace(): void {\n\t\tif (!this.mountNode || !this.loaded || this.destroyed) return;\n\t\tthis.destroyInstance();\n\t\tthis._instanceState = undefined;\n\t\tthis.initialize(this.mountNode);\n\t}\n\n\tprivate buildConfiguration(): QtiPciConfiguration {\n\t\treturn {\n\t\t\tresponseIdentifier: this.data.responseIdentifier,\n\t\t\tstatus: typeof this.statusSource === 'function' ? this.statusSource() : (this.statusSource ?? 'interacting'),\n\t\t\tproperties: { ...this.data.config },\n\t\t\tonready: (_instance, state) => {\n\t\t\t\tif (state !== undefined) this._instanceState = state;\n\t\t\t\tthis.captureInstanceResponse();\n\t\t\t},\n\t\t\tondone: (_instance, state) => {\n\t\t\t\tif (state !== undefined) this._instanceState = state;\n\t\t\t\tthis.captureInstanceResponse();\n\t\t\t},\n\t\t};\n\t}\n\n\t/** Take the mounted module's response as its own report and publish it. */\n\tprivate captureInstanceResponse(): void {\n\t\tif (!this.instance) return;\n\t\ttry {\n\t\t\tconst value = fromQtiVariableJson(this.instance.getResponse());\n\t\t\tif (value === null && !this._hasResponse) return;\n\t\t\tthis._response = value;\n\t\t\tthis._hasResponse = true;\n\t\t\tthis._moduleOwnsResponse = true;\n\t\t\tthis._restorePending = false;\n\t\t\tfor (const listener of this._responseChangeListeners) {\n\t\t\t\tlistener(this.data.responseIdentifier, value);\n\t\t\t}\n\t\t} catch {\n\t\t\t// A module whose getResponse() throws has reported nothing yet.\n\t\t}\n\t}\n\n\t/** The held response as the `state` a fresh instantiation receives. */\n\tprivate seedValue(): unknown {\n\t\tif (this._instanceState !== undefined) return this._instanceState;\n\t\tif (!this._hasResponse) return undefined;\n\t\tconst cardinality = this.responseDeclaration?.cardinality ?? inferCardinality(this._response);\n\t\treturn toQtiVariableJson(\n\t\t\tthis._response,\n\t\t\tthis.responseDeclaration?.baseType,\n\t\t\tcardinality\n\t\t);\n\t}\n\n\tprivate valuesEqual(a: unknown, b: unknown): boolean {\n\t\tif (a === b) return true;\n\t\ttry {\n\t\t\treturn JSON.stringify(a) === JSON.stringify(b);\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n\n\tprivate isCurrentLoad(generation: number): boolean {\n\t\treturn !this.destroyed && generation === this.loadGeneration;\n\t}\n}\n\n/** A response's cardinality from its JavaScript shape, when no declaration is known. */\nfunction inferCardinality(value: unknown): 'single' | 'multiple' {\n\treturn Array.isArray(value) ? 'multiple' : 'single';\n}\n"]}
@@ -1,4 +1,4 @@
1
- import type { PciModuleResolutionContext, PciModuleResolver } from './types.js';
1
+ import type { PciModulePolicy, PciModuleResolutionContext, PciModuleResolver } from './types.js';
2
2
  /**
3
3
  * Raised when an authored PCI module path falls outside the configured allow-list.
4
4
  */
@@ -24,6 +24,15 @@ export interface AllowlistPciResolverOptions {
24
24
  */
25
25
  importModule?: (resolvedUrl: string, context: PciModuleResolutionContext) => Promise<unknown>;
26
26
  }
27
+ /** Options for {@link createAllowlistPciModulePolicy}; no import hook exists. */
28
+ export type AllowlistPciPolicyOptions = Omit<AllowlistPciResolverOptions, 'importModule'>;
29
+ /**
30
+ * Build a `modulePolicy` — the sandboxed engine's variant of the allow-list
31
+ * resolver. It applies exactly the same origin/prefix/scheme checks but never
32
+ * imports anything: the module is not evaluated in the page, so the policy only
33
+ * decides whether its URL may be handed to the runner frame.
34
+ */
35
+ export declare function createAllowlistPciModulePolicy(options: AllowlistPciPolicyOptions): PciModulePolicy;
27
36
  /**
28
37
  * Build a `moduleResolver` that imports PCI modules only from an explicit
29
38
  * allow-list.