@altopelago/sansa 0.14.2 → 0.15.0-rc.3
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/CHANGELOG.md +133 -1
- package/README.md +98 -1
- package/conformance/README.md +8 -0
- package/conformance/aeonic-anchor-claims.json +133 -0
- package/conformance/aeonic-arithmetic-claims.json +60 -0
- package/conformance/aeonic-clock-claims.json +123 -0
- package/conformance/aeonic-comparison-claims.json +37 -0
- package/conformance/aeonic-datetime-claims.json +110 -0
- package/conformance/aeonic-rational-arithmetic-claims.json +72 -0
- package/conformance/aeonic-temporal-claims.json +105 -0
- package/conformance/cts-claims.json +17 -3
- package/conformance/results/aeonic-anchor-bounded-expansion-2026-11-24.json +39 -0
- package/conformance/results/aeonic-anchor-capacity-bounded-expansion-2026-11-24.json +452 -0
- package/conformance/results/aeonic-anchor-capacity-rc3-2026-11-24.json +452 -0
- package/conformance/results/aeonic-anchor-capacity.json +452 -0
- package/conformance/results/aeonic-anchor-rc3-2026-11-24.json +39 -0
- package/conformance/results/aeonic-anchor-snapshot-0.1.json +39 -0
- package/conformance/results/aeonic-arithmetic-snapshot-0.1.json +28 -0
- package/conformance/results/aeonic-clock-all-bounded-expansion-2026-11-24.json +49 -0
- package/conformance/results/aeonic-clock-all-rc3-2026-11-24.json +49 -0
- package/conformance/results/aeonic-clock-all-snapshot-0.1.json +49 -0
- package/conformance/results/aeonic-clock-arithmetic-bounded-expansion-2026-11-24.json +48 -0
- package/conformance/results/aeonic-clock-arithmetic-rc3-2026-11-24.json +48 -0
- package/conformance/results/aeonic-clock-arithmetic-snapshot-0.1.json +48 -0
- package/conformance/results/aeonic-clock-capacity-bounded-expansion-2026-11-24.json +326 -0
- package/conformance/results/aeonic-clock-capacity-rc3-2026-11-24.json +326 -0
- package/conformance/results/aeonic-clock-capacity.json +326 -0
- package/conformance/results/aeonic-clock-relations-bounded-expansion-2026-11-24.json +48 -0
- package/conformance/results/aeonic-clock-relations-rc3-2026-11-24.json +48 -0
- package/conformance/results/aeonic-clock-relations-snapshot-0.1.json +48 -0
- package/conformance/results/aeonic-comparison-snapshot-0.1.json +19 -0
- package/conformance/results/aeonic-datetime-all-bounded-expansion-2026-11-24.json +47 -0
- package/conformance/results/aeonic-datetime-all-rc3-2026-11-24.json +47 -0
- package/conformance/results/aeonic-datetime-all-snapshot-0.1.json +47 -0
- package/conformance/results/aeonic-datetime-arithmetic-bounded-expansion-2026-11-24.json +46 -0
- package/conformance/results/aeonic-datetime-arithmetic-rc3-2026-11-24.json +46 -0
- package/conformance/results/aeonic-datetime-arithmetic-snapshot-0.1.json +46 -0
- package/conformance/results/aeonic-datetime-capacity-bounded-expansion-2026-11-24.json +302 -0
- package/conformance/results/aeonic-datetime-capacity-rc3-2026-11-24.json +302 -0
- package/conformance/results/aeonic-datetime-capacity.json +302 -0
- package/conformance/results/aeonic-datetime-relations-bounded-expansion-2026-11-24.json +46 -0
- package/conformance/results/aeonic-datetime-relations-rc3-2026-11-24.json +46 -0
- package/conformance/results/aeonic-datetime-relations-snapshot-0.1.json +46 -0
- package/conformance/results/aeonic-rational-arithmetic-capacity.json +100 -0
- package/conformance/results/aeonic-rational-arithmetic-snapshot-0.2.json +30 -0
- package/conformance/results/aeonic-temporal-all-bounded-expansion-2026-11-24.json +39 -0
- package/conformance/results/aeonic-temporal-all-property-addressing-2026-11-16.json +39 -0
- package/conformance/results/aeonic-temporal-all-rc3-2026-11-24.json +39 -0
- package/conformance/results/aeonic-temporal-all-snapshot-0.1.json +39 -0
- package/conformance/results/aeonic-temporal-calendar-bounded-expansion-2026-11-24.json +38 -0
- package/conformance/results/aeonic-temporal-calendar-property-addressing-2026-11-16.json +38 -0
- package/conformance/results/aeonic-temporal-calendar-rc3-2026-11-24.json +38 -0
- package/conformance/results/aeonic-temporal-calendar-snapshot-0.1.json +38 -0
- package/conformance/results/aeonic-temporal-capacity-bounded-expansion-2026-11-24.json +136 -0
- package/conformance/results/aeonic-temporal-capacity-property-addressing-2026-11-16.json +136 -0
- package/conformance/results/aeonic-temporal-capacity-rc3-2026-11-24.json +136 -0
- package/conformance/results/aeonic-temporal-capacity.json +136 -0
- package/conformance/results/aeonic-temporal-relations-bounded-expansion-2026-11-24.json +38 -0
- package/conformance/results/aeonic-temporal-relations-property-addressing-2026-11-16.json +38 -0
- package/conformance/results/aeonic-temporal-relations-rc3-2026-11-24.json +38 -0
- package/conformance/results/aeonic-temporal-relations-snapshot-0.1.json +38 -0
- package/docs/aeonic-arithmetic.md +126 -0
- package/docs/aeonic-comparison.md +123 -0
- package/docs/aeonic-rational-arithmetic.md +167 -0
- package/docs/aeonic-temporal-civil-anchor.md +89 -0
- package/docs/aeonic-temporal-civil-clock.md +100 -0
- package/docs/aeonic-temporal-civil-date.md +124 -0
- package/docs/aeonic-temporal-civil-datetime.md +122 -0
- package/docs/api-contract.md +130 -3
- package/docs/capabilities.json +106 -2
- package/docs/child-identity-activation.md +93 -0
- package/docs/child-identity-candidate.md +60 -0
- package/docs/child-identity-tooling.md +31 -0
- package/docs/child-identity-workflows.md +102 -0
- package/docs/empty-keys-candidate.md +29 -0
- package/docs/migration-0.15.0.md +86 -0
- package/docs/property-addressing-implementation.md +118 -0
- package/docs/property-resolve-implementation.md +105 -0
- package/docs/property-selector-support.md +65 -0
- package/docs/property-selectors-api.d.ts +43 -0
- package/docs/property-selectors-api.pyi +27 -0
- package/docs/property-selectors-api.rs +48 -0
- package/docs/property-selectors-contract.md +168 -0
- package/docs/query-tool.md +32 -1
- package/docs/selector-cursor.md +45 -0
- package/docs/unicode-hardening.md +41 -0
- package/fixtures/address-v1.json +4 -3
- package/fixtures/child-identity-workflows/README.md +9 -0
- package/fixtures/child-identity-workflows/moved.aeon +10 -0
- package/fixtures/child-identity-workflows/original.aeon +10 -0
- package/fixtures/child-identity-workflows/reordered.aeon +10 -0
- package/fixtures/child-identity-workflows/replacement.aeon +10 -0
- package/fixtures/child-identity-workflows/workflows.json +89 -0
- package/fixtures/property-namespace-candidate-v1.json +336 -0
- package/fixtures/property-parser-candidate-v1.json +705 -0
- package/fixtures/property-query-candidate-v1.json +398 -0
- package/fixtures/property-resolve-candidate-v1.json +2702 -0
- package/fixtures/unicode-hardening-v1.json +401 -0
- package/package.json +30 -3
- package/scripts/calibrate-aeonic-anchor-capacity.py +294 -0
- package/scripts/calibrate-aeonic-clock-capacity.py +62 -0
- package/scripts/calibrate-aeonic-datetime-capacity.py +76 -0
- package/scripts/calibrate-aeonic-rational-capacity.py +85 -0
- package/scripts/calibrate-aeonic-temporal-capacity.py +95 -0
- package/scripts/cts-address.mjs +6 -2
- package/scripts/cts-aeonic-anchor.mjs +21 -0
- package/scripts/cts-aeonic-arithmetic-adapter.mjs +25 -0
- package/scripts/cts-aeonic-arithmetic.mjs +24 -0
- package/scripts/cts-aeonic-clock.mjs +24 -0
- package/scripts/cts-aeonic-comparison-adapter.mjs +30 -0
- package/scripts/cts-aeonic-comparison.mjs +25 -0
- package/scripts/cts-aeonic-datetime.mjs +24 -0
- package/scripts/cts-aeonic-rational-arithmetic-adapter.mjs +25 -0
- package/scripts/cts-aeonic-rational-arithmetic.mjs +24 -0
- package/scripts/cts-aeonic-temporal-civil-anchor-adapter.mjs +26 -0
- package/scripts/cts-aeonic-temporal-civil-clock-adapter.mjs +28 -0
- package/scripts/cts-aeonic-temporal-civil-date-adapter.mjs +28 -0
- package/scripts/cts-aeonic-temporal-civil-datetime-adapter.mjs +28 -0
- package/scripts/cts-aeonic-temporal.mjs +24 -0
- package/scripts/cts-instruction.mjs +4 -2
- package/scripts/cts-mutate.mjs +3 -2
- package/scripts/cts-resolve.mjs +17 -2
- package/scripts/playground.mjs +110 -0
- package/src/aeonic-arithmetic-binding.js +61 -0
- package/src/aeonic-arithmetic.d.ts +84 -0
- package/src/aeonic-arithmetic.js +276 -0
- package/src/aeonic-comparison.d.ts +86 -0
- package/src/aeonic-comparison.js +274 -0
- package/src/aeonic-convenience.d.ts +30 -0
- package/src/aeonic-convenience.js +45 -0
- package/src/aeonic-exact-number.js +34 -0
- package/src/aeonic-json.js +45 -0
- package/src/aeonic-rational-arithmetic.d.ts +86 -0
- package/src/aeonic-rational-arithmetic.js +417 -0
- package/src/aeonic-rational-json.js +51 -0
- package/src/aeonic-temporal-civil-anchor.d.ts +54 -0
- package/src/aeonic-temporal-civil-anchor.js +316 -0
- package/src/aeonic-temporal-civil-clock.d.ts +124 -0
- package/src/aeonic-temporal-civil-clock.js +388 -0
- package/src/aeonic-temporal-civil-date.d.ts +123 -0
- package/src/aeonic-temporal-civil-date.js +310 -0
- package/src/aeonic-temporal-civil-datetime.d.ts +138 -0
- package/src/aeonic-temporal-civil-datetime.js +501 -0
- package/src/index.d.ts +84 -1
- package/src/index.js +859 -190
- package/src/property-address.js +196 -0
- package/src/property-resolve.js +132 -0
- package/src/query-metadata.d.ts +16 -0
- package/src/query-metadata.js +25 -0
- package/src/selector-cursor.d.ts +19 -0
- package/src/selector-cursor.js +79 -0
- package/stress-tests/address/invalid.sansa-cases +0 -2
- package/stress-tests/address/valid.sansa-cases +3 -0
- package/tools/mutate-web/examples.mjs +1 -1
- package/tools/mutate-web/runtime.mjs +0 -2
- package/tools/playground/README.md +165 -0
- package/tools/playground/accessibility.js +91 -0
- package/tools/playground/aeon-highlight.js +77 -0
- package/tools/playground/aeon-source-composer.js +1077 -0
- package/tools/playground/anchor-examples.mjs +16 -0
- package/tools/playground/arithmetic-evaluator.mjs +28 -0
- package/tools/playground/arithmetic-model.mjs +187 -0
- package/tools/playground/arithmetic-worker.mjs +14 -0
- package/tools/playground/arithmetic.css +1 -0
- package/tools/playground/arithmetic.html +29 -0
- package/tools/playground/arithmetic.mjs +110 -0
- package/tools/playground/clock-examples.mjs +16 -0
- package/tools/playground/datetime-examples.mjs +22 -0
- package/tools/playground/examples.mjs +46 -0
- package/tools/playground/index.html +174 -0
- package/tools/playground/local.css +25 -0
- package/tools/playground/namespace.mjs +39 -0
- package/tools/playground/sansa-playground.js +1565 -0
- package/tools/playground/site.css +3914 -0
- package/tools/playground/temporal-examples.mjs +20 -0
- package/tools/playground/walkthrough.js +90 -0
- package/tools/playground/website-origin.json +16 -0
- package/tools/query-web/IDENTITY_SELECTORS.md +44 -0
- package/tools/query-web/app.js +4 -0
- package/tools/query-web/index.html +4 -0
- package/tools/query-web/runtime.mjs +70 -19
- package/tools/workflows/property-playground-assertions.mjs +33 -0
- package/tools/workflows/verify-child-identities.mjs +137 -0
- package/tools/workflows/verify-property-playground.mjs +48 -0
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {createServer} from 'node:http';
|
|
3
|
+
import {readFile, realpath, stat} from 'node:fs/promises';
|
|
4
|
+
import {existsSync, readdirSync, readFileSync} from 'node:fs';
|
|
5
|
+
import {basename, extname, resolve, sep} from 'node:path';
|
|
6
|
+
import {fileURLToPath} from 'node:url';
|
|
7
|
+
|
|
8
|
+
const repo = fileURLToPath(new URL('..', import.meta.url));
|
|
9
|
+
|
|
10
|
+
export function findAeonRoot(explicit) {
|
|
11
|
+
const candidates = explicit ? [resolve(explicit)] : [
|
|
12
|
+
resolve(repo, '../../aeon', basename(repo)), resolve(repo, '../aeon'),
|
|
13
|
+
];
|
|
14
|
+
const found = candidates.find(p => existsSync(resolve(p, 'implementations/typescript/packages/sdk/dist/sansa.js')));
|
|
15
|
+
if (!found) throw new Error('A built AEON checkout is required. Run npm run playground -- --aeon-root /path/to/aeon (build its TypeScript packages first).');
|
|
16
|
+
return found;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function playgroundImports(aeonRoot) {
|
|
20
|
+
const packages = resolve(aeonRoot, 'implementations/typescript/packages');
|
|
21
|
+
const imports = {'@altopelago/sansa': '/src/index.js',
|
|
22
|
+
'@altopelago/sansa/parsing/selector-cursor': '/src/selector-cursor.js'};
|
|
23
|
+
for (const dir of readdirSync(packages, {withFileTypes: true}).filter(d => d.isDirectory())) {
|
|
24
|
+
const root = resolve(packages, dir.name);
|
|
25
|
+
if (!existsSync(resolve(root, 'package.json'))) continue;
|
|
26
|
+
const pkg = JSON.parse(readFileSync(resolve(root, 'package.json'), 'utf8'));
|
|
27
|
+
const rootExport = pkg.exports?.['.'] ?? pkg.exports;
|
|
28
|
+
const main = typeof rootExport === 'string' ? rootExport
|
|
29
|
+
: rootExport?.import ?? rootExport?.default ?? pkg.module ?? pkg.main ?? './dist/index.js';
|
|
30
|
+
if (typeof main !== 'string' || !main.startsWith('./dist/')) continue;
|
|
31
|
+
imports[pkg.name] = `/aeon/${dir.name}/${main.slice(7)}`;
|
|
32
|
+
// SDK subpaths and any other explicit browser-compatible public entry points.
|
|
33
|
+
for (const [key, value] of Object.entries(pkg.exports ?? {})) {
|
|
34
|
+
const entry = typeof value === 'string' ? value : value?.import;
|
|
35
|
+
if (key.startsWith('./') && typeof entry === 'string' && entry.startsWith('./dist/')) {
|
|
36
|
+
imports[pkg.name + key.slice(1)] = `/aeon/${dir.name}/${entry.slice(7)}`;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
imports['@aeon/runtime'] = imports['@altopelago/aeon-runtime'];
|
|
41
|
+
if (!imports['@aeon/runtime'] || !imports['@altopelago/aeon-sdk/sansa'] || !imports['@altopelago/aeon-highlight']) {
|
|
42
|
+
throw new Error('AEON runtime, SDK and highlight browser entry points are missing from the selected checkout.');
|
|
43
|
+
}
|
|
44
|
+
return {imports};
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function createPlaygroundServer({aeonRoot}) {
|
|
48
|
+
const imports = JSON.stringify(playgroundImports(aeonRoot)).replaceAll('<', '\\u003c');
|
|
49
|
+
const packages = resolve(aeonRoot, 'implementations/typescript/packages');
|
|
50
|
+
return createServer(async (request, response) => {
|
|
51
|
+
const reply = (status, text) => {
|
|
52
|
+
response.writeHead(status, {'content-type': 'text/plain; charset=utf-8', 'cache-control': 'no-store'});
|
|
53
|
+
response.end(text);
|
|
54
|
+
};
|
|
55
|
+
if (!['GET', 'HEAD'].includes(request.method)) return reply(405, 'Use GET or HEAD.');
|
|
56
|
+
try {
|
|
57
|
+
const pathname = decodeURIComponent(new URL(request.url, 'http://localhost').pathname);
|
|
58
|
+
let root, relative;
|
|
59
|
+
if (pathname === '/' || pathname === '/tools/playground/' || pathname === '/tools/playground/index.html') {
|
|
60
|
+
const html = (await readFile(resolve(repo, 'tools/playground/index.html'), 'utf8'))
|
|
61
|
+
.replace('__PLAYGROUND_IMPORTS__', () => imports);
|
|
62
|
+
response.writeHead(200, {'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store'});
|
|
63
|
+
return response.end(request.method === 'HEAD' ? undefined : html);
|
|
64
|
+
}
|
|
65
|
+
if (pathname === '/tools/playground/arithmetic.html') {
|
|
66
|
+
const html = await readFile(resolve(repo, 'tools/playground/arithmetic.html'), 'utf8');
|
|
67
|
+
response.writeHead(200, {'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store'});
|
|
68
|
+
return response.end(request.method === 'HEAD' ? undefined : html);
|
|
69
|
+
}
|
|
70
|
+
if (pathname.startsWith('/src/')) {
|
|
71
|
+
root = resolve(repo, 'src'); relative = pathname.slice(5);
|
|
72
|
+
} else if (pathname.startsWith('/tools/playground/')) {
|
|
73
|
+
root = resolve(repo, 'tools/playground'); relative = pathname.slice('/tools/playground/'.length);
|
|
74
|
+
} else if (pathname.startsWith('/aeon/')) {
|
|
75
|
+
const match = /^\/aeon\/([a-z0-9-]+)\/(.+)$/.exec(pathname);
|
|
76
|
+
if (!match) return reply(404, 'Not found.');
|
|
77
|
+
root = resolve(packages, match[1], 'dist'); relative = match[2];
|
|
78
|
+
} else return reply(404, 'Not found.');
|
|
79
|
+
const file = await realpath(resolve(root, relative));
|
|
80
|
+
const allowedRoot = await realpath(root);
|
|
81
|
+
if (!file.startsWith(allowedRoot + sep) || !(await stat(file)).isFile()) return reply(403, 'Forbidden.');
|
|
82
|
+
const types = {'.js': 'text/javascript', '.mjs': 'text/javascript', '.css': 'text/css', '.json': 'application/json'};
|
|
83
|
+
const type = types[extname(file)];
|
|
84
|
+
if (!type) return reply(404, 'Not found.');
|
|
85
|
+
const body = await readFile(file);
|
|
86
|
+
response.writeHead(200, {'content-type': `${type}; charset=utf-8`, 'cache-control': 'no-store'});
|
|
87
|
+
response.end(request.method === 'HEAD' ? undefined : body);
|
|
88
|
+
} catch (error) {
|
|
89
|
+
reply(error instanceof URIError ? 400 : 404, 'Not found.');
|
|
90
|
+
}
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
|
95
|
+
const arg = name => { const i = process.argv.indexOf(name); return i < 0 ? undefined : process.argv[i + 1]; };
|
|
96
|
+
try {
|
|
97
|
+
const aeonRoot = findAeonRoot(arg('--aeon-root') ?? process.env.SANSA_PLAYGROUND_AEON_ROOT);
|
|
98
|
+
const port = Number(arg('--port') ?? 4174);
|
|
99
|
+
if (!Number.isInteger(port) || port < 0 || port > 65535) throw new Error('Port must be an integer from 0 to 65535.');
|
|
100
|
+
const server = createPlaygroundServer({aeonRoot});
|
|
101
|
+
server.on('error', error => { console.error(error.message); process.exitCode = 1; });
|
|
102
|
+
server.listen(port, '127.0.0.1', () => {
|
|
103
|
+
console.log(`SANSA source playground: http://127.0.0.1:${server.address().port}/tools/playground/`);
|
|
104
|
+
console.log(`SANSA: ${resolve(repo, 'src/index.js')}\nAEON: ${aeonRoot}`);
|
|
105
|
+
});
|
|
106
|
+
} catch (error) {
|
|
107
|
+
console.error(error.message);
|
|
108
|
+
process.exitCode = 1;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Adapted from Aeonic at 9433ce2d57200dec2efe50ed0c02bf6b74e636e9 (MIT).
|
|
2
|
+
import { parseStrictJson } from './aeonic-json.js';
|
|
3
|
+
|
|
4
|
+
function exactLimit(token, value) {
|
|
5
|
+
if (!Number.isSafeInteger(value) || value < 0) return false;
|
|
6
|
+
const [mantissa, exponent = '0'] = token.toLowerCase().split('e');
|
|
7
|
+
const fraction = mantissa.split('.')[1] ?? '';
|
|
8
|
+
let digits = mantissa.replace(/^-|\./gu, '').replace(/^0+/u, '');
|
|
9
|
+
// Underflow of a nonzero literal must not turn it into an integer zero.
|
|
10
|
+
if (value === 0) return digits.length === 0;
|
|
11
|
+
const e = Number(exponent);
|
|
12
|
+
if (!Number.isSafeInteger(e) || Math.abs(e) > token.length + 32) return false;
|
|
13
|
+
const trimmed = digits.replace(/0+$/u, '');
|
|
14
|
+
const scale = e - fraction.length + digits.length - trimmed.length;
|
|
15
|
+
digits = trimmed;
|
|
16
|
+
if (scale < 0 || digits.length + scale > 16) return false;
|
|
17
|
+
return Number((mantissa.startsWith('-') ? '-' : '') + digits + '0'.repeat(scale)) === value;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** Retain the mathematical integer constraint at the trusted JSON boundary.
|
|
21
|
+
* JSON.parse alone can round fractional tokens into apparently safe integers.
|
|
22
|
+
* The validated token stream is scanned iteratively, including escaped keys.
|
|
23
|
+
*/
|
|
24
|
+
export function parseArithmeticEnvelope(text) {
|
|
25
|
+
const result = parseStrictJson(text), frames = [];
|
|
26
|
+
const path = () => {
|
|
27
|
+
const f = frames.at(-1);
|
|
28
|
+
// Only the root policy/resourceLimits path matters. Retaining complete
|
|
29
|
+
// paths would use quadratic memory on deeply nested logical fixtures.
|
|
30
|
+
return f ? f.path.length === 4 ? f.path : [...f.path, f.object ? f.key : f.index] : [];
|
|
31
|
+
};
|
|
32
|
+
const done = () => {
|
|
33
|
+
const f = frames.at(-1);
|
|
34
|
+
if (f) { f.state = 'comma'; if (!f.object) f.index++; }
|
|
35
|
+
};
|
|
36
|
+
for (let i = 0; i < text.length;) {
|
|
37
|
+
const c = text[i];
|
|
38
|
+
if (/\s/u.test(c)) { i++; continue; }
|
|
39
|
+
if (c === '{' || c === '[') {
|
|
40
|
+
const at = path(); done(); frames.push({ path: at, object: c === '{', state: c === '{' ? 'key' : 'value', key: null, index: 0 }); i++;
|
|
41
|
+
} else if (c === '}' || c === ']') { frames.pop(); i++; }
|
|
42
|
+
else if (c === ':') { frames.at(-1).state = 'value'; i++; }
|
|
43
|
+
else if (c === ',') { const f = frames.at(-1); f.state = f.object ? 'key' : 'value'; i++; }
|
|
44
|
+
else if (c === '"') {
|
|
45
|
+
const start = i++;
|
|
46
|
+
while (i < text.length) { if (text[i] === '\\') i += 2; else if (text[i++] === '"') break; }
|
|
47
|
+
const f = frames.at(-1);
|
|
48
|
+
if (f?.object && f.state === 'key') { f.key = JSON.parse(text.slice(start, i)); f.state = 'colon'; }
|
|
49
|
+
else done();
|
|
50
|
+
} else if (c === '-' || /[0-9]/u.test(c)) {
|
|
51
|
+
const start = i++;
|
|
52
|
+
while (i < text.length && /[0-9eE+.\-]/u.test(text[i])) i++;
|
|
53
|
+
const at = path(), token = text.slice(start, i);
|
|
54
|
+
if (at.length === 3 && at[0] === 'policy' && at[1] === 'resourceLimits' && !exactLimit(token, Number(token))) {
|
|
55
|
+
throw new TypeError('Trusted resource limit must be an exact nonnegative safe integer');
|
|
56
|
+
}
|
|
57
|
+
done();
|
|
58
|
+
} else { i += c === 't' || c === 'n' ? 4 : 5; done(); }
|
|
59
|
+
}
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
export const AEONIC_ARITHMETIC_PROFILE: 'aeonic.operations.arithmetic.exact.v1';
|
|
2
|
+
export interface AeonicArithmeticResourceLimits {
|
|
3
|
+
readonly maxRequestBytes: number;
|
|
4
|
+
readonly maxRequestDepth: number;
|
|
5
|
+
readonly maxNumericCharacters: number;
|
|
6
|
+
readonly maxCoefficientDigits: number;
|
|
7
|
+
readonly maxExponentMagnitude: number;
|
|
8
|
+
readonly maxWorkspaceDigits: number;
|
|
9
|
+
readonly maxOutputCharacters: number;
|
|
10
|
+
}
|
|
11
|
+
export const AEONIC_ARITHMETIC_DEFAULT_RESOURCE_LIMITS: Readonly<AeonicArithmeticResourceLimits>;
|
|
12
|
+
export interface AeonicArithmeticOptions {
|
|
13
|
+
readonly resourceLimits?: Partial<AeonicArithmeticResourceLimits>;
|
|
14
|
+
}
|
|
15
|
+
export type AeonicArithmeticHistory = 'none-declared' | 'approximation-declared';
|
|
16
|
+
export interface AeonicFiniteNumber {
|
|
17
|
+
readonly category: 'finiteNumber';
|
|
18
|
+
readonly value: string;
|
|
19
|
+
}
|
|
20
|
+
export interface AeonicExactNumber {
|
|
21
|
+
readonly category: 'exactNumber';
|
|
22
|
+
readonly coefficient: string;
|
|
23
|
+
readonly exponent: string;
|
|
24
|
+
}
|
|
25
|
+
export interface AeonicArithmeticDeferredNumber {
|
|
26
|
+
readonly category: 'string' | 'boolean' | 'symbol' | 'positiveInfinity' | 'negativeInfinity'
|
|
27
|
+
| 'nan' | 'explicitNull' | 'explicitAbsence' | 'toggle' | 'hex' | 'radix'
|
|
28
|
+
| 'encoding' | 'separator' | 'sansaAddress' | 'referenceForm' | 'temporal' | 'container';
|
|
29
|
+
readonly [field: string]: unknown;
|
|
30
|
+
}
|
|
31
|
+
export type AeonicArithmeticOperand =
|
|
32
|
+
| { readonly number: AeonicFiniteNumber | AeonicArithmeticDeferredNumber; readonly history?: AeonicArithmeticHistory }
|
|
33
|
+
| { readonly number: AeonicExactNumber; readonly history: AeonicArithmeticHistory };
|
|
34
|
+
export interface AeonicArithmeticPolicy {
|
|
35
|
+
readonly profile?: string;
|
|
36
|
+
}
|
|
37
|
+
export interface AeonicArithmeticBinaryRequest {
|
|
38
|
+
readonly operation: 'add' | 'subtract' | 'multiply';
|
|
39
|
+
readonly input: {
|
|
40
|
+
readonly left: AeonicArithmeticOperand;
|
|
41
|
+
readonly right: AeonicArithmeticOperand;
|
|
42
|
+
readonly policy?: AeonicArithmeticPolicy;
|
|
43
|
+
readonly context?: AeonicArithmeticPolicy;
|
|
44
|
+
};
|
|
45
|
+
}
|
|
46
|
+
export type AeonicArithmeticOutputFamily = 'integer' | 'decimal' | 'exponent';
|
|
47
|
+
export interface AeonicArithmeticMaterializeRequest {
|
|
48
|
+
readonly operation: 'materialize';
|
|
49
|
+
readonly input: {
|
|
50
|
+
readonly value: AeonicArithmeticOperand;
|
|
51
|
+
readonly context?: AeonicArithmeticPolicy;
|
|
52
|
+
readonly policy: AeonicArithmeticPolicy & {
|
|
53
|
+
readonly family: AeonicArithmeticOutputFamily;
|
|
54
|
+
readonly zeroSign?: 'positive' | 'negative';
|
|
55
|
+
};
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
export type AeonicArithmeticRequest = AeonicArithmeticBinaryRequest | AeonicArithmeticMaterializeRequest;
|
|
59
|
+
export interface AeonicArithmeticDiagnostic {
|
|
60
|
+
readonly outcome: 'diagnostic';
|
|
61
|
+
readonly reason: 'resource_limit' | 'invalid_operand' | 'unsupported_operation'
|
|
62
|
+
| 'invalid_policy' | 'unsupported_profile' | 'unsupported_domain' | 'unrepresentable_result';
|
|
63
|
+
readonly context: { readonly stage: 1 | 2 | 3 | 4 | 5 | 6 | 7; readonly path: string | null };
|
|
64
|
+
readonly message?: string;
|
|
65
|
+
}
|
|
66
|
+
export interface AeonicArithmeticValueResult {
|
|
67
|
+
readonly outcome: 'value';
|
|
68
|
+
readonly value:
|
|
69
|
+
| { readonly number: AeonicFiniteNumber; readonly history: AeonicArithmeticHistory }
|
|
70
|
+
| { readonly number: AeonicExactNumber; readonly history: AeonicArithmeticHistory };
|
|
71
|
+
readonly metadata: {
|
|
72
|
+
readonly evaluation: 'exact-for-operands';
|
|
73
|
+
readonly effectivePolicy: {
|
|
74
|
+
readonly profile: typeof AEONIC_ARITHMETIC_PROFILE;
|
|
75
|
+
readonly family?: AeonicArithmeticOutputFamily;
|
|
76
|
+
readonly zeroSign?: 'positive' | 'negative';
|
|
77
|
+
};
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
export type AeonicArithmeticResult = AeonicArithmeticValueResult | AeonicArithmeticDiagnostic;
|
|
81
|
+
/** Exact finite arithmetic and explicit materialization; diagnostics never carry values. */
|
|
82
|
+
export function evaluateAeonicArithmetic(request: AeonicArithmeticRequest, options?: AeonicArithmeticOptions): AeonicArithmeticResult;
|
|
83
|
+
/** Exact Unicode JSON ingress with staged byte/depth and duplicate-key admission. */
|
|
84
|
+
export function evaluateAeonicArithmeticText(requestText: string, options?: AeonicArithmeticOptions): AeonicArithmeticResult;
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
// Adapted from Aeonic exact arithmetic at 9433ce2d57200dec2efe50ed0c02bf6b74e636e9.
|
|
2
|
+
// Copyright (c) 2026 Patrik. MIT; see LICENSE and docs/aeonic-arithmetic.md.
|
|
3
|
+
import { FINITE_NUMBER } from './aeonic-exact-number.js';
|
|
4
|
+
import { exceedsJsonDepth, parseStrictJson } from './aeonic-json.js';
|
|
5
|
+
|
|
6
|
+
export const AEONIC_ARITHMETIC_PROFILE = 'aeonic.operations.arithmetic.exact.v1';
|
|
7
|
+
export const AEONIC_ARITHMETIC_DEFAULT_RESOURCE_LIMITS = Object.freeze({
|
|
8
|
+
maxRequestBytes: 4194304, maxRequestDepth: 32, maxNumericCharacters: 65536,
|
|
9
|
+
maxCoefficientDigits: 65536, maxExponentMagnitude: 1000000,
|
|
10
|
+
maxWorkspaceDigits: 131072, maxOutputCharacters: 65536,
|
|
11
|
+
});
|
|
12
|
+
function compareScalars(left, right) {
|
|
13
|
+
const a = left[Symbol.iterator]();
|
|
14
|
+
const b = right[Symbol.iterator]();
|
|
15
|
+
while (true) {
|
|
16
|
+
const x = a.next(); const y = b.next();
|
|
17
|
+
if (x.done || y.done) return x.done === y.done ? 0 : x.done ? -1 : 1;
|
|
18
|
+
const difference = x.value.codePointAt(0) - y.value.codePointAt(0);
|
|
19
|
+
if (difference !== 0) return difference < 0 ? -1 : 1;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// Count only through the allowance; avoid a whole-input TextEncoder buffer.
|
|
24
|
+
function utf8ByteLength(text, limit) {
|
|
25
|
+
let bytes = 0;
|
|
26
|
+
for (const character of text) {
|
|
27
|
+
const point = character.codePointAt(0);
|
|
28
|
+
bytes += point <= 0x7f ? 1 : point <= 0x7ff ? 2 : point <= 0xffff ? 3 : 4;
|
|
29
|
+
if (bytes > limit) break;
|
|
30
|
+
}
|
|
31
|
+
return bytes;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
const DEFERRED = new Set(['string', 'boolean', 'symbol', 'positiveInfinity', 'negativeInfinity',
|
|
35
|
+
'nan', 'explicitNull', 'explicitAbsence', 'toggle', 'hex', 'radix', 'encoding',
|
|
36
|
+
'separator', 'sansaAddress', 'referenceForm', 'temporal', 'container']);
|
|
37
|
+
const HISTORY = ['none-declared', 'approximation-declared'];
|
|
38
|
+
const record = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
39
|
+
const scalar = (v) => typeof v === 'string' && !/[\uD800-\uDFFF]/u.test(v);
|
|
40
|
+
const identifier = (v) => scalar(v) && v.length > 0;
|
|
41
|
+
const pointer = (p, k) => p === null || !scalar(String(k)) ? null
|
|
42
|
+
: `${p}/${String(k).replaceAll('~', '~0').replaceAll('/', '~1')}`;
|
|
43
|
+
class Failure extends Error {
|
|
44
|
+
constructor(reason, stage, path) {
|
|
45
|
+
super(reason); this.result = { outcome: 'diagnostic', reason, context: { stage, path } };
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
const stop = (r, s, p) => { throw new Failure(r, s, p); };
|
|
49
|
+
function configured(options) {
|
|
50
|
+
if (!record(options) || Object.keys(options).some((k) => k !== 'resourceLimits')) throw new TypeError('Invalid trusted options');
|
|
51
|
+
const supplied = Object.hasOwn(options, 'resourceLimits') ? options.resourceLimits : {};
|
|
52
|
+
if (!record(supplied)) throw new TypeError('resourceLimits must be an object');
|
|
53
|
+
for (const [k, v] of Object.entries(supplied)) {
|
|
54
|
+
if (!Object.hasOwn(AEONIC_ARITHMETIC_DEFAULT_RESOURCE_LIMITS, k) || !Number.isSafeInteger(v) || v < 0) throw new TypeError('Invalid resource limit: ' + k);
|
|
55
|
+
}
|
|
56
|
+
return { ...AEONIC_ARITHMETIC_DEFAULT_RESOURCE_LIMITS, ...supplied };
|
|
57
|
+
}
|
|
58
|
+
function closed(v, fields, p, r, s) {
|
|
59
|
+
for (const k of Object.keys(v).sort(compareScalars)) if (!fields.includes(k)) stop(r, s, pointer(p, k));
|
|
60
|
+
}
|
|
61
|
+
function required(v, fields, p, r, s) {
|
|
62
|
+
for (const k of fields) if (!Object.hasOwn(v, k)) stop(r, s, pointer(p, k));
|
|
63
|
+
}
|
|
64
|
+
function admission(v, limit) {
|
|
65
|
+
const stack = [[v, 1, false]], active = new Set(), checked = new WeakMap();
|
|
66
|
+
while (stack.length) {
|
|
67
|
+
const [item, depth, leaving] = stack.pop();
|
|
68
|
+
if (item === null || typeof item !== 'object') continue;
|
|
69
|
+
if (leaving) { active.delete(item); checked.set(item, depth); continue; }
|
|
70
|
+
if (depth > limit) stop('resource_limit', 1, null);
|
|
71
|
+
if (active.has(item)) stop('invalid_operand', 2, null);
|
|
72
|
+
if ((checked.get(item) ?? 0) >= depth) continue;
|
|
73
|
+
active.add(item); stack.push([item, depth, true]);
|
|
74
|
+
for (const child of Object.values(item)) stack.push([child, depth + 1, false]);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
function structuredText(value, limit, depthLimit) {
|
|
78
|
+
const pending = [{ value, depth: 1 }], pieces = [], active = new Set();
|
|
79
|
+
let bytes = 0;
|
|
80
|
+
function append(text) {
|
|
81
|
+
bytes += utf8ByteLength(text, limit - bytes);
|
|
82
|
+
if (bytes > limit) stop('resource_limit', 1, null);
|
|
83
|
+
pieces.push(text);
|
|
84
|
+
}
|
|
85
|
+
while (pending.length) {
|
|
86
|
+
const task = pending.pop();
|
|
87
|
+
if (task.frame) {
|
|
88
|
+
const { item, array, keys, index, depth } = task;
|
|
89
|
+
const length = array ? item.length : keys.length;
|
|
90
|
+
if (index === length) { append(array ? ']' : '}'); active.delete(item); continue; }
|
|
91
|
+
if (index) append(',');
|
|
92
|
+
const key = array ? index : keys[index];
|
|
93
|
+
if (!array) {
|
|
94
|
+
if (key.length > limit) stop('resource_limit', 1, null);
|
|
95
|
+
append(JSON.stringify(key)); append(':');
|
|
96
|
+
}
|
|
97
|
+
pending.push({ ...task, index: index + 1 }, { value: item[key], depth: depth + 1 });
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
const item = task.value;
|
|
101
|
+
if (item !== null && typeof item === 'object') {
|
|
102
|
+
if (task.depth > depthLimit) stop('resource_limit', 1, null);
|
|
103
|
+
if (active.has(item)) stop('invalid_operand', 2, null);
|
|
104
|
+
const array = Array.isArray(item);
|
|
105
|
+
append(array ? '[' : '{');
|
|
106
|
+
active.add(item);
|
|
107
|
+
pending.push({ frame: true, item, array, keys: array ? null : Object.keys(item), index: 0, depth: task.depth });
|
|
108
|
+
} else {
|
|
109
|
+
if (typeof item === 'string' && item.length > limit) stop('resource_limit', 1, null);
|
|
110
|
+
const encoded = JSON.stringify(item);
|
|
111
|
+
if (encoded === undefined) throw new TypeError('Structured ingress requires JSON values');
|
|
112
|
+
append(encoded);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
return pieces.join('');
|
|
116
|
+
}
|
|
117
|
+
function selection(input, materialize) {
|
|
118
|
+
for (const key of ['context', 'policy']) {
|
|
119
|
+
if (!Object.hasOwn(input, key)) {
|
|
120
|
+
if (key === 'policy' && materialize) stop('invalid_policy', 3, '/input/policy');
|
|
121
|
+
continue;
|
|
122
|
+
}
|
|
123
|
+
const v = input[key], p = '/input/' + key;
|
|
124
|
+
if (!record(v)) stop('invalid_policy', 3, p);
|
|
125
|
+
if (key === 'policy' && materialize) required(v, ['family'], p, 'invalid_policy', 3);
|
|
126
|
+
closed(v, key === 'policy' && materialize ? ['profile', 'family', 'zeroSign'] : ['profile'], p, 'invalid_policy', 3);
|
|
127
|
+
}
|
|
128
|
+
for (const key of ['context', 'policy']) {
|
|
129
|
+
if (!Object.hasOwn(input, key)) continue;
|
|
130
|
+
const v = input[key], p = '/input/' + key;
|
|
131
|
+
if (Object.hasOwn(v, 'profile') && !identifier(v.profile)) stop('invalid_policy', 3, p + '/profile');
|
|
132
|
+
if (key === 'policy' && materialize) {
|
|
133
|
+
if (!['integer', 'decimal', 'exponent'].includes(v.family)) stop('invalid_policy', 3, p + '/family');
|
|
134
|
+
if (Object.hasOwn(v, 'zeroSign') && !['positive', 'negative'].includes(v.zeroSign)) stop('invalid_policy', 3, p + '/zeroSign');
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
const policy = input.policy ?? {}, context = input.context ?? {};
|
|
138
|
+
const owner = Object.hasOwn(policy, 'profile') ? 'policy' : Object.hasOwn(context, 'profile') ? 'context' : null;
|
|
139
|
+
if (owner && input[owner].profile !== AEONIC_ARITHMETIC_PROFILE) stop('unsupported_profile', 3, '/input/' + owner + '/profile');
|
|
140
|
+
return { profile: AEONIC_ARITHMETIC_PROFILE, ...(materialize ? { family: policy.family, zeroSign: policy.zeroSign ?? 'positive' } : {}) };
|
|
141
|
+
}
|
|
142
|
+
const abs = (v) => v < 0n ? -v : v;
|
|
143
|
+
function bounds(c, e, limits, stage, path) {
|
|
144
|
+
if (c.replace('-', '').length > limits.maxCoefficientDigits || abs(e) > BigInt(limits.maxExponentMagnitude)) stop('resource_limit', stage, path);
|
|
145
|
+
}
|
|
146
|
+
function normalize(c, e) {
|
|
147
|
+
if (c === '0' || c === '-0') return { c: '0', e: 0n };
|
|
148
|
+
const trimmed = c.replace(/0+$/u, '');
|
|
149
|
+
return { c: trimmed, e: e + BigInt(c.length - trimmed.length) };
|
|
150
|
+
}
|
|
151
|
+
function operand(bundle, p, limits) {
|
|
152
|
+
if (!record(bundle)) stop('invalid_operand', 4, p);
|
|
153
|
+
required(bundle, ['number'], p, 'invalid_operand', 4);
|
|
154
|
+
const number = bundle.number, np = p + '/number';
|
|
155
|
+
if (!record(number)) stop('invalid_operand', 4, np);
|
|
156
|
+
if (!['finiteNumber', 'exactNumber'].includes(number.category) && !DEFERRED.has(number.category)) stop('invalid_operand', 4, np + '/category');
|
|
157
|
+
if (number.category === 'exactNumber') required(bundle, ['history'], p, 'invalid_operand', 4);
|
|
158
|
+
closed(bundle, ['number', 'history'], p, 'invalid_operand', 4);
|
|
159
|
+
const history = Object.hasOwn(bundle, 'history') ? bundle.history : HISTORY[0];
|
|
160
|
+
if (!HISTORY.includes(history)) stop('invalid_operand', 4, p + '/history');
|
|
161
|
+
if (DEFERRED.has(number.category)) return { deferred: true, history };
|
|
162
|
+
const fields = number.category === 'finiteNumber' ? ['value'] : ['coefficient', 'exponent'];
|
|
163
|
+
required(number, fields, np, 'invalid_operand', 4);
|
|
164
|
+
closed(number, ['category', ...fields], np, 'invalid_operand', 4);
|
|
165
|
+
let count = 0;
|
|
166
|
+
for (const k of fields) {
|
|
167
|
+
if (typeof number[k] !== 'string') stop('invalid_operand', 4, np + '/' + k);
|
|
168
|
+
for (const character of number[k]) {
|
|
169
|
+
if (++count > limits.maxNumericCharacters) stop('resource_limit', 4, np + '/' + k);
|
|
170
|
+
}
|
|
171
|
+
const valid = k === 'value' ? FINITE_NUMBER.test(number[k])
|
|
172
|
+
: k === 'coefficient' ? /^(?:0|-?[1-9](?:[0-9]*[1-9])?)$(?![\s\S])/u.test(number[k])
|
|
173
|
+
: /^(?:0|-?[1-9][0-9]*)$(?![\s\S])/u.test(number[k]);
|
|
174
|
+
if (!valid) stop('invalid_operand', 4, np + '/' + k);
|
|
175
|
+
}
|
|
176
|
+
let c, e;
|
|
177
|
+
if (number.category === 'exactNumber') {
|
|
178
|
+
c = number.coefficient; e = BigInt(number.exponent);
|
|
179
|
+
if (c === '0' && e !== 0n) stop('invalid_operand', 4, np + '/exponent');
|
|
180
|
+
if (c.replace('-', '').length > limits.maxCoefficientDigits) stop('resource_limit', 4, np + '/coefficient');
|
|
181
|
+
if (abs(e) > BigInt(limits.maxExponentMagnitude)) stop('resource_limit', 4, np + '/exponent');
|
|
182
|
+
} else {
|
|
183
|
+
const [mantissa, exponent = '0'] = number.value.toLowerCase().split('e');
|
|
184
|
+
e = BigInt(exponent);
|
|
185
|
+
const at = np + '/value';
|
|
186
|
+
if (abs(e) > BigInt(limits.maxExponentMagnitude)) stop('resource_limit', 4, at);
|
|
187
|
+
const negative = mantissa.startsWith('-');
|
|
188
|
+
const unsigned = mantissa.replace(/^[+-]/u, '');
|
|
189
|
+
const [integer, fraction = ''] = unsigned.split('.');
|
|
190
|
+
const digits = (integer + fraction).replace(/^0+/u, '') || '0';
|
|
191
|
+
({ c, e } = normalize((negative && digits !== '0' ? '-' : '') + digits, e - BigInt(fraction.length)));
|
|
192
|
+
bounds(c, e, limits, 4, at);
|
|
193
|
+
}
|
|
194
|
+
return { c, e, history };
|
|
195
|
+
}
|
|
196
|
+
function calculate(op, a, b, limits) {
|
|
197
|
+
let result;
|
|
198
|
+
const x = BigInt(a.c), y = BigInt(b.c);
|
|
199
|
+
if (op === 'multiply' && (x === 0n || y === 0n)) result = { c: '0', e: 0n };
|
|
200
|
+
else if (op !== 'multiply' && x === 0n) result = { c: (op === 'subtract' ? -y : y).toString(), e: b.e };
|
|
201
|
+
else if (op !== 'multiply' && y === 0n) result = { c: a.c, e: a.e };
|
|
202
|
+
else if (op !== 'multiply' && a.e === b.e && x === (op === 'subtract' ? y : -y)) result = { c: '0', e: 0n };
|
|
203
|
+
else if (op === 'multiply') {
|
|
204
|
+
if (BigInt(a.c.replace('-', '').length + b.c.replace('-', '').length) > BigInt(limits.maxWorkspaceDigits)) stop('resource_limit', 6, null);
|
|
205
|
+
result = normalize((x * y).toString(), a.e + b.e);
|
|
206
|
+
} else {
|
|
207
|
+
const e = a.e < b.e ? a.e : b.e;
|
|
208
|
+
for (const v of [a, b]) {
|
|
209
|
+
if (BigInt(v.c.replace('-', '').length) + v.e - e > BigInt(limits.maxWorkspaceDigits)) stop('resource_limit', 6, null);
|
|
210
|
+
}
|
|
211
|
+
const left = x * 10n ** (a.e - e), right = y * 10n ** (b.e - e);
|
|
212
|
+
result = normalize((op === 'add' ? left + right : left - right).toString(), e);
|
|
213
|
+
}
|
|
214
|
+
bounds(result.c, result.e, limits, 6, null);
|
|
215
|
+
return result;
|
|
216
|
+
}
|
|
217
|
+
function render(a, policy, limits) {
|
|
218
|
+
const { c, e } = a;
|
|
219
|
+
if (policy.family === 'integer' && c !== '0' && e < 0n) stop('unrepresentable_result', 7, null);
|
|
220
|
+
const negative = c.startsWith('-') || (c === '0' && policy.zeroSign === 'negative');
|
|
221
|
+
const digits = c.replace('-', ''), sign = negative ? '-' : '';
|
|
222
|
+
const width = BigInt(digits.length), point = width + e;
|
|
223
|
+
let length;
|
|
224
|
+
if (policy.family === 'exponent') length = width + 1n + BigInt(e.toString().length);
|
|
225
|
+
else if (policy.family === 'integer') length = width + e;
|
|
226
|
+
else length = e >= 0n ? width + e + 2n : point > 0n ? width + 1n : 2n - point + width;
|
|
227
|
+
if (length + BigInt(sign.length) > BigInt(limits.maxOutputCharacters)) stop('resource_limit', 7, null);
|
|
228
|
+
if (policy.family === 'exponent') return sign + digits + 'e' + e;
|
|
229
|
+
if (policy.family === 'integer') return sign + digits + '0'.repeat(Number(e));
|
|
230
|
+
if (e >= 0n) return sign + digits + '0'.repeat(Number(e)) + '.0';
|
|
231
|
+
if (point > 0n) return sign + digits.slice(0, Number(point)) + '.' + digits.slice(Number(point));
|
|
232
|
+
return sign + '0.' + '0'.repeat(Number(-point)) + digits;
|
|
233
|
+
}
|
|
234
|
+
function evaluate(request, limits) {
|
|
235
|
+
if (!record(request)) stop('invalid_operand', 2, null);
|
|
236
|
+
required(request, ['operation', 'input'], '', 'invalid_operand', 2);
|
|
237
|
+
if (!identifier(request.operation)) stop('invalid_operand', 2, '/operation');
|
|
238
|
+
if (!record(request.input)) stop('invalid_operand', 2, '/input');
|
|
239
|
+
closed(request, ['operation', 'input'], '', 'invalid_operand', 2);
|
|
240
|
+
const input = request.input;
|
|
241
|
+
closed(input, ['left', 'right', 'value', 'context', 'policy'], '/input', 'invalid_operand', 2);
|
|
242
|
+
if (!['add', 'subtract', 'multiply', 'materialize'].includes(request.operation)) stop('unsupported_operation', 2, '/operation');
|
|
243
|
+
const materialize = request.operation === 'materialize', keys = materialize ? ['value'] : ['left', 'right'];
|
|
244
|
+
required(input, keys, '/input', 'invalid_operand', 2);
|
|
245
|
+
closed(input, [...keys, 'context', 'policy'], '/input', 'invalid_operand', 2);
|
|
246
|
+
const policy = selection(input, materialize);
|
|
247
|
+
const operands = keys.map((key) => operand(input[key], '/input/' + key, limits));
|
|
248
|
+
for (const [i, value] of operands.entries()) if (value.deferred) stop('unsupported_domain', 5, '/input/' + keys[i] + '/number/category');
|
|
249
|
+
const history = operands.some((v) => v.history === HISTORY[1]) ? HISTORY[1] : HISTORY[0];
|
|
250
|
+
const number = materialize ? { category: 'finiteNumber', value: render(operands[0], policy, limits) }
|
|
251
|
+
: (() => { const v = calculate(request.operation, ...operands, limits); return { category: 'exactNumber', coefficient: v.c, exponent: v.e.toString() }; })();
|
|
252
|
+
return { outcome: 'value', value: { number, history }, metadata: { evaluation: 'exact-for-operands', effectivePolicy: policy } };
|
|
253
|
+
}
|
|
254
|
+
function guarded(action) {
|
|
255
|
+
try { return action(); } catch (e) { if (e instanceof Failure) return e.result; throw e; }
|
|
256
|
+
}
|
|
257
|
+
export function evaluateAeonicArithmetic(request, options = {}) {
|
|
258
|
+
const limits = configured(options);
|
|
259
|
+
return guarded(() => { admission(request, limits.maxRequestDepth); return evaluate(request, limits); });
|
|
260
|
+
}
|
|
261
|
+
export function evaluateAeonicArithmeticText(text, options = {}) {
|
|
262
|
+
if (!scalar(text)) throw new TypeError('requestText must be Unicode scalar text');
|
|
263
|
+
const limits = configured(options);
|
|
264
|
+
return guarded(() => {
|
|
265
|
+
if (utf8ByteLength(text, limits.maxRequestBytes) > limits.maxRequestBytes || exceedsJsonDepth(text, limits.maxRequestDepth)) stop('resource_limit', 1, null);
|
|
266
|
+
let request;
|
|
267
|
+
try { request = parseStrictJson(text); } catch (e) { if (e instanceof SyntaxError) stop('invalid_operand', 2, null); throw e; }
|
|
268
|
+
return evaluate(request, limits);
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
export function evaluateAeonicArithmeticStructuredJson(request, options = {}) {
|
|
272
|
+
const limits = configured(options);
|
|
273
|
+
return guarded(() => {
|
|
274
|
+
return evaluateAeonicArithmeticText(structuredText(request, limits.maxRequestBytes, limits.maxRequestDepth), options);
|
|
275
|
+
});
|
|
276
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
export const AEONIC_COMPARISON_BASELINE_PROFILE: 'aeonic.operations.comparison.baseline.v1';
|
|
2
|
+
export const AEONIC_COMPARISON_CODEPOINT_PROFILE: 'aeonic.operations.string.codepoint.v1';
|
|
3
|
+
|
|
4
|
+
export interface AeonicComparisonResourceLimits {
|
|
5
|
+
readonly maxRequestBytes: number;
|
|
6
|
+
readonly maxRequestDepth: number;
|
|
7
|
+
readonly maxNumericCharacters: number;
|
|
8
|
+
readonly maxStringScalars: number;
|
|
9
|
+
readonly maxSymbolScalars: number;
|
|
10
|
+
readonly maxDeclarations: number;
|
|
11
|
+
readonly maxDeclaredSymbols: number;
|
|
12
|
+
}
|
|
13
|
+
export const AEONIC_COMPARISON_DEFAULT_RESOURCE_LIMITS: Readonly<AeonicComparisonResourceLimits>;
|
|
14
|
+
export interface AeonicComparisonOptions {
|
|
15
|
+
readonly resourceLimits?: Partial<AeonicComparisonResourceLimits>;
|
|
16
|
+
}
|
|
17
|
+
export interface AeonicComparisonSymbol {
|
|
18
|
+
readonly category: 'symbol';
|
|
19
|
+
readonly value: string;
|
|
20
|
+
}
|
|
21
|
+
export type AeonicComparisonOperand =
|
|
22
|
+
| { readonly category: 'finiteNumber' | 'string'; readonly value: string }
|
|
23
|
+
| { readonly category: 'boolean'; readonly value: boolean }
|
|
24
|
+
| AeonicComparisonSymbol
|
|
25
|
+
| {
|
|
26
|
+
readonly category: 'positiveInfinity' | 'negativeInfinity' | 'nan' | 'explicitNull'
|
|
27
|
+
| 'explicitAbsence' | 'toggle' | 'hex' | 'radix' | 'encoding' | 'separator'
|
|
28
|
+
| 'sansaAddress' | 'referenceForm' | 'temporal' | 'container';
|
|
29
|
+
readonly [field: string]: unknown;
|
|
30
|
+
};
|
|
31
|
+
export interface AeonicComparisonDeclaration {
|
|
32
|
+
readonly id: string;
|
|
33
|
+
readonly version: string;
|
|
34
|
+
readonly order: readonly AeonicComparisonSymbol[];
|
|
35
|
+
}
|
|
36
|
+
export type AeonicComparisonSymbolSelection =
|
|
37
|
+
| { readonly mode: 'string-profile'; readonly profile: string }
|
|
38
|
+
| {
|
|
39
|
+
readonly mode: 'declared-order';
|
|
40
|
+
readonly declaration: { readonly order: readonly AeonicComparisonSymbol[] }
|
|
41
|
+
| { readonly reference: { readonly id: string; readonly version: string } };
|
|
42
|
+
};
|
|
43
|
+
export interface AeonicComparisonPolicy {
|
|
44
|
+
readonly profile?: string;
|
|
45
|
+
readonly strings?: { readonly profile: string };
|
|
46
|
+
readonly symbols?: AeonicComparisonSymbolSelection;
|
|
47
|
+
}
|
|
48
|
+
export interface AeonicComparisonContext extends AeonicComparisonPolicy {
|
|
49
|
+
readonly declarations?: readonly AeonicComparisonDeclaration[];
|
|
50
|
+
}
|
|
51
|
+
export interface AeonicComparisonRequest {
|
|
52
|
+
readonly operation: 'equal' | 'compare';
|
|
53
|
+
readonly input: {
|
|
54
|
+
readonly left: AeonicComparisonOperand;
|
|
55
|
+
readonly right: AeonicComparisonOperand;
|
|
56
|
+
readonly policy?: AeonicComparisonPolicy;
|
|
57
|
+
readonly context?: AeonicComparisonContext;
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
export type AeonicComparisonDiagnosticReason = 'invalid_operand' | 'unsupported_domain'
|
|
61
|
+
| 'incompatible_comparison' | 'unsupported_operation' | 'unsupported_profile'
|
|
62
|
+
| 'invalid_policy' | 'undeclared_symbol' | 'resource_limit';
|
|
63
|
+
export type AeonicComparisonResult =
|
|
64
|
+
| {
|
|
65
|
+
readonly outcome: 'value';
|
|
66
|
+
readonly value: { readonly category: 'symbol'; readonly value: 'equal' | 'notEqual' | 'less' | 'greater' };
|
|
67
|
+
readonly metadata: {
|
|
68
|
+
readonly effectivePolicy: {
|
|
69
|
+
readonly profile: typeof AEONIC_COMPARISON_BASELINE_PROFILE;
|
|
70
|
+
readonly domain: 'finiteNumber' | 'string' | 'boolean' | 'symbol';
|
|
71
|
+
readonly comparison: 'exact-numeric' | 'boolean' | 'string-profile';
|
|
72
|
+
readonly strings: { readonly profile: typeof AEONIC_COMPARISON_CODEPOINT_PROFILE };
|
|
73
|
+
readonly symbols: { readonly mode: 'string-profile'; readonly profile: typeof AEONIC_COMPARISON_CODEPOINT_PROFILE };
|
|
74
|
+
};
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
| {
|
|
78
|
+
readonly outcome: 'diagnostic';
|
|
79
|
+
readonly reason: AeonicComparisonDiagnosticReason;
|
|
80
|
+
readonly context: { readonly stage: 1 | 2 | 3 | 4 | 5 | 6 | 7; readonly path: string | null };
|
|
81
|
+
readonly message?: string;
|
|
82
|
+
};
|
|
83
|
+
/** Typed logical operands; no JSON serialization or implicit numeric coercion. */
|
|
84
|
+
export function evaluateAeonicComparison(request: AeonicComparisonRequest, options?: AeonicComparisonOptions): AeonicComparisonResult;
|
|
85
|
+
/** Exact JSON ingress, with byte/depth admission and duplicate-member rejection. */
|
|
86
|
+
export function evaluateAeonicComparisonText(requestText: string, options?: AeonicComparisonOptions): AeonicComparisonResult;
|