@dice-o-rolla/dice-core 0.1.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.
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,4 @@
1
+ Dice O Rolla
2
+ Copyright 2026 Dmitriy Pyankov
3
+
4
+ This product is licensed under the Apache License, Version 2.0.
package/README.md ADDED
@@ -0,0 +1,16 @@
1
+ # `@dice-o-rolla/dice-core`
2
+
3
+ Framework-neutral domain primitives for Dice O Rolla: notation parsing, roll results, lifecycle
4
+ events, limits, and random sources.
5
+
6
+ Most browser applications should install `@dice-o-rolla/dice-engine` instead. Use this package when
7
+ building a custom engine composition or consuming the domain model independently.
8
+
9
+ ```ts
10
+ import { parseNotation, SeededRandomSource } from '@dice-o-rolla/dice-core';
11
+
12
+ const expression = parseNotation('2d20 + 4');
13
+ const random = new SeededRandomSource(42);
14
+ ```
15
+
16
+ Licensed under Apache-2.0. See `LICENSE`, `NOTICE`, and `THIRD_PARTY_NOTICES.md` in the package.
@@ -0,0 +1,18 @@
1
+ # Third-party notices
2
+
3
+ ## 3DDiceRoller
4
+
5
+ The geometry model and physical dice behavior were informed by 3DDiceRoller by MajorVictory,
6
+ released under The Unlicense.
7
+
8
+ - Source: <https://github.com/MajorVictory/3DDiceRoller>
9
+ - License: <https://unlicense.org/>
10
+
11
+ ## Runtime dependencies
12
+
13
+ - Three.js is distributed under the MIT License: <https://github.com/mrdoob/three.js>.
14
+ - Rapier is distributed under the Apache License 2.0:
15
+ <https://github.com/dimforge/rapier.js>.
16
+
17
+ The UNLICENSED anvil-dice-engine project was used only for architectural comparison. No source code,
18
+ assets, sounds, shaders, or textures from that project are included in this distribution.
@@ -0,0 +1,28 @@
1
+ export declare const STANDARD_DIE_TYPES: readonly ['d4', 'd6', 'd8', 'd10', 'd12', 'd20', 'd100'];
2
+ export type DieType = (typeof STANDARD_DIE_TYPES)[number];
3
+ export interface DieDefinition {
4
+ readonly id: DieType;
5
+ readonly sides: number;
6
+ }
7
+ interface BaseDieResult {
8
+ readonly id: string;
9
+ readonly value: number;
10
+ }
11
+ export type DiceComponentRole = 'tens' | 'units';
12
+ export interface DiceComponentResult {
13
+ readonly groupId: string;
14
+ readonly groupType: 'd100' | 'd66';
15
+ readonly role: DiceComponentRole;
16
+ readonly faceValue: number;
17
+ }
18
+ export interface StandardDieResult extends BaseDieResult {
19
+ readonly type: Exclude<DieType, 'd100'>;
20
+ readonly component?: never;
21
+ }
22
+ export interface ComponentDieResult extends BaseDieResult {
23
+ readonly type: DieType;
24
+ readonly component: DiceComponentResult;
25
+ }
26
+ export type DieResult = StandardDieResult | ComponentDieResult;
27
+ export declare function isDieType(value: unknown): value is DieType;
28
+ export {};
@@ -0,0 +1,4 @@
1
+ export const STANDARD_DIE_TYPES = ['d4', 'd6', 'd8', 'd10', 'd12', 'd20', 'd100'];
2
+ export function isDieType(value) {
3
+ return typeof value === 'string' && STANDARD_DIE_TYPES.some((type) => type === value);
4
+ }
@@ -0,0 +1,12 @@
1
+ type EventMap = object;
2
+ type EventListener<Payload> = (payload: Payload) => void;
3
+ export declare class TypedEventEmitter<Events extends EventMap> {
4
+ #private;
5
+ on<Key extends keyof Events>(event: Key, listener: EventListener<Events[Key]>): () => void;
6
+ once<Key extends keyof Events>(event: Key, listener: EventListener<Events[Key]>): () => void;
7
+ off<Key extends keyof Events>(event: Key, listener: EventListener<Events[Key]>): void;
8
+ emit<Key extends keyof Events>(event: Key, payload: Events[Key]): readonly unknown[];
9
+ clear(event?: keyof Events): void;
10
+ listenerCount(event: keyof Events): number;
11
+ }
12
+ export {};
@@ -0,0 +1,72 @@
1
+ class EventChannel {
2
+ #listeners = new Set();
3
+ add(listener) {
4
+ this.#listeners.add(listener);
5
+ }
6
+ delete(listener) {
7
+ this.#listeners.delete(listener);
8
+ }
9
+ emit(payload) {
10
+ const errors = [];
11
+ for (const listener of Array.from(this.#listeners)) {
12
+ try {
13
+ listener(payload);
14
+ }
15
+ catch (error) {
16
+ errors.push(error);
17
+ }
18
+ }
19
+ return errors;
20
+ }
21
+ clear() {
22
+ this.#listeners.clear();
23
+ }
24
+ get size() {
25
+ return this.#listeners.size;
26
+ }
27
+ }
28
+ export class TypedEventEmitter {
29
+ #channels = {};
30
+ #allChannels = new Set();
31
+ on(event, listener) {
32
+ const channel = this.#getOrCreateChannel(event);
33
+ channel.add(listener);
34
+ return () => channel.delete(listener);
35
+ }
36
+ once(event, listener) {
37
+ const channel = this.#getOrCreateChannel(event);
38
+ const onceListener = (payload) => {
39
+ channel.delete(onceListener);
40
+ listener(payload);
41
+ };
42
+ channel.add(onceListener);
43
+ return () => channel.delete(onceListener);
44
+ }
45
+ off(event, listener) {
46
+ this.#channels[event]?.delete(listener);
47
+ }
48
+ emit(event, payload) {
49
+ return this.#channels[event]?.emit(payload) ?? [];
50
+ }
51
+ clear(event) {
52
+ if (event !== undefined) {
53
+ this.#channels[event]?.clear();
54
+ return;
55
+ }
56
+ for (const channel of this.#allChannels) {
57
+ channel.clear();
58
+ }
59
+ }
60
+ listenerCount(event) {
61
+ return this.#channels[event]?.size ?? 0;
62
+ }
63
+ #getOrCreateChannel(event) {
64
+ const existing = this.#channels[event];
65
+ if (existing !== undefined)
66
+ return existing;
67
+ const channel = new EventChannel();
68
+ this.#channels[event] = channel;
69
+ this.#allChannels.add(channel);
70
+ return channel;
71
+ }
72
+ }
@@ -0,0 +1,12 @@
1
+ export type { DiceComponentResult, DiceComponentRole, ComponentDieResult, DieDefinition, DieResult, DieType, StandardDieResult, } from './dice/types.js';
2
+ export { isDieType, STANDARD_DIE_TYPES } from './dice/types.js';
3
+ export { TypedEventEmitter } from './events/typed-event-emitter.js';
4
+ export type { QuaternionLike, Vector3Like } from './math/types.js';
5
+ export type { DiceExpression, ModifierExpression, PairedDiceExpression, PairedDiceType, RollExpression, RollNotation, } from './notation/ast.js';
6
+ export { NotationParseError } from './notation/errors.js';
7
+ export type { NotationParseErrorCode } from './notation/errors.js';
8
+ export { parseNotation } from './notation/parser.js';
9
+ export type { RandomSource } from './random/random-source.js';
10
+ export { cryptoRandomSource, mathRandomSource, SeededRandomSource, } from './random/random-source.js';
11
+ export { createRollResult, getNotationModifier } from './roll/aggregation.js';
12
+ export type { CreateRollResultOptions, RollMode, RollResult, RollSession, RollState, } from './roll/types.js';
package/dist/index.js ADDED
@@ -0,0 +1,6 @@
1
+ export { isDieType, STANDARD_DIE_TYPES } from './dice/types.js';
2
+ export { TypedEventEmitter } from './events/typed-event-emitter.js';
3
+ export { NotationParseError } from './notation/errors.js';
4
+ export { parseNotation } from './notation/parser.js';
5
+ export { cryptoRandomSource, mathRandomSource, SeededRandomSource, } from './random/random-source.js';
6
+ export { createRollResult, getNotationModifier } from './roll/aggregation.js';
@@ -0,0 +1,8 @@
1
+ export interface Vector3Like {
2
+ readonly x: number;
3
+ readonly y: number;
4
+ readonly z: number;
5
+ }
6
+ export interface QuaternionLike extends Vector3Like {
7
+ readonly w: number;
8
+ }
File without changes
@@ -0,0 +1,21 @@
1
+ export interface DiceExpression {
2
+ readonly kind: 'dice';
3
+ readonly count: number;
4
+ readonly sides: number;
5
+ }
6
+ export type PairedDiceType = 'd100' | 'd66';
7
+ export interface PairedDiceExpression {
8
+ readonly kind: 'paired-dice';
9
+ readonly count: number;
10
+ readonly type: PairedDiceType;
11
+ }
12
+ export interface ModifierExpression {
13
+ readonly kind: 'modifier';
14
+ readonly value: number;
15
+ }
16
+ export type RollExpression = DiceExpression | PairedDiceExpression | ModifierExpression;
17
+ export interface RollNotation {
18
+ readonly kind: 'roll';
19
+ readonly source: string;
20
+ readonly expressions: readonly RollExpression[];
21
+ }
File without changes
@@ -0,0 +1,7 @@
1
+ export type NotationParseErrorCode = 'EMPTY_NOTATION' | 'EXPECTED_OPERATOR' | 'EXPECTED_TERM' | 'INVALID_COUNT' | 'INVALID_SIDES' | 'NEGATIVE_DICE' | 'UNSAFE_INTEGER' | 'UNEXPECTED_CHARACTER';
2
+ export declare class NotationParseError extends Error {
3
+ readonly code: NotationParseErrorCode;
4
+ readonly index: number;
5
+ readonly input: string;
6
+ constructor(code: NotationParseErrorCode, message: string, input: string, index: number);
7
+ }
@@ -0,0 +1,12 @@
1
+ export class NotationParseError extends Error {
2
+ code;
3
+ index;
4
+ input;
5
+ constructor(code, message, input, index) {
6
+ super(`${message} at index ${index}`);
7
+ this.name = 'NotationParseError';
8
+ this.code = code;
9
+ this.index = index;
10
+ this.input = input;
11
+ }
12
+ }
@@ -0,0 +1,2 @@
1
+ import type { RollNotation } from './ast.js';
2
+ export declare function parseNotation(input: string): RollNotation;
@@ -0,0 +1,150 @@
1
+ import { NotationParseError } from './errors.js';
2
+ class NotationParser {
3
+ #input;
4
+ #index = 0;
5
+ constructor(input) {
6
+ this.#input = input;
7
+ }
8
+ parse() {
9
+ this.#skipWhitespace();
10
+ if (this.#isAtEnd()) {
11
+ this.#fail('EMPTY_NOTATION', 'Notation must contain at least one term');
12
+ }
13
+ const expressions = [];
14
+ let first = true;
15
+ while (!this.#isAtEnd()) {
16
+ const sign = this.#readSign(first);
17
+ this.#skipWhitespace();
18
+ if (this.#isAtEnd()) {
19
+ this.#fail('EXPECTED_TERM', 'Expected a dice expression or integer modifier');
20
+ }
21
+ expressions.push(this.#readTerm(sign));
22
+ this.#skipWhitespace();
23
+ first = false;
24
+ if (!this.#isAtEnd() && !this.#isSign(this.#current())) {
25
+ this.#fail('EXPECTED_OPERATOR', 'Expected "+" or "-" between terms');
26
+ }
27
+ }
28
+ return {
29
+ kind: 'roll',
30
+ source: this.#input,
31
+ expressions,
32
+ };
33
+ }
34
+ #readSign(first) {
35
+ const character = this.#current();
36
+ if (character === '+') {
37
+ this.#index += 1;
38
+ return 1;
39
+ }
40
+ if (character === '-') {
41
+ this.#index += 1;
42
+ return -1;
43
+ }
44
+ if (first) {
45
+ return 1;
46
+ }
47
+ return this.#fail('EXPECTED_OPERATOR', 'Expected "+" or "-" between terms');
48
+ }
49
+ #readTerm(sign) {
50
+ const termStart = this.#index;
51
+ const integerStart = this.#index;
52
+ this.#consumeDigits();
53
+ const integerEnd = this.#index;
54
+ if (this.#current()?.toLowerCase() === 'd') {
55
+ if (sign === -1) {
56
+ this.#failAt('NEGATIVE_DICE', 'Negative dice expressions are not supported', termStart);
57
+ }
58
+ const count = integerStart === integerEnd ? 1 : this.#readInteger(integerStart, integerEnd, 'count');
59
+ this.#index += 1;
60
+ if (count < 1) {
61
+ this.#failAt('INVALID_COUNT', 'Dice count must be at least one', integerStart);
62
+ }
63
+ if (this.#current() === '%') {
64
+ this.#index += 1;
65
+ return {
66
+ kind: 'paired-dice',
67
+ count,
68
+ type: 'd100',
69
+ };
70
+ }
71
+ const sidesStart = this.#index;
72
+ this.#consumeDigits();
73
+ if (sidesStart === this.#index) {
74
+ this.#fail('INVALID_SIDES', 'A dice expression must specify its number of sides');
75
+ }
76
+ const sides = this.#readInteger(sidesStart, this.#index, 'sides');
77
+ if (sides < 2) {
78
+ this.#failAt('INVALID_SIDES', 'A die must have at least two sides', sidesStart);
79
+ }
80
+ if (sides === 100 || sides === 66) {
81
+ return {
82
+ kind: 'paired-dice',
83
+ count,
84
+ type: `d${sides}`,
85
+ };
86
+ }
87
+ return {
88
+ kind: 'dice',
89
+ count,
90
+ sides,
91
+ };
92
+ }
93
+ if (integerStart === integerEnd) {
94
+ const character = this.#current();
95
+ if (character === undefined) {
96
+ this.#fail('EXPECTED_TERM', 'Expected a dice expression or integer modifier');
97
+ }
98
+ this.#fail('UNEXPECTED_CHARACTER', `Unexpected character "${character}"`);
99
+ }
100
+ const value = this.#readInteger(integerStart, integerEnd, 'modifier') * sign;
101
+ return {
102
+ kind: 'modifier',
103
+ value,
104
+ };
105
+ }
106
+ #readInteger(start, end, description) {
107
+ const value = Number(this.#input.slice(start, end));
108
+ if (!Number.isSafeInteger(value)) {
109
+ this.#failAt('UNSAFE_INTEGER', `${description} must be a safe integer`, start);
110
+ }
111
+ return value;
112
+ }
113
+ #consumeDigits() {
114
+ while (!this.#isAtEnd() && this.#isDigit(this.#current())) {
115
+ this.#index += 1;
116
+ }
117
+ }
118
+ #skipWhitespace() {
119
+ while (!this.#isAtEnd() && this.#isWhitespace(this.#current())) {
120
+ this.#index += 1;
121
+ }
122
+ }
123
+ #current() {
124
+ return this.#input[this.#index];
125
+ }
126
+ #isAtEnd() {
127
+ return this.#index >= this.#input.length;
128
+ }
129
+ #isDigit(character) {
130
+ if (character === undefined)
131
+ return false;
132
+ const code = character.charCodeAt(0);
133
+ return code >= 48 && code <= 57;
134
+ }
135
+ #isWhitespace(character) {
136
+ return character === ' ' || character === '\t' || character === '\n' || character === '\r';
137
+ }
138
+ #isSign(character) {
139
+ return character === '+' || character === '-';
140
+ }
141
+ #fail(code, message) {
142
+ return this.#failAt(code, message, this.#index);
143
+ }
144
+ #failAt(code, message, index) {
145
+ throw new NotationParseError(code, message, this.#input, index);
146
+ }
147
+ }
148
+ export function parseNotation(input) {
149
+ return new NotationParser(input).parse();
150
+ }
@@ -0,0 +1,10 @@
1
+ export interface RandomSource {
2
+ next(): number;
3
+ }
4
+ export declare const mathRandomSource: RandomSource;
5
+ export declare const cryptoRandomSource: RandomSource;
6
+ export declare class SeededRandomSource implements RandomSource {
7
+ #private;
8
+ constructor(seed: number);
9
+ next(): number;
10
+ }
@@ -0,0 +1,33 @@
1
+ const UINT32_RANGE = 4_294_967_296;
2
+ const UINT53_RANGE = 9_007_199_254_740_992;
3
+ export const mathRandomSource = Object.freeze({
4
+ next: () => Math.random(),
5
+ });
6
+ export const cryptoRandomSource = Object.freeze({
7
+ next: () => {
8
+ const crypto = globalThis.crypto;
9
+ if (crypto === undefined) {
10
+ throw new Error('Web Crypto is required for cryptographic dice randomness');
11
+ }
12
+ const words = new Uint32Array(2);
13
+ crypto.getRandomValues(words);
14
+ const high = words[0] & 0x001f_ffff;
15
+ return (high * UINT32_RANGE + words[1]) / UINT53_RANGE;
16
+ },
17
+ });
18
+ export class SeededRandomSource {
19
+ #state;
20
+ constructor(seed) {
21
+ if (!Number.isSafeInteger(seed)) {
22
+ throw new TypeError('Random seed must be a safe integer');
23
+ }
24
+ this.#state = seed >>> 0;
25
+ }
26
+ next() {
27
+ this.#state = (this.#state + 0x6d2b79f5) >>> 0;
28
+ let value = this.#state;
29
+ value = Math.imul(value ^ (value >>> 15), value | 1);
30
+ value ^= value + Math.imul(value ^ (value >>> 7), value | 61);
31
+ return ((value ^ (value >>> 14)) >>> 0) / 4_294_967_296;
32
+ }
33
+ }
@@ -0,0 +1,4 @@
1
+ import type { RollNotation } from '../notation/ast.js';
2
+ import type { CreateRollResultOptions, RollResult } from './types.js';
3
+ export declare function getNotationModifier(notation: RollNotation): number;
4
+ export declare function createRollResult(options: CreateRollResultOptions): RollResult;
@@ -0,0 +1,76 @@
1
+ export function getNotationModifier(notation) {
2
+ return notation.expressions.reduce((total, expression) => total + (expression.kind === 'modifier' ? expression.value : 0), 0);
3
+ }
4
+ export function createRollResult(options) {
5
+ if (options.id.length === 0) {
6
+ throw new TypeError('Roll result id must not be empty');
7
+ }
8
+ if (options.completedAt < options.startedAt) {
9
+ throw new RangeError('Roll completion time must not precede its start time');
10
+ }
11
+ const dice = Object.freeze(options.dice.map((die) => Object.freeze({
12
+ ...die,
13
+ ...(die.component === undefined ? {} : { component: Object.freeze({ ...die.component }) }),
14
+ })));
15
+ const diceTotal = getDiceTotal(dice);
16
+ return Object.freeze({
17
+ id: options.id,
18
+ notation: options.notation,
19
+ dice,
20
+ modifier: options.modifier,
21
+ total: diceTotal + options.modifier,
22
+ startedAt: options.startedAt,
23
+ completedAt: options.completedAt,
24
+ });
25
+ }
26
+ function getDiceTotal(dice) {
27
+ let total = 0;
28
+ const groups = new Map();
29
+ for (const die of dice) {
30
+ const component = die.component;
31
+ if (component === undefined) {
32
+ total += die.value;
33
+ continue;
34
+ }
35
+ const existing = groups.get(component.groupId);
36
+ const group = existing ?? { type: component.groupType };
37
+ if (group.type !== component.groupType) {
38
+ throw new RangeError(`Dice group ${component.groupId} mixes incompatible group types`);
39
+ }
40
+ if (group[component.role] !== undefined) {
41
+ throw new RangeError(`Dice group ${component.groupId} has duplicate ${component.role} dice`);
42
+ }
43
+ const digit = component.groupType === 'd100' ? component.faceValue % 10 : component.faceValue;
44
+ const expectedValue = component.role === 'tens' ? digit * 10 : digit;
45
+ if (die.value !== expectedValue) {
46
+ throw new RangeError(`Dice component ${die.id} has value ${die.value}; expected ${expectedValue} from its face`);
47
+ }
48
+ group[component.role] = component;
49
+ groups.set(component.groupId, group);
50
+ }
51
+ for (const [groupId, group] of groups) {
52
+ if (group.tens === undefined || group.units === undefined) {
53
+ throw new RangeError(`Dice group ${groupId} must contain one tens die and one units die`);
54
+ }
55
+ total += getGroupTotal(groupId, group.type, group.tens, group.units);
56
+ }
57
+ return total;
58
+ }
59
+ function getGroupTotal(groupId, groupType, tens, units) {
60
+ const tensFace = tens.faceValue;
61
+ const unitsFace = units.faceValue;
62
+ if (groupType === 'd100') {
63
+ assertFaceRange(groupId, tensFace, 1, 10);
64
+ assertFaceRange(groupId, unitsFace, 1, 10);
65
+ const value = (tensFace % 10) * 10 + (unitsFace % 10);
66
+ return value === 0 ? 100 : value;
67
+ }
68
+ assertFaceRange(groupId, tensFace, 1, 6);
69
+ assertFaceRange(groupId, unitsFace, 1, 6);
70
+ return tensFace * 10 + unitsFace;
71
+ }
72
+ function assertFaceRange(groupId, value, minimum, maximum) {
73
+ if (!Number.isInteger(value) || value < minimum || value > maximum) {
74
+ throw new RangeError(`Dice group ${groupId} has face value ${value}; expected an integer in [${minimum}, ${maximum}]`);
75
+ }
76
+ }
@@ -0,0 +1,28 @@
1
+ import type { DieResult } from '../dice/types.js';
2
+ export type RollState = 'pending' | 'rolling' | 'settled' | 'cancelled' | 'failed';
3
+ export type RollMode = 'queue' | 'replace' | 'parallel';
4
+ export interface RollSession {
5
+ readonly id: string;
6
+ readonly notation: string;
7
+ readonly state: RollState;
8
+ readonly createdAt: number;
9
+ readonly startedAt?: number;
10
+ readonly completedAt?: number;
11
+ }
12
+ export interface RollResult {
13
+ readonly id: string;
14
+ readonly notation: string;
15
+ readonly dice: readonly DieResult[];
16
+ readonly modifier: number;
17
+ readonly total: number;
18
+ readonly startedAt: number;
19
+ readonly completedAt: number;
20
+ }
21
+ export interface CreateRollResultOptions {
22
+ readonly id: string;
23
+ readonly notation: string;
24
+ readonly dice: readonly DieResult[];
25
+ readonly modifier: number;
26
+ readonly startedAt: number;
27
+ readonly completedAt: number;
28
+ }
File without changes
package/package.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "name": "@dice-o-rolla/dice-core",
3
+ "version": "0.1.0",
4
+ "description": "Framework-neutral dice notation, roll results, events, and random sources.",
5
+ "keywords": [
6
+ "dice",
7
+ "dice-roller",
8
+ "rpg",
9
+ "typescript"
10
+ ],
11
+ "license": "Apache-2.0",
12
+ "files": [
13
+ "dist",
14
+ "README.md",
15
+ "LICENSE",
16
+ "NOTICE",
17
+ "THIRD_PARTY_NOTICES.md"
18
+ ],
19
+ "type": "module",
20
+ "sideEffects": false,
21
+ "types": "./dist/index.d.ts",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "import": "./dist/index.js",
26
+ "default": "./dist/index.js"
27
+ }
28
+ },
29
+ "publishConfig": {
30
+ "access": "public",
31
+ "registry": "https://registry.npmjs.org/"
32
+ },
33
+ "engines": {
34
+ "node": ">=20.0.0"
35
+ }
36
+ }