@earnestjs/model 0.1.0 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/search.js CHANGED
@@ -1,6 +1,7 @@
1
- import { NullFault, DivisionFault, RemainderFault, isJsonList, keyOf, toJson, } from "./values.js";
2
- /** The state limit `explore` uses when it is given none, the same as `earnest verify`. */
3
- export const DEFAULT_MAX_STATES = 5_000_000;
1
+ import { breadthFirst, stateLimit, trailTo, } from "./breadth.js";
2
+ import { rowsOf } from "./declarations.js";
3
+ import { hunter } from "./runs.js";
4
+ import { NullFault, DivisionFault, RemainderFault, frozen, isJsonList, keyOf, toJson, } from "./values.js";
4
5
  /**
5
6
  * Gives the function that names a part of a model: the name it is exported under in `exports`,
6
7
  * or `fallback`, its sentence, when it is not exported there.
@@ -16,8 +17,7 @@ export const namer = (exports = {}) => {
16
17
  };
17
18
  const NULL_READ = "reads a value that is null";
18
19
  const OVERFLOW = "computes a number too large to hold";
19
- const REMAINDER = "takes a remainder with a negative number or a divisor below 1";
20
- const DIVISION = "takes a division with a negative number or a divisor below 1";
20
+ const BY_ZERO = "takes a division or a remainder by zero";
21
21
  const WRONG_KIND = "uses a value of the wrong kind";
22
22
  /**
23
23
  * Runs part of a model and turns a fault into a value: reading a field of `null`, or using a
@@ -28,11 +28,8 @@ export const attempt = (run) => {
28
28
  return { fault: null, value: run() };
29
29
  }
30
30
  catch (thrown) {
31
- if (thrown instanceof RemainderFault) {
32
- return { fault: REMAINDER, value: null };
33
- }
34
- if (thrown instanceof DivisionFault) {
35
- return { fault: DIVISION, value: null };
31
+ if (thrown instanceof RemainderFault || thrown instanceof DivisionFault) {
32
+ return { fault: BY_ZERO, value: null };
36
33
  }
37
34
  if (thrown instanceof NullFault) {
38
35
  return { fault: NULL_READ, value: null };
@@ -46,7 +43,7 @@ export const attempt = (run) => {
46
43
  const numberFault = (json) => {
47
44
  if (typeof json === "number") {
48
45
  if (Number.isNaN(json)) {
49
- return REMAINDER;
46
+ return BY_ZERO;
50
47
  }
51
48
  return Math.abs(json) > Number.MAX_SAFE_INTEGER ? OVERFLOW : null;
52
49
  }
@@ -56,12 +53,6 @@ const numberFault = (json) => {
56
53
  const inside = isJsonList(json) ? json : Object.values(json);
57
54
  return inside.map(numberFault).find((fault) => fault !== null) ?? null;
58
55
  };
59
- const stateLimit = (maxStates) => {
60
- if (!Number.isInteger(maxStates) || maxStates < 0) {
61
- throw new Error(`maxStates must be a whole number that is not negative, not ${maxStates}`);
62
- }
63
- return maxStates;
64
- };
65
56
  /**
66
57
  * Applies an action and gives the next state, or the fault that stops it. Besides the faults of
67
58
  * `attempt`, a next state that holds `NaN`, which `%` by zero gives, or a number too large for
@@ -76,68 +67,50 @@ export const nextState = (action, state, input) => {
76
67
  return fault === null ? tried : { fault, value: null };
77
68
  };
78
69
  /** Every input an action is tried with, in the checker's order: the first input varies fastest. */
79
- export const inputsOf = (action) => action.inputs.reduceRight((rest, [name, declared]) => rest.flatMap((later) => declared.values().map((value) => ({ [name]: value, ...later }))), [{}]);
70
+ export const inputsOf = (action) => rowsOf(action.inputs);
71
+ const STAYS = "nothing changes the state from here, so the run can stay in it forever";
80
72
  class Search {
81
73
  #fields;
82
74
  #parts;
83
75
  #inputs;
84
76
  #name;
85
- #maxStates;
86
- #seen = new Set();
87
77
  #firstBroken = new Map();
88
78
  #unjudged = new Set();
89
79
  #stuck = null;
90
80
  #outside = null;
91
81
  #trouble = null;
92
- #reason = null;
93
82
  #isCutShort = false;
94
- constructor(fields, parts, options) {
83
+ #starts;
84
+ #maxStates;
85
+ #seenMoves = [];
86
+ #keepsMoves;
87
+ constructor(fields, parts, options, starts) {
95
88
  this.#fields = fields;
96
- this.#parts = parts;
89
+ this.#parts = {
90
+ ...parts,
91
+ witnesses: (parts.witnesses ?? []).filter((witness) => witness.setup === options.setup),
92
+ };
97
93
  this.#inputs = new Map(parts.actions.map((action) => [action, inputsOf(action)]));
98
94
  this.#name = namer(options.exports);
99
- this.#maxStates = stateLimit(options.maxStates ?? DEFAULT_MAX_STATES);
100
- }
101
- run(starts) {
102
- const waiting = [];
103
- for (const start of starts) {
104
- this.#visit(start, null, waiting);
105
- }
106
- let searched = 0;
107
- for (const visited of waiting) {
108
- if (this.#reason !== null) {
109
- break;
110
- }
111
- searched += 1;
112
- const expanded = this.#expand(visited.row);
113
- this.#record(visited, expanded);
114
- for (const successor of expanded.successors) {
115
- const parent = { from: visited, action: successor.action, input: successor.input };
116
- if (!this.#visit(successor.next, parent, waiting)) {
117
- break;
118
- }
119
- }
120
- }
121
- for (const counted of waiting.slice(searched)) {
122
- this.#record(counted, this.#judge(counted.row));
123
- }
124
- return this.#outcome();
95
+ this.#starts = starts;
96
+ this.#maxStates = stateLimit(options.maxStates);
97
+ this.#keepsMoves = (parts.eventually ?? []).length > 0;
125
98
  }
126
- #keyOf(row) {
99
+ key(row) {
127
100
  return this.#fields.map(([name]) => keyOf(row[name])).join(";");
128
101
  }
129
- #visit(row, parent, waiting) {
130
- const key = this.#keyOf(row);
131
- if (this.#seen.has(key)) {
132
- return true;
133
- }
134
- if (this.#seen.size >= this.#maxStates) {
135
- this.#reason = `state limit of ${this.#maxStates}`;
136
- return false;
102
+ expand(at) {
103
+ const expanded = this.#expand(at.state);
104
+ this.#record(at, expanded);
105
+ if (this.#keepsMoves) {
106
+ for (const { move, next } of expanded.successors) {
107
+ this.#seenMoves.push({ from: at, taken: move, next: this.key(next) });
108
+ }
137
109
  }
138
- this.#seen.add(key);
139
- waiting.push({ row, key, parent });
140
- return true;
110
+ return expanded.successors;
111
+ }
112
+ judge(at) {
113
+ this.#record(at, this.#judge(at.state));
141
114
  }
142
115
  #judge(state) {
143
116
  const outside = this.#fields.find(([name, declared]) => !declared.has(state[name]));
@@ -210,7 +183,7 @@ class Search {
210
183
  found.isEnabled = true;
211
184
  const next = nextState(action, state, input);
212
185
  if (next.fault === null) {
213
- found.successors.push({ action, input, next: next.value });
186
+ found.successors.push({ move: { action, input }, next: next.value });
214
187
  }
215
188
  else {
216
189
  found.trouble ??= `the change of the action \`${id}\` ${next.fault}`;
@@ -242,12 +215,11 @@ class Search {
242
215
  #named(row) {
243
216
  return this.#fields.map(([name]) => ({ name, value: toJson(row[name]) }));
244
217
  }
245
- #step(parent, after) {
246
- const before = parent.from.row;
218
+ #step({ action, input }, before, after) {
247
219
  return {
248
- action: this.#name(parent.action.part, parent.action.sentence),
249
- label: parent.action.sentence,
250
- input: parent.action.inputs.map(([name]) => ({ name, value: toJson(parent.input[name]) })),
220
+ action: this.#name(action.part, action.sentence),
221
+ label: action.sentence,
222
+ input: action.inputs.map(([name]) => ({ name, value: toJson(input[name]) })),
251
223
  changes: this.#fields
252
224
  .filter(([name]) => keyOf(before[name]) !== keyOf(after[name]))
253
225
  .map(([name]) => ({
@@ -259,13 +231,158 @@ class Search {
259
231
  };
260
232
  }
261
233
  #pathTo(target) {
234
+ const { start, steps } = trailTo(target);
235
+ return {
236
+ start: this.#named(start),
237
+ steps: steps.map(({ move, state }, index) => this.#step(move, steps[index - 1]?.state ?? start, state)),
238
+ };
239
+ }
240
+ #kept(visits) {
241
+ const byKey = new Map(visits.map((visit, index) => [this.key(visit.state), index]));
242
+ const byVisit = new Map(visits.map((visit, index) => [visit, index]));
243
+ const positions = new Map(this.#parts.actions.map((action, position) => [action, position]));
244
+ const kept = new Map();
245
+ for (const { from: visit, taken, next } of this.#seenMoves) {
246
+ const from = byVisit.get(visit);
247
+ const to = byKey.get(next);
248
+ const action = positions.get(taken.action);
249
+ if (from === undefined || to === undefined || action === undefined || from === to) {
250
+ continue;
251
+ }
252
+ const edge = `${from},${to},${action}`;
253
+ if (!kept.has(edge)) {
254
+ kept.set(edge, { from, to, action, taken });
255
+ }
256
+ }
257
+ return [...kept.values()].sort((one, other) => one.from - other.from || one.to - other.to || one.action - other.action);
258
+ }
259
+ #lassoPath(lasso, visits, edges) {
260
+ const rowOf = (state) => state === undefined ? {} : (visits[state]?.state ?? {});
261
+ const steps = [];
262
+ for (const [position, to] of lasso.states.entries()) {
263
+ const from = lasso.states[position - 1];
264
+ const only = lasso.actions[position] ?? null;
265
+ const edge = edges.find((kept) => kept.from === from && kept.to === to && (only === null || kept.action === only));
266
+ if (from !== undefined && edge !== undefined) {
267
+ steps.push(this.#step(edge.taken, rowOf(from), rowOf(to)));
268
+ }
269
+ }
270
+ return { start: this.#named(rowOf(lasso.states[0])), steps };
271
+ }
272
+ #eventually({ visits, reason }) {
273
+ const rules = this.#parts.eventually ?? [];
274
+ const unknown = (rule) => ({
275
+ id: this.#name(rule.part, rule.says),
276
+ says: rule.says,
277
+ verdict: "unknown",
278
+ path: null,
279
+ kind: "eventually",
280
+ });
281
+ if (rules.length === 0 || reason !== null || this.#isCutShort) {
282
+ return rules.map(unknown);
283
+ }
284
+ const edges = this.#kept(visits);
285
+ const byVisit = new Map(visits.map((visit, index) => [visit, index]));
286
+ const parents = visits.map((visit) => visit.parent === null ? null : (byVisit.get(visit.parent.from) ?? null));
287
+ const depth = [];
288
+ for (const parent of parents) {
289
+ depth.push(parent === null ? 0 : (depth[parent] ?? 0) + 1);
290
+ }
291
+ const fair = this.#parts.actions.flatMap((action, position) => action.fair === true ? [position] : []);
292
+ const hunt = hunter({ states: visits.length, edges, fair, parents, depth });
293
+ return rules.map((rule) => {
294
+ const startsHere = [];
295
+ const reached = [];
296
+ for (const visit of visits) {
297
+ const { after } = rule;
298
+ const starts = after === null ? null : attempt(() => after(visit.state));
299
+ const reaches = attempt(() => rule.reaches(visit.state));
300
+ const fault = starts?.fault ?? reaches.fault;
301
+ if (fault !== null) {
302
+ const id = this.#name(rule.part, rule.says);
303
+ this.#trouble ??= { at: visit, message: `the rule \`${id}\` ${fault} in this state` };
304
+ return unknown(rule);
305
+ }
306
+ startsHere.push(starts === null ? visit.parent === null : starts.value === true);
307
+ reached.push(reaches.value === true);
308
+ }
309
+ const lasso = hunt(startsHere, reached);
310
+ if (lasso === null) {
311
+ return { ...unknown(rule), verdict: "holds" };
312
+ }
313
+ if (lasso === "lost") {
314
+ return unknown(rule);
315
+ }
316
+ const broken = {
317
+ ...unknown(rule),
318
+ verdict: "broken",
319
+ path: this.#lassoPath(lasso, visits, edges),
320
+ };
321
+ return lasso.repeatsFrom === null
322
+ ? { ...broken, reason: STAYS }
323
+ : {
324
+ ...broken,
325
+ reason: `steps ${lasso.repeatsFrom + 1} to ${lasso.states.length - 1} can repeat forever`,
326
+ repeatsFrom: lasso.repeatsFrom,
327
+ };
328
+ });
329
+ }
330
+ #play(witness, start) {
331
+ let state = start;
262
332
  const steps = [];
263
- let at = target;
264
- while (at.parent !== null) {
265
- steps.push(this.#step(at.parent, at.row));
266
- at = at.parent.from;
333
+ const broken = (reason) => ({
334
+ broken: true,
335
+ path: { start: this.#named(start), steps },
336
+ reason,
337
+ });
338
+ for (const [position, { action, input }] of witness.steps.entries()) {
339
+ const number = position + 1;
340
+ const id = this.#name(action.part, action.sentence);
341
+ const before = state;
342
+ const can = attempt(() => action.when(before, input));
343
+ if (can.fault !== null) {
344
+ return broken(`step ${number}: the condition of the action \`${id}\` ${can.fault} here`);
345
+ }
346
+ if (!can.value) {
347
+ return broken(`step ${number}, \`${id}\`, can't happen here`);
348
+ }
349
+ const next = nextState(action, before, input);
350
+ if (next.fault !== null) {
351
+ return broken(`step ${number}: the change of the action \`${id}\` ${next.fault} here`);
352
+ }
353
+ const after = next.value;
354
+ steps.push(this.#step({ action, input }, before, after));
355
+ state = after;
356
+ const outside = this.#fields.find(([name, declared]) => !declared.has(after[name]));
357
+ if (outside !== undefined) {
358
+ return broken(`step ${number}, \`${id}\`, takes the field \`${outside[0]}\` out of the values it declares`);
359
+ }
360
+ }
361
+ const last = state;
362
+ const expected = attempt(() => witness.expect(last));
363
+ if (expected.fault !== null) {
364
+ return broken(`what the witness expects ${expected.fault} here`);
365
+ }
366
+ return expected.value ? { broken: false } : broken("what the witness expects is false here");
367
+ }
368
+ #witness(witness) {
369
+ const result = { id: this.#name(witness.part, witness.says), says: witness.says };
370
+ for (const [position, start] of this.#starts.entries()) {
371
+ if (position >= this.#maxStates) {
372
+ return { ...result, verdict: "unknown", path: null, kind: "witness" };
373
+ }
374
+ const played = this.#play(witness, start);
375
+ if (played.broken) {
376
+ return {
377
+ ...result,
378
+ verdict: "broken",
379
+ path: played.path,
380
+ kind: "witness",
381
+ reason: played.reason,
382
+ };
383
+ }
267
384
  }
268
- return { start: this.#named(at.row), steps: steps.reverse() };
385
+ return { ...result, verdict: "holds", path: null, kind: "witness" };
269
386
  }
270
387
  #findings() {
271
388
  const findings = [];
@@ -292,10 +409,11 @@ class Search {
292
409
  }
293
410
  return findings;
294
411
  }
295
- #outcome() {
296
- const rules = this.#parts.rules.map((rule) => {
412
+ outcome(reach) {
413
+ const { visits, reason } = reach;
414
+ const always = this.#parts.rules.map((rule) => {
297
415
  const first = this.#firstBroken.get(rule);
298
- const isJudged = this.#reason === null && !this.#isCutShort && !this.#unjudged.has(rule);
416
+ const isJudged = reason === null && !this.#isCutShort && !this.#unjudged.has(rule);
299
417
  const unbroken = isJudged ? "holds" : "unknown";
300
418
  return {
301
419
  id: this.#name(rule.part, rule.says),
@@ -304,18 +422,47 @@ class Search {
304
422
  path: first === undefined ? null : this.#pathTo(first),
305
423
  };
306
424
  });
425
+ const eventually = this.#eventually(reach);
426
+ const witnesses = (this.#parts.witnesses ?? []).map((witness) => this.#witness(witness));
427
+ const rules = [...always, ...eventually, ...witnesses];
307
428
  const findings = this.#findings();
308
429
  const hasFailed = findings.length > 0 || rules.some((rule) => rule.verdict === "broken");
309
- const unfailed = this.#reason === null ? "pass" : "unfinished";
430
+ const unfailed = reason === null ? "pass" : "unfinished";
310
431
  return {
311
432
  status: hasFailed ? "fail" : unfailed,
312
- states: this.#seen.size,
433
+ states: visits.length,
313
434
  rules,
314
435
  findings,
315
- reason: this.#reason,
436
+ reason,
316
437
  };
317
438
  }
318
439
  }
440
+ /**
441
+ * Gives the start states of `model`, or of `setup`, a setup declared on it with `m.setup`: each
442
+ * start state of the model with the setup's fields put in, once each, in the model's order.
443
+ * `asker` names the function in the error thrown for a setup of another model.
444
+ */
445
+ export const startsOf = (model, setup, asker) => {
446
+ if (setup === undefined) {
447
+ return [...model.starts()];
448
+ }
449
+ const fields = Object.keys(model.fields);
450
+ const key = (row) => fields.map((name) => keyOf(row[name])).join(";");
451
+ const chosen = (model.runners().setups ?? []).find((each) => each.part === setup);
452
+ if (chosen === undefined) {
453
+ throw new Error(`${model.name}: the setup given to ${asker} is not one declared on this model`);
454
+ }
455
+ const seen = new Set();
456
+ return model
457
+ .starts()
458
+ .map((start) => frozen({ ...start, ...chosen.starts }))
459
+ .filter((start) => {
460
+ const found = key(start);
461
+ const isNew = !seen.has(found);
462
+ seen.add(found);
463
+ return isNew;
464
+ });
465
+ };
319
466
  /**
320
467
  * Searches every state a model can reach, breadth first, and gives the count of distinct
321
468
  * states, each rule's verdict with the shortest path to a state that breaks it, and the first
@@ -324,4 +471,14 @@ class Search {
324
471
  * `earnest verify`, so the two results can be compared. Pass the model file's exports as
325
472
  * `exports` to get the same ids.
326
473
  */
327
- export const explore = (model, options = {}) => new Search(Object.entries(model.fields), model.runners(), options).run(model.starts());
474
+ export const explore = (model, options = {}) => {
475
+ const maxStates = stateLimit(options.maxStates);
476
+ const fields = Object.entries(model.fields);
477
+ const parts = model.runners();
478
+ const key = (row) => fields.map(([name]) => keyOf(row[name])).join(";");
479
+ const search = (starts) => {
480
+ const found = new Search(fields, parts, options, starts);
481
+ return found.outcome(breadthFirst(starts, key, maxStates, found));
482
+ };
483
+ return search(startsOf(model, options.setup, "explore"));
484
+ };
package/dist/values.d.ts CHANGED
@@ -260,11 +260,11 @@ export declare const setOf: <const T>(...items: readonly T[]) => SetValue<T>;
260
260
  export declare const seqOf: <const T>(...items: readonly T[]) => SeqValue<T>;
261
261
  /** Writes a map value from `[key, value]` pairs: `m.mapOf(["a", 1], ["b", 2])`. */
262
262
  export declare const mapOf: <const K, const V>(...entries: readonly (readonly [K, V])[]) => MapValue<K, V>;
263
- /** Thrown by `rem` for a remainder the contract makes a fault; `explore` and `replay` report it. */
263
+ /** Thrown by `rem` for a divisor of zero; `explore` and `replay` report it as `earnest verify` does. */
264
264
  export declare class RemainderFault extends Error {
265
265
  constructor();
266
266
  }
267
- /** Thrown by `div` for a division the contract makes a fault; `explore` and `replay` report it. */
267
+ /** Thrown by `div` for a divisor of zero; `explore` and `replay` report it as `earnest verify` does. */
268
268
  export declare class DivisionFault extends Error {
269
269
  constructor();
270
270
  }
@@ -279,15 +279,18 @@ export declare class NullFault extends Error {
279
279
  */
280
280
  export declare const some: <T>(value: T | null) => T;
281
281
  /**
282
- * Writes the remainder of `a` divided by `b`: `m.rem(7, 3)` is 1. A negative `a` or a `b`
283
- * below 1 is a fault, as in `earnest verify`, because languages disagree on the result there.
284
- * Use it where JavaScript would use `%`, which a model file may not.
282
+ * Writes the remainder of `a` divided by `b`, JavaScript's `a % b`: `m.rem(7, 3)` is 1,
283
+ * `m.rem(-7, 2)` is -1 and `m.rem(7, -2)` is 1, with the sign of `a` as Rust's `%` has it. A
284
+ * zero result is 0, never -0. A `b` of zero is a fault, as in `earnest verify`, where JavaScript
285
+ * would go on with `NaN`, and so is a `NaN`. Use it where JavaScript would use `%`, which a model
286
+ * file may not.
285
287
  */
286
288
  export declare const rem: (a: number, b: number) => number;
287
289
  /**
288
- * Writes the whole number of times `b` goes into `a`: `m.div(7, 2)` is 3. A negative `a` or a
289
- * `b` below 1 is a fault, as in `earnest verify`, because languages disagree on the result
290
- * there and Rust panics on a divisor of zero. Use it where JavaScript would use `/`, which a
291
- * model file may not, since it gives a fraction.
290
+ * Writes the whole number of times `b` goes into `a`, `Math.trunc(a / b)`: `m.div(7, 2)` is 3,
291
+ * `m.div(-7, 2)` is -3 and `m.div(-7, -2)` is 3, as Rust's `/` on integers. It is exact for
292
+ * every safe integer, and a zero result is 0, never -0. A `b` of zero is a fault, as in
293
+ * `earnest verify` and as Rust panics, and so is a `NaN`. Use it where JavaScript would use
294
+ * `/`, which a model file may not, since it gives a fraction.
292
295
  */
293
296
  export declare const div: (a: number, b: number) => number;
package/dist/values.js CHANGED
@@ -627,17 +627,18 @@ export const setOf = (...items) => SetValue.of(items);
627
627
  export const seqOf = (...items) => SeqValue.of(items);
628
628
  /** Writes a map value from `[key, value]` pairs: `m.mapOf(["a", 1], ["b", 2])`. */
629
629
  export const mapOf = (...entries) => MapValue.of(entries);
630
- /** Thrown by `rem` for a remainder the contract makes a fault; `explore` and `replay` report it. */
630
+ const BY_ZERO = "takes a division or a remainder by zero";
631
+ /** Thrown by `rem` for a divisor of zero; `explore` and `replay` report it as `earnest verify` does. */
631
632
  export class RemainderFault extends Error {
632
633
  constructor() {
633
- super("takes a remainder with a negative number or a divisor below 1");
634
+ super(BY_ZERO);
634
635
  this.name = "RemainderFault";
635
636
  }
636
637
  }
637
- /** Thrown by `div` for a division the contract makes a fault; `explore` and `replay` report it. */
638
+ /** Thrown by `div` for a divisor of zero; `explore` and `replay` report it as `earnest verify` does. */
638
639
  export class DivisionFault extends Error {
639
640
  constructor() {
640
- super("takes a division with a negative number or a divisor below 1");
641
+ super(BY_ZERO);
641
642
  this.name = "DivisionFault";
642
643
  }
643
644
  }
@@ -659,26 +660,36 @@ export const some = (value) => {
659
660
  }
660
661
  return value;
661
662
  };
663
+ const numbers = (a, b) => {
664
+ if (Number.isNaN(a) || Number.isNaN(b)) {
665
+ throw new TypeError("m.div and m.rem take numbers, and NaN is not one");
666
+ }
667
+ };
662
668
  /**
663
- * Writes the remainder of `a` divided by `b`: `m.rem(7, 3)` is 1. A negative `a` or a `b`
664
- * below 1 is a fault, as in `earnest verify`, because languages disagree on the result there.
665
- * Use it where JavaScript would use `%`, which a model file may not.
669
+ * Writes the remainder of `a` divided by `b`, JavaScript's `a % b`: `m.rem(7, 3)` is 1,
670
+ * `m.rem(-7, 2)` is -1 and `m.rem(7, -2)` is 1, with the sign of `a` as Rust's `%` has it. A
671
+ * zero result is 0, never -0. A `b` of zero is a fault, as in `earnest verify`, where JavaScript
672
+ * would go on with `NaN`, and so is a `NaN`. Use it where JavaScript would use `%`, which a model
673
+ * file may not.
666
674
  */
667
675
  export const rem = (a, b) => {
668
- if (a < 0 || b < 1 || Number.isNaN(a) || Number.isNaN(b)) {
676
+ numbers(a, b);
677
+ if (b === 0) {
669
678
  throw new RemainderFault();
670
679
  }
671
- return a % b;
680
+ return (a % b) + 0;
672
681
  };
673
682
  /**
674
- * Writes the whole number of times `b` goes into `a`: `m.div(7, 2)` is 3. A negative `a` or a
675
- * `b` below 1 is a fault, as in `earnest verify`, because languages disagree on the result
676
- * there and Rust panics on a divisor of zero. Use it where JavaScript would use `/`, which a
677
- * model file may not, since it gives a fraction.
683
+ * Writes the whole number of times `b` goes into `a`, `Math.trunc(a / b)`: `m.div(7, 2)` is 3,
684
+ * `m.div(-7, 2)` is -3 and `m.div(-7, -2)` is 3, as Rust's `/` on integers. It is exact for
685
+ * every safe integer, and a zero result is 0, never -0. A `b` of zero is a fault, as in
686
+ * `earnest verify` and as Rust panics, and so is a `NaN`. Use it where JavaScript would use
687
+ * `/`, which a model file may not, since it gives a fraction.
678
688
  */
679
689
  export const div = (a, b) => {
680
- if (a < 0 || b < 1 || Number.isNaN(a) || Number.isNaN(b)) {
690
+ numbers(a, b);
691
+ if (b === 0) {
681
692
  throw new DivisionFault();
682
693
  }
683
- return (a - (a % b)) / b;
694
+ return Math.trunc(a / b) + 0;
684
695
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@earnestjs/model",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
4
4
  "description": "The TypeScript library that earnest models are written with",
5
5
  "homepage": "https://earnest.cpeaustriajc.dev",
6
6
  "license": "LGPL-3.0-or-later",
@@ -42,10 +42,10 @@
42
42
  "test": "vitest run"
43
43
  },
44
44
  "devDependencies": {
45
- "@types/node": "22.20.5",
46
- "oxfmt": "0.79.0",
47
- "tsrs": "7.1.0-beta.tsrs3",
48
- "vitest": "5.1.1"
45
+ "@types/node": "^26.6.6",
46
+ "oxfmt": "^0.79.0",
47
+ "tsrs": "^7.1.0-beta.tsrs4",
48
+ "vitest": "^5.1.1"
49
49
  },
50
50
  "engines": {
51
51
  "node": ">=22.18"