pict-section-form 1.3.14 → 1.3.15

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 (42) hide show
  1. package/docs/Injection_Conformance.md +137 -0
  2. package/docs/_sidebar.md +1 -0
  3. package/package.json +6 -5
  4. package/source/providers/Pict-Provider-DynamicFormSolverBehaviors.js +73 -5
  5. package/source/providers/Pict-Provider-DynamicSolver.js +20 -2
  6. package/source/views/Pict-View-Form-Metacontroller.js +685 -90
  7. package/test/Pict-Provider-DynamicFormSolverBehaviors-OrdinalScope_tests.js +105 -0
  8. package/test/Pict-View-Form-Metacontroller-DistinctManifest_tests.js +410 -0
  9. package/test/PictSectionForm-Injection-Conformance_tests.js +751 -0
  10. package/test/browser/Injection-Conformance-Differential-Scenario.js +346 -0
  11. package/test/browser/Injection-Conformance-EdgeCase-Scenario.js +168 -0
  12. package/test/browser/Injection-Conformance-Harness-Driver.js +538 -0
  13. package/test/browser/Injection-Conformance-Harness-Runner.js +487 -0
  14. package/test/browser/Injection-Conformance-Reconstitution-Scenario.js +191 -0
  15. package/test/browser/Injection-Conformance-Standalone-Scenario.js +114 -0
  16. package/test/fixtures/injection/Injection-Fixture-Cases.js +203 -0
  17. package/test/fixtures/injection/Injection-Fixture-Manifest.json +366 -0
  18. package/types/source/providers/Pict-Provider-DynamicFormSolverBehaviors.d.ts +110 -1
  19. package/types/source/providers/Pict-Provider-DynamicFormSolverBehaviors.d.ts.map +1 -1
  20. package/types/source/providers/Pict-Provider-DynamicSolver.d.ts.map +1 -1
  21. package/types/source/providers/Pict-Provider-DynamicTabularData.d.ts +17 -1
  22. package/types/source/providers/Pict-Provider-DynamicTabularData.d.ts.map +1 -1
  23. package/types/source/providers/Pict-Provider-InputExtension.d.ts +31 -0
  24. package/types/source/providers/Pict-Provider-InputExtension.d.ts.map +1 -1
  25. package/types/source/providers/inputs/Pict-Provider-Input-Chart-CSS.d.ts +16 -0
  26. package/types/source/providers/inputs/Pict-Provider-Input-Chart-CSS.d.ts.map +1 -0
  27. package/types/source/providers/inputs/Pict-Provider-Input-Chart.d.ts +47 -0
  28. package/types/source/providers/inputs/Pict-Provider-Input-Chart.d.ts.map +1 -1
  29. package/types/source/providers/inputs/Pict-Provider-Input-Diagram.d.ts +86 -0
  30. package/types/source/providers/inputs/Pict-Provider-Input-Diagram.d.ts.map +1 -1
  31. package/types/source/providers/inputs/Pict-Provider-Input-ObjectEditor.d.ts +128 -0
  32. package/types/source/providers/inputs/Pict-Provider-Input-ObjectEditor.d.ts.map +1 -0
  33. package/types/source/providers/inputs/Pict-Provider-Input-PreciseNumber.d.ts.map +1 -1
  34. package/types/source/providers/inputs/Pict-Provider-Input-TabGroupSelector.d.ts +10 -1
  35. package/types/source/providers/inputs/Pict-Provider-Input-TabGroupSelector.d.ts.map +1 -1
  36. package/types/source/providers/inputs/Pict-Provider-Input-TabSectionSelector.d.ts +10 -1
  37. package/types/source/providers/inputs/Pict-Provider-Input-TabSectionSelector.d.ts.map +1 -1
  38. package/types/source/providers/layouts/Pict-Layout-Tabular.d.ts +76 -4
  39. package/types/source/providers/layouts/Pict-Layout-Tabular.d.ts.map +1 -1
  40. package/types/source/views/Pict-View-DynamicForm.d.ts.map +1 -1
  41. package/types/source/views/Pict-View-Form-Metacontroller.d.ts +63 -2
  42. package/types/source/views/Pict-View-Form-Metacontroller.d.ts.map +1 -1
@@ -0,0 +1,487 @@
1
+ #!/usr/bin/env node
2
+ /*
3
+ Injection conformance, browser tier: the node side.
4
+
5
+ Bundles the in-page driver with browserify (the bundler quackage builds with) and runs it in headless
6
+ Chrome with --dump-dom, so the tier needs no extra dependency; set CHROME_BIN to pick the browser.
7
+
8
+ npm run test:injection [-- --verbose] [-- --rebuild] [-- --keep]
9
+
10
+ Prints [ok] / [fail] / [open] per invariant and exits non-zero when a [fail] check fails. `[open]` marks a
11
+ known, reported gap: it is printed but does not fail the run. Without a browser the run exits non-zero
12
+ saying so, rather than passing quietly -- the tier that runs anywhere is the DOM tier, in
13
+ test/PictSectionForm-Injection-Conformance_tests.js.
14
+
15
+ It is also a library: require() it and call runPage / runDifferential with any manifest.
16
+ */
17
+
18
+ const libFS = require('fs');
19
+ const libOS = require('os');
20
+ const libPath = require('path');
21
+ const libURL = require('url');
22
+ const libChildProcess = require('child_process');
23
+
24
+ const PACKAGE_ROOT = libPath.resolve(__dirname, '..', '..');
25
+ const DRIVER_ENTRY = libPath.join(__dirname, 'Injection-Conformance-Harness-Driver.js');
26
+ const BUNDLE_DIRECTORY = libPath.join(__dirname, 'dist');
27
+ const BUNDLE_PATH = libPath.join(BUNDLE_DIRECTORY, 'injection-conformance-harness.js');
28
+ const RESULTS_PATTERN = /data-results="([A-Za-z0-9+/=]*)"/;
29
+ const DIFFERENTIAL_PHASES = [ 'host', 'pair', 'solo-a', 'solo-b' ];
30
+
31
+ /**
32
+ * @param {string} pDirectory
33
+ * @param {(pFilePath: string) => boolean} fFilter
34
+ * @return {number} the newest modification time in milliseconds
35
+ */
36
+ function newestModifiedTime(pDirectory, fFilter)
37
+ {
38
+ let tmpNewest = 0;
39
+ const tmpEntries = libFS.existsSync(pDirectory) ? libFS.readdirSync(pDirectory, { withFileTypes: true }) : [];
40
+ for (const tmpEntry of tmpEntries)
41
+ {
42
+ const tmpEntryPath = libPath.join(pDirectory, tmpEntry.name);
43
+ if (tmpEntry.isDirectory())
44
+ {
45
+ if (tmpEntry.name !== 'dist')
46
+ {
47
+ tmpNewest = Math.max(tmpNewest, newestModifiedTime(tmpEntryPath, fFilter));
48
+ }
49
+ continue;
50
+ }
51
+ if (fFilter(tmpEntryPath))
52
+ {
53
+ tmpNewest = Math.max(tmpNewest, libFS.statSync(tmpEntryPath).mtimeMs);
54
+ }
55
+ }
56
+ return tmpNewest;
57
+ }
58
+
59
+ /**
60
+ * Browserifies the in-page driver, skipping the build when the bundle is newer than every source file.
61
+ *
62
+ * @param {boolean} [pForce]
63
+ * @return {string} the bundle path
64
+ */
65
+ function buildBundle(pForce)
66
+ {
67
+ const fFilter = (pFilePath) => pFilePath.endsWith('.js') || pFilePath.endsWith('.json');
68
+ const tmpNewestSource = Math.max(
69
+ newestModifiedTime(libPath.join(PACKAGE_ROOT, 'source'), fFilter),
70
+ newestModifiedTime(__dirname, fFilter),
71
+ newestModifiedTime(libPath.join(PACKAGE_ROOT, 'test', 'fixtures'), fFilter));
72
+ if (!pForce && libFS.existsSync(BUNDLE_PATH) && (libFS.statSync(BUNDLE_PATH).mtimeMs > tmpNewestSource))
73
+ {
74
+ return BUNDLE_PATH;
75
+ }
76
+ libFS.mkdirSync(BUNDLE_DIRECTORY, { recursive: true });
77
+ const tmpBrowserify = require.resolve('browserify/bin/cmd.js', { paths: [ PACKAGE_ROOT ] });
78
+ const tmpBuild = libChildProcess.spawnSync(process.execPath, [ tmpBrowserify, DRIVER_ENTRY, '-s', 'PictFormInjectionHarness', '-o', BUNDLE_PATH ], { cwd: PACKAGE_ROOT, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
79
+ if ((tmpBuild.status !== 0) || !libFS.existsSync(BUNDLE_PATH))
80
+ {
81
+ throw new Error(`Bundling the harness driver failed: ${tmpBuild.stderr || tmpBuild.error || 'unknown error'}`);
82
+ }
83
+ return BUNDLE_PATH;
84
+ }
85
+
86
+ /**
87
+ * @param {string} pModuleName
88
+ * @return {string} the module directory
89
+ */
90
+ function findModuleDirectory(pModuleName)
91
+ {
92
+ let tmpDirectory = PACKAGE_ROOT;
93
+ while (tmpDirectory)
94
+ {
95
+ const tmpCandidate = libPath.join(tmpDirectory, 'node_modules', pModuleName);
96
+ if (libFS.existsSync(tmpCandidate))
97
+ {
98
+ return tmpCandidate;
99
+ }
100
+ const tmpParent = libPath.dirname(tmpDirectory);
101
+ if (tmpParent === tmpDirectory)
102
+ {
103
+ break;
104
+ }
105
+ tmpDirectory = tmpParent;
106
+ }
107
+ throw new Error(`Could not find the [${pModuleName}] module from ${PACKAGE_ROOT}.`);
108
+ }
109
+
110
+ /**
111
+ * @return {string|null} path to a chrome-family browser binary, or null when there is none
112
+ */
113
+ function findChrome()
114
+ {
115
+ const tmpCandidates = [ process.env.CHROME_BIN, '/usr/bin/google-chrome', '/usr/bin/google-chrome-stable', '/usr/bin/chromium', '/usr/bin/chromium-browser', '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome' ];
116
+ const tmpCacheDirectory = libPath.join(libOS.homedir(), '.cache', 'puppeteer', 'chrome');
117
+ if (libFS.existsSync(tmpCacheDirectory))
118
+ {
119
+ for (const tmpVersion of libFS.readdirSync(tmpCacheDirectory))
120
+ {
121
+ tmpCandidates.push(libPath.join(tmpCacheDirectory, tmpVersion, 'chrome-linux64', 'chrome'));
122
+ tmpCandidates.push(libPath.join(tmpCacheDirectory, tmpVersion, 'chrome-mac-x64', 'Google Chrome for Testing.app', 'Contents', 'MacOS', 'Google Chrome for Testing'));
123
+ }
124
+ }
125
+ for (const tmpCandidate of tmpCandidates)
126
+ {
127
+ if (tmpCandidate && libFS.existsSync(tmpCandidate))
128
+ {
129
+ return tmpCandidate;
130
+ }
131
+ }
132
+ return null;
133
+ }
134
+
135
+ /**
136
+ * @param {string} pFilePath
137
+ * @return {string}
138
+ */
139
+ function toFileURL(pFilePath)
140
+ {
141
+ return libURL.pathToFileURL(pFilePath).href;
142
+ }
143
+
144
+ /**
145
+ * Runs one page load of the harness and returns what the driver published.
146
+ *
147
+ * @param {Object} pOptions
148
+ * @param {Record<string, any>} pOptions.Config - window.PictFormInjectionHarnessConfig for the page.
149
+ * @param {string} [pOptions.HooksSource] - JavaScript appended to the config script (window.PictFormInjectionHarnessHooks).
150
+ * @param {string} [pOptions.Label] - Names the generated files.
151
+ * @param {string} [pOptions.WorkDirectory] - Where the generated page and config land.
152
+ * @param {number} [pOptions.VirtualTimeBudgetMs]
153
+ * @param {number} [pOptions.TimeoutMs]
154
+ * @return {Record<string, any>} the parsed harness results
155
+ */
156
+ function runPage(pOptions)
157
+ {
158
+ const tmpChrome = findChrome();
159
+ if (!tmpChrome)
160
+ {
161
+ throw new Error('No chrome-family browser found; set CHROME_BIN to one. The tier that runs without a browser is test/PictSectionForm-Injection-Conformance_tests.js.');
162
+ }
163
+ const tmpLabel = pOptions.Label || 'harness';
164
+ const tmpWorkDirectory = pOptions.WorkDirectory || libFS.mkdtempSync(libPath.join(libOS.tmpdir(), 'pict-form-harness-'));
165
+ libFS.mkdirSync(tmpWorkDirectory, { recursive: true });
166
+ const tmpBundle = buildBundle(false);
167
+ const tmpPictDist = libPath.join(findModuleDirectory('pict'), 'dist', 'pict.js');
168
+ const tmpChartDist = libPath.join(findModuleDirectory('chart.js'), 'dist', 'chart.umd.js');
169
+
170
+ const tmpConfigPath = libPath.join(tmpWorkDirectory, `${tmpLabel}-config.js`);
171
+ libFS.writeFileSync(tmpConfigPath, `window.PictFormInjectionHarnessConfig = ${JSON.stringify(pOptions.Config)};\n${pOptions.HooksSource || ''}\n`);
172
+
173
+ const tmpPagePath = libPath.join(tmpWorkDirectory, `${tmpLabel}.html`);
174
+ libFS.writeFileSync(tmpPagePath, `<!doctype html>
175
+ <html lang="en">
176
+ <head>
177
+ <meta charset="utf-8">
178
+ <title>Injection Conformance Harness</title>
179
+ <style id="PICT-CSS"></style>
180
+ <script src="${toFileURL(tmpConfigPath)}"></script>
181
+ <script src="${toFileURL(tmpPictDist)}"></script>
182
+ <script src="${toFileURL(tmpChartDist)}"></script>
183
+ <script src="${toFileURL(tmpBundle)}"></script>
184
+ </head>
185
+ <body>
186
+ <div id="Pict-Form-Container"></div>
187
+ <div id="PictFormInjectionHarness-Results"></div>
188
+ <script>Pict.safeOnDocumentReady(function () { PictFormInjectionHarness.run(); });</script>
189
+ </body>
190
+ </html>
191
+ `);
192
+
193
+ const tmpProfileDirectory = libFS.mkdtempSync(libPath.join(libOS.tmpdir(), 'pict-form-harness-profile-'));
194
+ const tmpBrowser = libChildProcess.spawnSync(tmpChrome,
195
+ [
196
+ '--headless=new', '--disable-gpu', '--no-sandbox', '--no-first-run', '--no-default-browser-check',
197
+ '--allow-file-access-from-files', `--virtual-time-budget=${pOptions.VirtualTimeBudgetMs || 120000}`,
198
+ `--user-data-dir=${tmpProfileDirectory}`, '--dump-dom', toFileURL(tmpPagePath),
199
+ ],
200
+ { encoding: 'utf8', maxBuffer: 512 * 1024 * 1024, timeout: pOptions.TimeoutMs || 180000 });
201
+ libFS.rmSync(tmpProfileDirectory, { recursive: true, force: true });
202
+
203
+ const tmpMatch = RESULTS_PATTERN.exec(tmpBrowser.stdout || '');
204
+ if (!tmpMatch)
205
+ {
206
+ throw new Error(`The harness page published no results (${tmpPagePath}). Browser stderr: ${String(tmpBrowser.stderr || '').split('\n').slice(-12).join('\n')}`);
207
+ }
208
+ return JSON.parse(Buffer.from(tmpMatch[1], 'base64').toString('utf8'));
209
+ }
210
+
211
+ /**
212
+ * @param {any} pLeft
213
+ * @param {any} pRight
214
+ * @param {string} [pPath]
215
+ * @param {Array<string>} [pDifferences]
216
+ * @param {Array<string>} [pIgnoreKeys]
217
+ * @return {Array<string>} addresses that differ
218
+ */
219
+ function deepDifferences(pLeft, pRight, pPath, pDifferences, pIgnoreKeys)
220
+ {
221
+ const tmpPath = pPath || '';
222
+ const tmpDifferences = pDifferences || [];
223
+ const tmpIgnoreKeys = pIgnoreKeys || [];
224
+ if (tmpDifferences.length > 40)
225
+ {
226
+ return tmpDifferences;
227
+ }
228
+ const tmpLeftIsObject = (pLeft !== null) && (typeof pLeft === 'object');
229
+ const tmpRightIsObject = (pRight !== null) && (typeof pRight === 'object');
230
+ if (tmpLeftIsObject && tmpRightIsObject)
231
+ {
232
+ const tmpKeys = Array.from(new Set(Object.keys(pLeft).concat(Object.keys(pRight))));
233
+ for (const tmpKey of tmpKeys)
234
+ {
235
+ if (!tmpPath && tmpIgnoreKeys.includes(tmpKey))
236
+ {
237
+ continue;
238
+ }
239
+ deepDifferences(pLeft[tmpKey], pRight[tmpKey], tmpPath ? `${tmpPath}.${tmpKey}` : tmpKey, tmpDifferences, tmpIgnoreKeys);
240
+ }
241
+ return tmpDifferences;
242
+ }
243
+ if (String(pLeft) !== String(pRight))
244
+ {
245
+ tmpDifferences.push(`${tmpPath || '(root)'}: ${JSON.stringify(pLeft)} vs ${JSON.stringify(pRight)}`);
246
+ }
247
+ return tmpDifferences;
248
+ }
249
+
250
+ /**
251
+ * @param {Record<string, any>} pPhases - phase name -> harness results
252
+ * @param {Array<string>} pSalts
253
+ * @param {Array<string>} [pIgnoreRootKeys] - keys at the unsalted root that hold no copy data
254
+ * @return {Array<Record<string, any>>} checks
255
+ */
256
+ function compareDifferential(pPhases, pSalts, pIgnoreRootKeys)
257
+ {
258
+ const [ tmpSaltA, tmpSaltB ] = pSalts;
259
+ const tmpChecks = [];
260
+ const addCheck = (pLabel, pDifferences, pSeverity) =>
261
+ {
262
+ tmpChecks.push({ Label: pLabel, Passed: pDifferences.length === 0, Severity: pSeverity || 'fail', Detail: pDifferences.slice(0, 12) });
263
+ };
264
+ const tmpPair = pPhases['pair'].Snapshots.Differential;
265
+ const tmpSoloA = pPhases['solo-a'].Snapshots.Differential;
266
+ const tmpSoloB = pPhases['solo-b'].Snapshots.Differential;
267
+ const tmpHost = pPhases['host'].Snapshots.Differential;
268
+ const tmpIgnoreKeys = (pIgnoreRootKeys || []).concat(pPhases['pair'].Info ? (pPhases['pair'].Info.UndeclaredSolverTargets || []) : []);
269
+
270
+ addCheck(`copy ${tmpSaltA}: data is the same next to a sibling copy as it is alone`, deepDifferences(tmpPair.Copies[tmpSaltA].Data, tmpSoloA.Copies[tmpSaltA].Data));
271
+ addCheck(`copy ${tmpSaltB}: data is unaffected by the sibling copy's data`, deepDifferences(tmpPair.Copies[tmpSaltB].Data, tmpSoloB.Copies[tmpSaltB].Data));
272
+ addCheck('unsalted root: injected copies leave it as the host had it', deepDifferences(tmpHost.Root, tmpPair.Root, '', [], tmpIgnoreKeys));
273
+ addCheck(`copy ${tmpSaltA}: section and group visibility matches the copy alone`, deepDifferences(tmpPair.Copies[tmpSaltA].Hidden, tmpSoloA.Copies[tmpSaltA].Hidden));
274
+ addCheck(`copy ${tmpSaltB}: section and group visibility is unaffected by the sibling copy`, deepDifferences(tmpPair.Copies[tmpSaltB].Hidden, tmpSoloB.Copies[tmpSaltB].Hidden));
275
+ addCheck(`copy ${tmpSaltA}: chart data matches the copy alone`, deepDifferences(tmpPair.Copies[tmpSaltA].Charts, tmpSoloA.Copies[tmpSaltA].Charts));
276
+ addCheck(`copy ${tmpSaltB}: chart data is unaffected by the sibling copy`, deepDifferences(tmpPair.Copies[tmpSaltB].Charts, tmpSoloB.Copies[tmpSaltB].Charts));
277
+ return tmpChecks;
278
+ }
279
+
280
+ /**
281
+ * Runs the four differential phases for a manifest and returns the scenario checks plus the comparisons.
282
+ *
283
+ * @param {Object} pOptions - see runPage; plus Manifest, HostManifest, MarshalDestination, InitialAppData, Salts, Fill, DeclareUndeclaredSolverTargets, IgnoreRootKeys.
284
+ * @return {{ Checks: Array<Record<string, any>>, Phases: Record<string, any>, Info: Record<string, any> }}
285
+ */
286
+ function runDifferential(pOptions)
287
+ {
288
+ const tmpSalts = pOptions.Salts || [ 'alpha', 'beta' ];
289
+ const tmpPhases = {};
290
+ let tmpChecks = [];
291
+ for (const tmpPhase of DIFFERENTIAL_PHASES)
292
+ {
293
+ const tmpResults = runPage(Object.assign({}, pOptions,
294
+ {
295
+ Label: `${pOptions.Label || 'differential'}-${tmpPhase}`,
296
+ Config:
297
+ {
298
+ Scenario: 'Differential',
299
+ Phase: tmpPhase,
300
+ Manifest: pOptions.Manifest,
301
+ Manifests: pOptions.Manifests,
302
+ HostManifest: pOptions.HostManifest,
303
+ MarshalDestination: pOptions.MarshalDestination,
304
+ InitialAppData: pOptions.InitialAppData,
305
+ Salts: tmpSalts,
306
+ Fill: pOptions.Fill,
307
+ DeclareUndeclaredSolverTargets: Boolean(pOptions.DeclareUndeclaredSolverTargets),
308
+ },
309
+ }));
310
+ tmpPhases[tmpPhase] = tmpResults;
311
+ tmpChecks = tmpChecks.concat(tmpResults.Checks.map((pCheck) => Object.assign({}, pCheck, { Label: `${tmpPhase}: ${pCheck.Label}` })));
312
+ }
313
+ tmpChecks = tmpChecks.concat(compareDifferential(tmpPhases, tmpSalts, pOptions.IgnoreRootKeys));
314
+ return { Checks: tmpChecks, Phases: tmpPhases, Info: tmpPhases['pair'].Info || {} };
315
+ }
316
+
317
+ /**
318
+ * Runs a manifest live and then again from nothing but the data the live run saved, and compares.
319
+ *
320
+ * @param {Object} pOptions - see runDifferential; the same manifest, host, salts and fill drive both phases.
321
+ *
322
+ * @return {{ Checks: Array<Record<string, any>>, Phases: Record<string, any>, Info: Record<string, any> }}
323
+ */
324
+ function runReconstitution(pOptions)
325
+ {
326
+ const tmpSalts = pOptions.Salts || [ 'alpha', 'beta' ];
327
+ const tmpBaseConfig =
328
+ {
329
+ Scenario: 'Reconstitution',
330
+ Manifest: pOptions.Manifest,
331
+ Manifests: pOptions.Manifests,
332
+ HostManifest: pOptions.HostManifest,
333
+ MarshalDestination: pOptions.MarshalDestination,
334
+ InitialAppData: pOptions.InitialAppData,
335
+ Salts: tmpSalts,
336
+ Fill: pOptions.Fill,
337
+ DeclareUndeclaredSolverTargets: Boolean(pOptions.DeclareUndeclaredSolverTargets),
338
+ };
339
+ const tmpLive = runPage(Object.assign({}, pOptions, { Label: `${pOptions.Label || 'reconstitution'}-live`, Config: Object.assign({}, tmpBaseConfig, { Phase: 'live' }) }));
340
+ let tmpChecks = tmpLive.Checks.map((pCheck) => Object.assign({}, pCheck, { Label: `live: ${pCheck.Label}` }));
341
+ const tmpSavedData = tmpLive.Snapshots ? tmpLive.Snapshots.SavedData : null;
342
+ if (!tmpSavedData)
343
+ {
344
+ tmpChecks.push({ Label: 'the live phase produced data to save', Passed: false, Severity: 'fail', Detail: [ 'no SavedData snapshot; the live phase did not complete' ] });
345
+ return { Checks: tmpChecks, Phases: { live: tmpLive }, Info: tmpLive.Info || {} };
346
+ }
347
+ const tmpRest = runPage(Object.assign({}, pOptions, { Label: `${pOptions.Label || 'reconstitution'}-rest`, Config: Object.assign({}, tmpBaseConfig, { Phase: 'rest', SavedData: tmpSavedData }) }));
348
+ tmpChecks = tmpChecks.concat(tmpRest.Checks.map((pCheck) => Object.assign({}, pCheck, { Label: `rest: ${pCheck.Label}` })));
349
+
350
+ const tmpLiveSnapshot = tmpLive.Snapshots.Reconstitution;
351
+ const tmpRestSnapshot = tmpRest.Snapshots ? tmpRest.Snapshots.Reconstitution : null;
352
+ const addCheck = (pLabel, pDifferences) =>
353
+ {
354
+ tmpChecks.push({ Label: pLabel, Passed: pDifferences.length === 0, Severity: 'fail', Detail: pDifferences.slice(0, 12) });
355
+ };
356
+ if (!tmpRestSnapshot)
357
+ {
358
+ addCheck('the form rebuilt from its saved data', [ 'no Reconstitution snapshot; the rest phase did not complete' ]);
359
+ return { Checks: tmpChecks, Phases: { live: tmpLive, rest: tmpRest }, Info: tmpLive.Info || {} };
360
+ }
361
+ for (const tmpSalt of tmpSalts)
362
+ {
363
+ const tmpLiveCopy = tmpLiveSnapshot.Copies[tmpSalt] || {};
364
+ const tmpRestCopy = tmpRestSnapshot.Copies[tmpSalt] || {};
365
+ addCheck(`copy ${tmpSalt}: data read back from the saved form matches the form that was filled in`, deepDifferences(tmpLiveCopy.Data, tmpRestCopy.Data));
366
+ addCheck(`copy ${tmpSalt}: section and group visibility survives the round trip`, deepDifferences(tmpLiveCopy.Hidden, tmpRestCopy.Hidden));
367
+ addCheck(`copy ${tmpSalt}: chart data survives the round trip`, deepDifferences(tmpLiveCopy.Charts, tmpRestCopy.Charts));
368
+ addCheck(`copy ${tmpSalt}: every input displays what it displayed before the round trip`, deepDifferences(tmpLiveCopy.Displayed, tmpRestCopy.Displayed));
369
+ }
370
+ return { Checks: tmpChecks, Phases: { live: tmpLive, rest: tmpRest }, Info: tmpLive.Info || {} };
371
+ }
372
+
373
+ /**
374
+ * @param {string} pTitle
375
+ * @param {{ Checks: Array<Record<string, any>>, Errors?: Array<string>, Info?: Record<string, any> }} pResults
376
+ * @param {{ Verbose?: boolean }} [pOptions]
377
+ * @return {{ Failures: number, Open: number, Passed: number }}
378
+ */
379
+ function printResults(pTitle, pResults, pOptions)
380
+ {
381
+ const tmpOptions = pOptions || {};
382
+ let tmpFailures = 0;
383
+ let tmpOpen = 0;
384
+ let tmpPassed = 0;
385
+ console.log(`\n# ${pTitle}`);
386
+ for (const tmpCheck of pResults.Checks || [])
387
+ {
388
+ if (tmpCheck.Passed)
389
+ {
390
+ tmpPassed++;
391
+ console.log(`[ok] ${tmpCheck.Label}`);
392
+ continue;
393
+ }
394
+ const tmpDetail = (tmpCheck.Detail === undefined) ? '' : ` -- ${typeof tmpCheck.Detail === 'string' ? tmpCheck.Detail : JSON.stringify(tmpCheck.Detail)}`;
395
+ if (tmpCheck.Severity === 'open')
396
+ {
397
+ tmpOpen++;
398
+ console.log(`[open] ${tmpCheck.Label}${tmpDetail}`);
399
+ continue;
400
+ }
401
+ tmpFailures++;
402
+ console.log(`[fail] ${tmpCheck.Label}${tmpDetail}`);
403
+ }
404
+ if (tmpOptions.Verbose && Array.isArray(pResults.Errors) && (pResults.Errors.length > 0))
405
+ {
406
+ console.log(`\n error-level log lines (${pResults.Errors.length}):`);
407
+ for (const tmpError of Array.from(new Set(pResults.Errors)).slice(0, 25))
408
+ {
409
+ console.log(` - ${tmpError}`);
410
+ }
411
+ }
412
+ if (tmpOptions.Verbose && pResults.Info && (Object.keys(pResults.Info).length > 0))
413
+ {
414
+ console.log(` info: ${JSON.stringify(pResults.Info)}`);
415
+ }
416
+ return { Failures: tmpFailures, Open: tmpOpen, Passed: tmpPassed };
417
+ }
418
+
419
+ /**
420
+ * @return {number} the process exit code
421
+ */
422
+ function main()
423
+ {
424
+ const tmpVerbose = process.argv.includes('--verbose');
425
+ const tmpWorkDirectory = process.argv.includes('--keep') ? libPath.join(BUNDLE_DIRECTORY, 'pages') : undefined;
426
+ if (!findChrome())
427
+ {
428
+ console.log('No chrome-family browser found; set CHROME_BIN to one.');
429
+ console.log('The injection conformance tier that runs without a browser is part of `npm test` (test/PictSectionForm-Injection-Conformance_tests.js).');
430
+ return 2;
431
+ }
432
+ buildBundle(process.argv.includes('--rebuild'));
433
+ const tmpFixture = require('../fixtures/injection/Injection-Fixture-Manifest.json');
434
+ const tmpCases = require('../fixtures/injection/Injection-Fixture-Cases.js');
435
+
436
+ let tmpFailures = 0;
437
+ let tmpOpen = 0;
438
+ let tmpPassed = 0;
439
+ const tmpTally = (pCounts) =>
440
+ {
441
+ tmpFailures += pCounts.Failures;
442
+ tmpOpen += pCounts.Open;
443
+ tmpPassed += pCounts.Passed;
444
+ };
445
+
446
+ const tmpEdgeResults = runPage({ Config: { Scenario: 'EdgeCase' }, Label: 'edge-case', WorkDirectory: tmpWorkDirectory });
447
+ tmpTally(printResults('two salted copies of the fixture manifest and a host form in one page', tmpEdgeResults, { Verbose: tmpVerbose }));
448
+
449
+ const tmpDifferential = runDifferential(
450
+ {
451
+ Manifest: tmpFixture.InjectableManifest,
452
+ HostManifest: tmpFixture.HostManifest,
453
+ MarshalDestination: tmpCases.MARSHAL_DESTINATION,
454
+ InitialAppData: { Orchard: { HostRate: 3 } },
455
+ Salts: tmpCases.SALTS,
456
+ Fill: { Seed: 7, RowCount: 3 },
457
+ DeclareUndeclaredSolverTargets: true,
458
+ IgnoreRootKeys: Object.keys(tmpCases.KNOWN_ROOT_KEYS),
459
+ Label: 'differential',
460
+ WorkDirectory: tmpWorkDirectory,
461
+ });
462
+ tmpTally(printResults('a copy alone against a copy next to a sibling (any manifest, no expected values)', tmpDifferential, { Verbose: tmpVerbose }));
463
+
464
+ const tmpReconstitution = runReconstitution(
465
+ {
466
+ Manifest: tmpFixture.InjectableManifest,
467
+ HostManifest: tmpFixture.HostManifest,
468
+ MarshalDestination: tmpCases.MARSHAL_DESTINATION,
469
+ InitialAppData: { Orchard: { HostRate: 3 } },
470
+ Salts: tmpCases.SALTS,
471
+ Fill: { Seed: 7, RowCount: 3 },
472
+ DeclareUndeclaredSolverTargets: true,
473
+ Label: 'reconstitution',
474
+ WorkDirectory: tmpWorkDirectory,
475
+ });
476
+ tmpTally(printResults('a filled-in form against the same form rebuilt from the data it saved', tmpReconstitution, { Verbose: tmpVerbose }));
477
+
478
+ console.log(`\n${tmpPassed} passing, ${tmpFailures} failing, ${tmpOpen} open check(s)`);
479
+ return (tmpFailures > 0) ? 1 : 0;
480
+ }
481
+
482
+ module.exports = { buildBundle, findChrome, runPage, runDifferential, runReconstitution, compareDifferential, deepDifferences, printResults };
483
+
484
+ if (require.main === module)
485
+ {
486
+ process.exitCode = main();
487
+ }
@@ -0,0 +1,191 @@
1
+ /*
2
+ Reconstitution scenario: does a form built by injecting copies and filling them in match the same form
3
+ rebuilt from nothing but the data it saved?
4
+
5
+ A host application saves the marshalled data and, when the form is opened again, boots with that data and
6
+ injects the same manifests under the same salts. Nothing re-enters the values. So the two runs have to
7
+ agree, or a saved form reads back differently from the one that was filled in -- data landing outside the
8
+ copy it belongs to, a solver overwriting a saved value with a default, an input that cannot marshal its own
9
+ saved value back.
10
+
11
+ Two phases, run by the node side, which compares their snapshots:
12
+ live inject the copies, seed data, solve, and publish both the snapshot and the data to save
13
+ rest boot with that saved data, inject the same copies, solve, and publish the snapshot
14
+
15
+ Config: { Scenario: 'Reconstitution', Phase, Manifest, HostManifest, MarshalDestination?, InitialAppData?,
16
+ Salts, Fill?, SavedData? (rest only), DeclareUndeclaredSolverTargets? }
17
+ */
18
+
19
+ const libDifferential = require('./Injection-Conformance-Differential-Scenario.js');
20
+
21
+ /**
22
+ * @param {any} pValue
23
+ * @return {any}
24
+ */
25
+ function cloneData(pValue)
26
+ {
27
+ return (pValue === undefined) ? undefined : JSON.parse(JSON.stringify(pValue));
28
+ }
29
+
30
+ /**
31
+ * Saved data is relative to the form's marshal destination, and an application boots from its AppData root,
32
+ * so the saved document has to be nested back under the destination on the way in.
33
+ *
34
+ * @param {Record<string, any>} pInitialAppData - What the application would boot with anyway.
35
+ * @param {any} pSavedData - The marshalled data the live phase published.
36
+ * @param {string} [pMarshalDestination] - e.g. `AppData.Orchard`; defaults to the AppData root.
37
+ *
38
+ * @return {Record<string, any>} The AppData to boot with.
39
+ */
40
+ function nestSavedData(pInitialAppData, pSavedData, pMarshalDestination)
41
+ {
42
+ const tmpSaved = (pSavedData === undefined) ? {} : cloneData(pSavedData);
43
+ const tmpDestination = pMarshalDestination || 'AppData';
44
+ const tmpRelative = (tmpDestination === 'AppData') ? '' : tmpDestination.replace(/^AppData\./, '');
45
+ if (tmpRelative.length < 1)
46
+ {
47
+ return tmpSaved;
48
+ }
49
+ const tmpAppData = pInitialAppData || {};
50
+ const tmpSegments = tmpRelative.split('.');
51
+ let tmpCursor = tmpAppData;
52
+ for (let i = 0; i < (tmpSegments.length - 1); i++)
53
+ {
54
+ if (!tmpCursor[tmpSegments[i]] || (typeof(tmpCursor[tmpSegments[i]]) !== 'object'))
55
+ {
56
+ tmpCursor[tmpSegments[i]] = {};
57
+ }
58
+ tmpCursor = tmpCursor[tmpSegments[i]];
59
+ }
60
+ tmpCursor[tmpSegments[tmpSegments.length - 1]] = tmpSaved;
61
+ return tmpAppData;
62
+ }
63
+
64
+ /**
65
+ * The state a reopened form has to reproduce: every copy's data, what is hidden, what the charts hold, and
66
+ * what the inputs actually display.
67
+ *
68
+ * @param {import('./Injection-Conformance-Harness-Driver.js').HarnessContext} pContext
69
+ * @param {Record<string, any>} pOriginal - The manifest as authored, before salting.
70
+ * @param {Record<string, any>} pSalted - The salted copy.
71
+ * @param {string} pSalt
72
+ *
73
+ * @return {Record<string, any>}
74
+ */
75
+ function snapshotCopy(pContext, pOriginal, pSalted, pSalt)
76
+ {
77
+ const tmpHidden = {};
78
+ for (const tmpSection of pOriginal.Sections || [])
79
+ {
80
+ tmpHidden[tmpSection.Hash] = pContext.isSectionHidden(`${tmpSection.Hash}_${pSalt}`);
81
+ for (const tmpGroup of tmpSection.Groups || [])
82
+ {
83
+ tmpHidden[`${tmpSection.Hash}/${tmpGroup.Hash}`] = pContext.isGroupHidden(`${tmpSection.Hash}_${pSalt}`, `${tmpGroup.Hash}_${pSalt}`);
84
+ }
85
+ }
86
+ const tmpCharts = {};
87
+ const tmpDisplayed = {};
88
+ for (const [ tmpKey, tmpDescriptor ] of Object.entries(pSalted.Descriptors || {}))
89
+ {
90
+ const tmpOriginalKey = tmpDescriptor.OriginalHash || tmpDescriptor.OriginalDataAddress || tmpKey;
91
+ if (tmpDescriptor.PictForm && (tmpDescriptor.PictForm.InputType === 'Chart'))
92
+ {
93
+ tmpCharts[tmpOriginalKey] = pContext.getChartData(tmpDescriptor.Hash || tmpKey);
94
+ continue;
95
+ }
96
+ const tmpElement = pContext.getInputElement(tmpDescriptor.Hash || tmpKey);
97
+ if (tmpElement && ('value' in tmpElement))
98
+ {
99
+ tmpDisplayed[tmpOriginalKey] = tmpElement.value;
100
+ }
101
+ }
102
+ return { Data: cloneData(pContext.marshalDestinationObject[pSalt]), Hidden: tmpHidden, Charts: tmpCharts, Displayed: tmpDisplayed };
103
+ }
104
+
105
+ /**
106
+ * @param {import('./Injection-Conformance-Harness-Driver.js').HarnessContext} pContext
107
+ *
108
+ * @return {Promise<void>}
109
+ */
110
+ async function run(pContext)
111
+ {
112
+ const tmpConfig = pContext.config;
113
+ const tmpSalts = tmpConfig.Salts;
114
+ const tmpAtRest = (tmpConfig.Phase === 'rest');
115
+ if (!tmpAtRest && (tmpConfig.Phase !== 'live'))
116
+ {
117
+ throw new Error(`Unknown reconstitution phase [${tmpConfig.Phase}].`);
118
+ }
119
+
120
+ // The saved data stands in for the document a host application reopens, so it seeds the application
121
+ // rather than being written in after the form is up.
122
+ const tmpInitialAppData = tmpAtRest
123
+ ? nestSavedData(cloneData(tmpConfig.InitialAppData || {}), tmpConfig.SavedData, tmpConfig.MarshalDestination)
124
+ : cloneData(tmpConfig.InitialAppData || {});
125
+ await pContext.boot({ HostManifest: tmpConfig.HostManifest, MarshalDestination: tmpConfig.MarshalDestination, InitialAppData: tmpInitialAppData });
126
+
127
+ const tmpParser = pContext.pict.instantiateServiceProviderIfNotExists('ExpressionParser');
128
+ // Each salt can carry a manifest of its own, so a form holding several different tests round trips the
129
+ // same way one holding two copies of a single test does.
130
+ const tmpManifests = {};
131
+ const tmpUndeclared = [];
132
+ for (let i = 0; i < tmpSalts.length; i++)
133
+ {
134
+ const tmpSalt = tmpSalts[i];
135
+ let tmpSaltManifest = Array.isArray(tmpConfig.Manifests) ? tmpConfig.Manifests[i] : tmpConfig.Manifest;
136
+ const tmpUndeclaredForSalt = libDifferential.findUndeclaredSolverTargets(tmpParser, tmpSaltManifest);
137
+ for (const tmpTarget of tmpUndeclaredForSalt)
138
+ {
139
+ if (!tmpUndeclared.includes(tmpTarget))
140
+ {
141
+ tmpUndeclared.push(tmpTarget);
142
+ }
143
+ }
144
+ if (tmpConfig.DeclareUndeclaredSolverTargets)
145
+ {
146
+ tmpSaltManifest = cloneData(tmpSaltManifest);
147
+ for (const tmpTarget of tmpUndeclaredForSalt)
148
+ {
149
+ tmpSaltManifest.Descriptors[tmpTarget] = { Name: tmpTarget, Hash: tmpTarget, DataAddress: tmpTarget };
150
+ }
151
+ }
152
+ tmpManifests[tmpSalt] = tmpSaltManifest;
153
+ }
154
+ pContext.info.UndeclaredSolverTargets = tmpUndeclared;
155
+
156
+ const tmpMarshal = pContext.marshalDestinationObject;
157
+ let tmpFilledAddresses = 0;
158
+ const tmpCopies = {};
159
+ for (const tmpSalt of tmpSalts)
160
+ {
161
+ if (!tmpAtRest)
162
+ {
163
+ const tmpFill = libDifferential.buildFill(tmpManifests[tmpSalt], tmpConfig.Fill || {});
164
+ tmpFilledAddresses += Object.keys(tmpFill).length;
165
+ tmpMarshal[tmpSalt] = tmpMarshal[tmpSalt] || {};
166
+ for (const [ tmpAddress, tmpValue ] of Object.entries(tmpFill))
167
+ {
168
+ pContext.pict.manifest.setValueAtAddress(tmpMarshal[tmpSalt], tmpAddress, cloneData(tmpValue));
169
+ }
170
+ }
171
+ const tmpInjection = await pContext.inject(tmpManifests[tmpSalt], tmpSalt);
172
+ tmpCopies[tmpSalt] = tmpInjection.Salted;
173
+ }
174
+ pContext.info.FilledAddresses = tmpFilledAddresses;
175
+ await pContext.solve();
176
+ await pContext.solve();
177
+
178
+ const tmpSnapshot = { Copies: {} };
179
+ for (const tmpSalt of tmpSalts)
180
+ {
181
+ tmpSnapshot.Copies[tmpSalt] = snapshotCopy(pContext, tmpManifests[tmpSalt], tmpCopies[tmpSalt], tmpSalt);
182
+ }
183
+ pContext.snapshots.Reconstitution = tmpSnapshot;
184
+ if (!tmpAtRest)
185
+ {
186
+ // What the host would persist, and what the rest phase boots from.
187
+ pContext.snapshots.SavedData = cloneData(tmpMarshal);
188
+ }
189
+ }
190
+
191
+ module.exports = { run: run, snapshotCopy: snapshotCopy, nestSavedData: nestSavedData };