@mark1russell7/layout-contract 0.5.4 → 0.5.6
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.d.ts +36 -5
- package/build/index.d.ts.map +1 -1
- package/build/index.js +99 -12
- package/build/index.js.map +1 -1
- package/package.json +1 -1
- package/src/hash.ts +74 -5
- package/src/strategy-catalog.ts +20 -7
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package",
|
|
3
3
|
"name": "@mark1russell7/layout-contract",
|
|
4
|
-
"version": "0.5.
|
|
4
|
+
"version": "0.5.6",
|
|
5
5
|
"description": "The shared contract of the packing and highways layout engines: the input and record formats, the turn rule, margins, tolerances and hard rules.",
|
|
6
6
|
"keywords": [
|
|
7
7
|
"layout",
|
package/src/hash.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { canonicalInput, type LayoutInput } from "./input.ts";
|
|
2
|
+
import type { PackOutput } from "./output.ts";
|
|
2
3
|
import { RECORD_EPS } from "./tolerance.ts";
|
|
3
4
|
import { utf8Write } from "./utf8.ts";
|
|
4
5
|
|
|
@@ -88,6 +89,11 @@ export interface HashOptions {
|
|
|
88
89
|
* The value `0` keeps the exact numbers. A negative value or a value that is not finite causes a `RangeError`.
|
|
89
90
|
*/
|
|
90
91
|
readonly grid?: number;
|
|
92
|
+
/**
|
|
93
|
+
* The names of the fields that the hash does not read, at each depth. Use it for report fields, for example a trace or a time.
|
|
94
|
+
* A field with one of these names is out of the form in each object of the value, also in an object in a list.
|
|
95
|
+
*/
|
|
96
|
+
readonly skip?: readonly string[];
|
|
91
97
|
}
|
|
92
98
|
|
|
93
99
|
/** This function gives the factor of a grid: `1 / grid`, or `undefined` for the exact numbers. */
|
|
@@ -101,7 +107,7 @@ function gridFactor(options: HashOptions): number | undefined {
|
|
|
101
107
|
* This function gives a copy of a value with each number on the grid. The value `-0` becomes `0`.
|
|
102
108
|
* It throws a `RangeError` for a number that is not finite.
|
|
103
109
|
*/
|
|
104
|
-
function onGrid(value: unknown, path: string, k: number | undefined): unknown {
|
|
110
|
+
function onGrid(value: unknown, path: string, k: number | undefined, skip: ReadonlySet<string>): unknown {
|
|
105
111
|
if (typeof value === "number") {
|
|
106
112
|
if (!Number.isFinite(value)) throw new RangeError(`The value has the number ${value} at ${path}. JSON has no form for it.`);
|
|
107
113
|
if (k === undefined) return value;
|
|
@@ -110,10 +116,10 @@ function onGrid(value: unknown, path: string, k: number | undefined): unknown {
|
|
|
110
116
|
return r === 0 ? 0 : r;
|
|
111
117
|
}
|
|
112
118
|
if (value === null || typeof value !== "object") return value;
|
|
113
|
-
if (Array.isArray(value)) return value.map((v: unknown, i) => onGrid(v, `${path}[${i}]`, k));
|
|
119
|
+
if (Array.isArray(value)) return value.map((v: unknown, i) => onGrid(v, `${path}[${i}]`, k, skip));
|
|
114
120
|
const o = value as Record<string, unknown>;
|
|
115
121
|
const out: Record<string, unknown> = {};
|
|
116
|
-
for (const key of Object.keys(o)) out[key] = onGrid(o[key], `${path}.${key}`, k);
|
|
122
|
+
for (const key of Object.keys(o)) if (!skip.has(key)) out[key] = onGrid(o[key], `${path}.${key}`, k, skip);
|
|
117
123
|
return out;
|
|
118
124
|
}
|
|
119
125
|
|
|
@@ -121,13 +127,76 @@ function onGrid(value: unknown, path: string, k: number | undefined): unknown {
|
|
|
121
127
|
* This function gives the hash of an output: the first 16 hex characters of the SHA-256 of its canonical form.
|
|
122
128
|
* Before the canonical form, each number goes to the nearest point of the grid, and `-0` becomes `0`.
|
|
123
129
|
* With the default grid, the rounding is `round3` of `packing`: `Math.round(x * 1000) / 1000`.
|
|
124
|
-
* The function throws a `RangeError` for `NaN` and for an infinite number.
|
|
130
|
+
* The function throws a `RangeError` for `NaN` and for an infinite number. The fields of `options.skip` are out of the form.
|
|
125
131
|
*
|
|
126
132
|
* The grid can split two outputs. Two numbers near a rounding boundary can go to two different points.
|
|
127
133
|
* The grid can also merge two outputs whose numbers go to the same points. This merge is intentional: it removes the noise of floating-point numbers.
|
|
128
134
|
*/
|
|
129
135
|
export function outputHash(value: unknown, options: HashOptions = {}): string {
|
|
130
|
-
return sha256Hex(canonicalJson(onGrid(value, "$", gridFactor(options)))).slice(0, 16);
|
|
136
|
+
return sha256Hex(canonicalJson(onGrid(value, "$", gridFactor(options), new Set(options.skip ?? [])))).slice(0, 16);
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/** This function throws a `RangeError` when a list of the output has an id two times. A packer with this output has a bug. */
|
|
140
|
+
function uniqueIds(list: string, ids: readonly string[]): void {
|
|
141
|
+
const seen = new Set<string>();
|
|
142
|
+
for (const id of ids) {
|
|
143
|
+
if (seen.has(id)) throw new RangeError(`The list ${list} of the output has the id "${id}" two times.`);
|
|
144
|
+
seen.add(id);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** The order of two ids by their UTF-16 code units. It does not change with the locale. */
|
|
149
|
+
function byId(a: { readonly id: string }, b: { readonly id: string }): number {
|
|
150
|
+
return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* This function gives the normal form of the output of a packer, for a fingerprint.
|
|
155
|
+
* The form has the placements, the overflow, the size and the moved obstacles. It does not have the trace.
|
|
156
|
+
* The placements, the moved obstacles and the overflow are in the order of their ids. A placement without `turn` gets `turn: 0`.
|
|
157
|
+
* Thus two packers with the same result in a different order have the same form.
|
|
158
|
+
* The function throws a `RangeError` when `placements`, `overflow` or `moved` has an id two times.
|
|
159
|
+
*/
|
|
160
|
+
export function packOutputForm(output: PackOutput): unknown {
|
|
161
|
+
uniqueIds("placements", output.placements.map((p) => p.id));
|
|
162
|
+
uniqueIds("overflow", output.overflow);
|
|
163
|
+
uniqueIds("moved", output.moved.map((m) => m.id));
|
|
164
|
+
return {
|
|
165
|
+
placements: output.placements.map((p) => ({ id: p.id, x: p.x, y: p.y, turn: p.turn ?? 0 })).sort(byId),
|
|
166
|
+
overflow: [...output.overflow].sort(),
|
|
167
|
+
size: { w: output.size.w, h: output.size.h },
|
|
168
|
+
moved: output.moved.map((m) => ({ id: m.id, x: m.x, y: m.y })).sort(byId),
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** The hash of a probe that the strategy refused or does not support. It has no reason text, so a new text of a refusal does not change a fingerprint. */
|
|
173
|
+
export const REFUSED_PROBE = "refused";
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* This function gives the hash of one probe of a strategy. It calls `run` and gives `outputHash` of its result, with exact numbers by default.
|
|
177
|
+
* When `run` throws an error that `refused` accepts, the function gives `REFUSED_PROBE`. It throws each other error again.
|
|
178
|
+
* The option `grid` of `options` puts the numbers on a grid. Its default here is `0`, so a change in a number changes the hash.
|
|
179
|
+
*/
|
|
180
|
+
export function probeHash(run: () => unknown, refused: (error: unknown) => boolean, options: HashOptions = {}): string {
|
|
181
|
+
let value: unknown;
|
|
182
|
+
try {
|
|
183
|
+
value = run();
|
|
184
|
+
} catch (error) {
|
|
185
|
+
if (refused(error)) return REFUSED_PROBE;
|
|
186
|
+
throw error;
|
|
187
|
+
}
|
|
188
|
+
return outputHash(value, { ...options, grid: options.grid ?? 0 });
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
/**
|
|
192
|
+
* This function gives the fingerprint of the outputs of one strategy: one hash of the hashes of its probes.
|
|
193
|
+
* The key of `hashes` is the id of a probe, and its value is the hash of the probe, from `probeHash`.
|
|
194
|
+
* The order of the keys does not change the fingerprint. A new probe, a probe less or a changed hash changes it.
|
|
195
|
+
* The function throws a `RangeError` when there is no probe.
|
|
196
|
+
*/
|
|
197
|
+
export function fingerprintOf(hashes: Readonly<Record<string, string>>): string {
|
|
198
|
+
if (Object.keys(hashes).length === 0) throw new RangeError("A fingerprint needs one probe or more.");
|
|
199
|
+
return sha256Hex(canonicalJson(hashes)).slice(0, 16);
|
|
131
200
|
}
|
|
132
201
|
|
|
133
202
|
/**
|
package/src/strategy-catalog.ts
CHANGED
|
@@ -5,10 +5,13 @@ import { type AnyOption, declarationIssues, type ListItem, type NoDefaultReason,
|
|
|
5
5
|
import type { ParamValue, StrategySpace } from "./strategy-space.ts";
|
|
6
6
|
|
|
7
7
|
/** The newest schema of a strategy catalog. A new field is a new version of the schema. */
|
|
8
|
-
export const STRATEGY_CATALOG_SCHEMA = "strategy-catalog/
|
|
8
|
+
export const STRATEGY_CATALOG_SCHEMA = "strategy-catalog/3";
|
|
9
9
|
|
|
10
|
-
/** The schemas that `parseStrategyCatalog` reads, oldest first. Schema 2 adds the field `output` of an entry
|
|
11
|
-
export const STRATEGY_CATALOG_SCHEMAS: readonly ["strategy-catalog/1", "strategy-catalog/2"] = ["strategy-catalog/1", STRATEGY_CATALOG_SCHEMA];
|
|
10
|
+
/** The schemas that `parseStrategyCatalog` reads, oldest first. Schema 2 adds the field `output` of an entry, and schema 3 adds the field `fingerprint`. */
|
|
11
|
+
export const STRATEGY_CATALOG_SCHEMAS: readonly ["strategy-catalog/1", "strategy-catalog/2", "strategy-catalog/3"] = ["strategy-catalog/1", "strategy-catalog/2", STRATEGY_CATALOG_SCHEMA];
|
|
12
|
+
|
|
13
|
+
/** The form of the field `fingerprint` of an entry: the 16 lowercase hex digits that `fingerprintOf` gives. */
|
|
14
|
+
const FINGERPRINT = /^[0-9a-f]{16}$/u;
|
|
12
15
|
|
|
13
16
|
/** The name of one schema of a strategy catalog. */
|
|
14
17
|
export type StrategyCatalogSchema = (typeof STRATEGY_CATALOG_SCHEMAS)[number];
|
|
@@ -113,6 +116,8 @@ export interface CatalogEntry {
|
|
|
113
116
|
readonly baseline?: true;
|
|
114
117
|
/** The reads of the output of the strategy. A file with this field has the schema 2. */
|
|
115
118
|
readonly output?: readonly OutputRow[];
|
|
119
|
+
/** The fingerprint of the outputs of the strategy on the probes of its engine, from `fingerprintOf`. A file with this field has the schema 3. */
|
|
120
|
+
readonly fingerprint?: string;
|
|
116
121
|
/** The declarations of the options, in the order of a form. */
|
|
117
122
|
readonly options: Readonly<Record<string, AnyOption>>;
|
|
118
123
|
}
|
|
@@ -210,7 +215,7 @@ const STRATEGY_KINDS: readonly string[] = ["single", "composite", "shape"];
|
|
|
210
215
|
const NO_DEFAULT_REASONS: readonly NoDefaultReason[] = ["unset", "required", "derived", "function"];
|
|
211
216
|
const SCALES: readonly OptionScale[] = ["linear", "log"];
|
|
212
217
|
const TOP_FIELDS: readonly string[] = ["schema", "engine", "version", "strategies"];
|
|
213
|
-
const ENTRY_FIELDS: readonly string[] = ["key", "id", "step", "family", "kind", "describe", "supports", "limits", "deterministic", "determinismNote", "optIn", "baseline", "output", "options"];
|
|
218
|
+
const ENTRY_FIELDS: readonly string[] = ["key", "id", "step", "family", "kind", "describe", "supports", "limits", "deterministic", "determinismNote", "optIn", "baseline", "output", "fingerprint", "options"];
|
|
214
219
|
const COMMON_FIELDS: readonly string[] = ["type", "describe", "default", "noDefault", "when"];
|
|
215
220
|
const NUMBER_FIELDS: readonly string[] = [...COMMON_FIELDS, "min", "max", "step", "scale", "special", "marks", "values"];
|
|
216
221
|
const ENUM_FIELDS: readonly string[] = [...COMMON_FIELDS, "values", "custom"];
|
|
@@ -479,7 +484,7 @@ function checkEvidence(at: string, property: unknown, rowClass: unknown, raw: un
|
|
|
479
484
|
|
|
480
485
|
/** This function adds the faults of the field `output` of one entry. */
|
|
481
486
|
function checkOutput(at: string, raw: unknown, schema: unknown, faults: string[]): void {
|
|
482
|
-
if (schema === STRATEGY_CATALOG_SCHEMAS[0]) faults.push(`${at}: the field "output" needs the schema ${
|
|
487
|
+
if (schema === STRATEGY_CATALOG_SCHEMAS[0]) faults.push(`${at}: the field "output" needs the schema ${STRATEGY_CATALOG_SCHEMAS[1]} or a newer schema.`);
|
|
483
488
|
if (!Array.isArray(raw) || raw.length === 0) {
|
|
484
489
|
faults.push(`${at}: "output" is not a list with rows.`);
|
|
485
490
|
return;
|
|
@@ -519,6 +524,10 @@ function readEntry(at: string, raw: unknown, schema: unknown, faults: string[]):
|
|
|
519
524
|
if (!isFields(raw["supports"]) || !Object.values(raw["supports"]).every(isTextList)) faults.push(`${at}: "supports" is not a record of text lists.`);
|
|
520
525
|
checkLimits(at, raw["limits"], faults);
|
|
521
526
|
if (raw["output"] !== undefined) checkOutput(at, raw["output"], schema, faults);
|
|
527
|
+
if (raw["fingerprint"] !== undefined) {
|
|
528
|
+
if (schema !== STRATEGY_CATALOG_SCHEMAS[2]) faults.push(`${at}: the field "fingerprint" needs the schema ${STRATEGY_CATALOG_SCHEMAS[2]}.`);
|
|
529
|
+
if (!isText(raw["fingerprint"]) || !FINGERPRINT.test(raw["fingerprint"])) faults.push(`${at}: "fingerprint" is not 16 lowercase hex digits.`);
|
|
530
|
+
}
|
|
522
531
|
if (isText(raw["id"]) && raw["key"] !== catalogKey(raw["id"], raw["step"] as string | undefined)) faults.push(`${at}: the key does not follow from "step" and "id".`);
|
|
523
532
|
if (!isFields(raw["options"])) {
|
|
524
533
|
faults.push(`${at}: "options" is not an object.`);
|
|
@@ -552,6 +561,7 @@ function readEntry(at: string, raw: unknown, schema: unknown, faults: string[]):
|
|
|
552
561
|
optIn: raw["optIn"] as boolean,
|
|
553
562
|
...(raw["baseline"] === true ? { baseline: true as const } : {}),
|
|
554
563
|
...(raw["output"] === undefined ? {} : { output: raw["output"] as readonly OutputRow[] }),
|
|
564
|
+
...(raw["fingerprint"] === undefined ? {} : { fingerprint: raw["fingerprint"] as string }),
|
|
555
565
|
options,
|
|
556
566
|
};
|
|
557
567
|
}
|
|
@@ -726,6 +736,7 @@ function writeEntry(e: CatalogEntry): Fields {
|
|
|
726
736
|
optIn: e.optIn,
|
|
727
737
|
...(e.baseline === true ? { baseline: true } : {}),
|
|
728
738
|
...(e.output === undefined ? {} : { output: e.output.map(writeRow) }),
|
|
739
|
+
...(e.fingerprint === undefined ? {} : { fingerprint: e.fingerprint }),
|
|
729
740
|
options,
|
|
730
741
|
};
|
|
731
742
|
}
|
|
@@ -741,12 +752,14 @@ function unsafeValues(v: unknown, at: string): string[] {
|
|
|
741
752
|
|
|
742
753
|
/**
|
|
743
754
|
* This function gives the text of the catalog file, sorted by key. The same source and version give the same bytes.
|
|
744
|
-
* The file has the oldest schema that holds it
|
|
755
|
+
* The file has the oldest schema that holds it. A catalog with no `output` and no `fingerprint` stays valid for a reader of the schema 1.
|
|
756
|
+
* A catalog with no `fingerprint` stays valid for a reader of the schema 2.
|
|
745
757
|
* The caller gives the version from `package.json`. The function throws an error if the file breaks a rule of the format.
|
|
746
758
|
*/
|
|
747
759
|
export function writeStrategyCatalog(source: StrategyCatalogSource, version: string): string {
|
|
748
760
|
const strategies = [...source.strategies].sort((a, b) => (a.key < b.key ? -1 : a.key > b.key ? 1 : 0)).map(writeEntry);
|
|
749
|
-
const
|
|
761
|
+
const has = (field: "output" | "fingerprint"): boolean => source.strategies.some((e) => e[field] !== undefined);
|
|
762
|
+
const schema = has("fingerprint") ? STRATEGY_CATALOG_SCHEMAS[2] : has("output") ? STRATEGY_CATALOG_SCHEMAS[1] : STRATEGY_CATALOG_SCHEMAS[0];
|
|
750
763
|
const doc = { schema, engine: source.engine, version, strategies };
|
|
751
764
|
const unsafe = unsafeValues(doc, "catalog");
|
|
752
765
|
if (unsafe.length > 0) throw new Error(`The catalog of ${source.engine} has values that JSON cannot hold: ${unsafe.join(" ")}`);
|