fatedb 0.0.0-stage → 0.10.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.
Files changed (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +264 -2
  3. package/dist/bin.d.ts +2 -0
  4. package/dist/bin.js +3 -0
  5. package/dist/cli.d.ts +15 -0
  6. package/dist/cli.js +256 -0
  7. package/dist/client.d.ts +152 -0
  8. package/dist/client.js +416 -0
  9. package/dist/cloudflare.d.ts +197 -0
  10. package/dist/cloudflare.js +159 -0
  11. package/dist/datalog/ast.d.ts +35 -0
  12. package/dist/datalog/ast.js +40 -0
  13. package/dist/datalog/evaluator.d.ts +14 -0
  14. package/dist/datalog/evaluator.js +395 -0
  15. package/dist/datalog/fact-source.d.ts +30 -0
  16. package/dist/datalog/fact-source.js +1 -0
  17. package/dist/datalog/fingerprint.d.ts +12 -0
  18. package/dist/datalog/fingerprint.js +50 -0
  19. package/dist/datalog/parser.d.ts +3 -0
  20. package/dist/datalog/parser.js +302 -0
  21. package/dist/datalog/value.d.ts +34 -0
  22. package/dist/datalog/value.js +104 -0
  23. package/dist/domain/date-validation.d.ts +2 -0
  24. package/dist/domain/date-validation.js +32 -0
  25. package/dist/domain/fact-value.d.ts +91 -0
  26. package/dist/domain/fact-value.js +167 -0
  27. package/dist/domain/fact.d.ts +14 -0
  28. package/dist/domain/fact.js +47 -0
  29. package/dist/domain/failure.d.ts +44 -0
  30. package/dist/domain/failure.js +30 -0
  31. package/dist/domain/graph-id.d.ts +7 -0
  32. package/dist/domain/graph-id.js +10 -0
  33. package/dist/domain/histogram.d.ts +29 -0
  34. package/dist/domain/histogram.js +48 -0
  35. package/dist/domain/identifiers.d.ts +26 -0
  36. package/dist/domain/identifiers.js +75 -0
  37. package/dist/domain/numbers.d.ts +12 -0
  38. package/dist/domain/numbers.js +77 -0
  39. package/dist/domain/projection.d.ts +252 -0
  40. package/dist/domain/projection.js +51 -0
  41. package/dist/domain/query-metrics.d.ts +31 -0
  42. package/dist/domain/query-metrics.js +35 -0
  43. package/dist/domain/read-token.d.ts +37 -0
  44. package/dist/domain/read-token.js +93 -0
  45. package/dist/domain/result.d.ts +22 -0
  46. package/dist/domain/result.js +16 -0
  47. package/dist/domain/schema-observation.d.ts +20 -0
  48. package/dist/domain/schema-observation.js +61 -0
  49. package/dist/domain/string-order.d.ts +2 -0
  50. package/dist/domain/string-order.js +15 -0
  51. package/dist/domain/vocabulary.d.ts +101 -0
  52. package/dist/domain/vocabulary.js +276 -0
  53. package/dist/index.d.ts +15 -0
  54. package/dist/index.js +14 -0
  55. package/dist/projection-config.d.ts +3 -0
  56. package/dist/projection-config.js +212 -0
  57. package/dist/server/access.d.ts +32 -0
  58. package/dist/server/access.js +117 -0
  59. package/dist/server/admin.d.ts +233 -0
  60. package/dist/server/admin.js +483 -0
  61. package/dist/server/authorization.d.ts +35 -0
  62. package/dist/server/authorization.js +76 -0
  63. package/dist/server/console-assets.d.ts +6 -0
  64. package/dist/server/console-assets.js +2 -0
  65. package/dist/server/console.d.ts +8 -0
  66. package/dist/server/console.js +301 -0
  67. package/dist/server/index.d.ts +122 -0
  68. package/dist/server/index.js +487 -0
  69. package/dist/server/mcp.d.ts +31 -0
  70. package/dist/server/mcp.js +169 -0
  71. package/dist/server/telemetry-do.d.ts +31 -0
  72. package/dist/server/telemetry-do.js +342 -0
  73. package/dist/server/telemetry.d.ts +27 -0
  74. package/dist/server/telemetry.js +191 -0
  75. package/dist/storage/constants.d.ts +20 -0
  76. package/dist/storage/constants.js +21 -0
  77. package/dist/storage/environment.d.ts +438 -0
  78. package/dist/storage/environment.js +145 -0
  79. package/dist/storage/facts.d.ts +41 -0
  80. package/dist/storage/facts.js +73 -0
  81. package/dist/storage/http.d.ts +55 -0
  82. package/dist/storage/http.js +169 -0
  83. package/dist/storage/keys.d.ts +50 -0
  84. package/dist/storage/keys.js +84 -0
  85. package/dist/storage/layout.d.ts +67 -0
  86. package/dist/storage/layout.js +134 -0
  87. package/dist/storage/log.d.ts +41 -0
  88. package/dist/storage/log.js +137 -0
  89. package/dist/storage/manifest.d.ts +26 -0
  90. package/dist/storage/manifest.js +206 -0
  91. package/dist/storage/operations.d.ts +303 -0
  92. package/dist/storage/operations.js +719 -0
  93. package/dist/storage/partition.d.ts +125 -0
  94. package/dist/storage/partition.js +816 -0
  95. package/dist/storage/projection.d.ts +72 -0
  96. package/dist/storage/projection.js +1349 -0
  97. package/dist/storage/root.d.ts +120 -0
  98. package/dist/storage/root.js +596 -0
  99. package/dist/storage/segment.d.ts +145 -0
  100. package/dist/storage/segment.js +451 -0
  101. package/dist/storage/shard.d.ts +82 -0
  102. package/dist/storage/shard.js +710 -0
  103. package/dist/storage/source.d.ts +60 -0
  104. package/dist/storage/source.js +199 -0
  105. package/dist/telemetry/model.d.ts +123 -0
  106. package/dist/telemetry/model.js +292 -0
  107. package/dist/version.d.ts +4 -0
  108. package/dist/version.js +6 -0
  109. package/package.json +82 -4
@@ -0,0 +1,167 @@
1
+ // A fact's value: tagged with its type, in one canonical form per value, as storage keeps it and
2
+ // JSON carries it (RFD0014). Writes may give a value's payload as the JavaScript value that holds it,
3
+ // such as a bigint or a Date; the typed API returns each value as that JavaScript value (`toValue`).
4
+ // A value's type is its own: no schema changes how it is stored or returned (RFD0013).
5
+ import { isCalendarDate, isRfc3339Timestamp } from "./date-validation.js";
6
+ import { parseDecimal, parseInteger } from "./numbers.js";
7
+ import { compareUnicodeScalars } from "./string-order.js";
8
+ import { parseUri } from "./identifiers.js";
9
+ import { isRecord, parsed, rejected } from "./result.js";
10
+ export function toValue(value) {
11
+ switch (value.type) {
12
+ case "null":
13
+ return null;
14
+ case "text":
15
+ case "reference":
16
+ case "decimal":
17
+ return value.value;
18
+ case "number":
19
+ return BigInt(value.value);
20
+ case "boolean":
21
+ return value.value;
22
+ case "date":
23
+ return new Date(`${value.value}T00:00:00.000Z`);
24
+ case "date_time":
25
+ return new Date(value.value);
26
+ case "bytes":
27
+ return Uint8Array.from(value.value);
28
+ case "list":
29
+ return value.value.map(toValue);
30
+ case "map": {
31
+ const pairs = [];
32
+ for (const [key, item] of Object.entries(value.value))
33
+ pairs.push([key, toValue(item)]);
34
+ return Object.fromEntries(pairs);
35
+ }
36
+ }
37
+ }
38
+ const MAX_VALUE_DEPTH = 64;
39
+ /** Instants and dates are kept from the year 0000 to 9999 in UTC, where their text sorts in time order. */
40
+ const FIRST_INSTANT = Date.parse("0000-01-01T00:00:00.000Z");
41
+ const LAST_INSTANT = Date.parse("9999-12-31T23:59:59.999Z");
42
+ export function parseFactValue(input, path = "value") {
43
+ return parseAtDepth(input, path, 0);
44
+ }
45
+ function parseAtDepth(input, path, depth) {
46
+ if (depth > MAX_VALUE_DEPTH) {
47
+ return rejected(path, `fact values cannot be nested more than ${MAX_VALUE_DEPTH} levels`);
48
+ }
49
+ if (!isRecord(input) || typeof input["type"] !== "string") {
50
+ return rejected(path, "expected a tagged fact value");
51
+ }
52
+ switch (input["type"]) {
53
+ case "null":
54
+ if (input["value"] !== undefined && input["value"] !== null) {
55
+ return rejected(`${path}.value`, "null values cannot carry a payload");
56
+ }
57
+ return parsed(Object.freeze({ type: "null" }));
58
+ case "text":
59
+ return typeof input["value"] === "string"
60
+ ? parsed(Object.freeze({ type: "text", value: input["value"] }))
61
+ : rejected(`${path}.value`, "expected a string for text");
62
+ case "number": {
63
+ const number = parseInteger(input["value"], `${path}.value`);
64
+ return number.ok
65
+ ? parsed(Object.freeze({ type: "number", value: number.value }))
66
+ : number;
67
+ }
68
+ case "decimal": {
69
+ const decimal = parseDecimal(input["value"], `${path}.value`);
70
+ return decimal.ok
71
+ ? parsed(Object.freeze({ type: "decimal", value: decimal.value }))
72
+ : decimal;
73
+ }
74
+ case "boolean":
75
+ return typeof input["value"] === "boolean"
76
+ ? parsed(Object.freeze({ type: "boolean", value: input["value"] }))
77
+ : rejected(`${path}.value`, "expected a boolean");
78
+ case "bytes":
79
+ return parseBytes(input["value"], `${path}.value`);
80
+ case "reference": {
81
+ const uri = parseUri(input["value"], `${path}.value`);
82
+ return uri.ok
83
+ ? parsed(Object.freeze({ type: "reference", value: uri.value }))
84
+ : uri;
85
+ }
86
+ case "date":
87
+ return parseDate(input["value"], `${path}.value`);
88
+ case "date_time":
89
+ return parseDateTime(input["value"], `${path}.value`);
90
+ case "list":
91
+ return parseList(input["value"], `${path}.value`, depth);
92
+ case "map":
93
+ return parseMap(input["value"], `${path}.value`, depth);
94
+ default:
95
+ return rejected(`${path}.type`, `unsupported fact value tag: ${input["type"]}`);
96
+ }
97
+ }
98
+ function parseBytes(input, path) {
99
+ if (input instanceof Uint8Array) {
100
+ return parsed(Object.freeze({ type: "bytes", value: Object.freeze(Array.from(input)) }));
101
+ }
102
+ if (!Array.isArray(input)) {
103
+ return rejected(path, "expected a Uint8Array or an array of byte values");
104
+ }
105
+ const bytes = [];
106
+ for (const [index, byte] of input.entries()) {
107
+ if (typeof byte !== "number" || !Number.isInteger(byte) || byte < 0 || byte > 255) {
108
+ return rejected(`${path}[${index}]`, "expected an integer between 0 and 255");
109
+ }
110
+ bytes.push(byte);
111
+ }
112
+ return parsed(Object.freeze({ type: "bytes", value: Object.freeze(bytes) }));
113
+ }
114
+ /** A calendar date; from a Date, its day in UTC. */
115
+ function parseDate(input, path) {
116
+ if (input instanceof Date) {
117
+ const instant = input.getTime();
118
+ if (!(instant >= FIRST_INSTANT && instant <= LAST_INSTANT))
119
+ return rejected(path, "expected a valid Date from the year 0000 to 9999 in UTC");
120
+ return parsed(Object.freeze({ type: "date", value: new Date(instant).toISOString().slice(0, 10) }));
121
+ }
122
+ if (typeof input !== "string" || !isCalendarDate(input)) {
123
+ return rejected(path, "expected a Date, or a valid calendar date in YYYY-MM-DD form");
124
+ }
125
+ return parsed(Object.freeze({ type: "date", value: input }));
126
+ }
127
+ /**
128
+ * An instant, kept in UTC to the millisecond, as a Date holds it: a Date read back writes back as
129
+ * the same value. The offset a timestamp was written with, and digits below a millisecond, are not kept.
130
+ */
131
+ function parseDateTime(input, path) {
132
+ const instant = input instanceof Date ? input.getTime() : typeof input === "string" && isRfc3339Timestamp(input) ? Date.parse(input) : Number.NaN;
133
+ if (Number.isNaN(instant)) {
134
+ return rejected(path, 'expected a Date, or an RFC 3339 timestamp with a timezone, such as "1997-07-22T09:00:00+09:00"');
135
+ }
136
+ if (!(instant >= FIRST_INSTANT && instant <= LAST_INSTANT))
137
+ return rejected(path, "expected an instant from the year 0000 to 9999 in UTC");
138
+ return parsed(Object.freeze({ type: "date_time", value: new Date(instant).toISOString() }));
139
+ }
140
+ function parseList(input, path, depth) {
141
+ if (!Array.isArray(input)) {
142
+ return rejected(path, "expected an array of fact values");
143
+ }
144
+ const values = [];
145
+ for (const [index, item] of input.entries()) {
146
+ const value = parseAtDepth(item, `${path}[${index}]`, depth + 1);
147
+ if (!value.ok)
148
+ return value;
149
+ values.push(value.value);
150
+ }
151
+ return parsed(Object.freeze({ type: "list", value: Object.freeze(values) }));
152
+ }
153
+ function parseMap(input, path, depth) {
154
+ if (!isRecord(input)) {
155
+ return rejected(path, "expected an object of fact values");
156
+ }
157
+ const entries = Object.entries(input).sort(([left], [right]) => compareUnicodeScalars(left, right));
158
+ const pairs = [];
159
+ for (const [key, item] of entries) {
160
+ const value = parseAtDepth(item, `${path}.${key}`, depth + 1);
161
+ if (!value.ok)
162
+ return value;
163
+ pairs.push([key, value.value]);
164
+ }
165
+ const values = Object.fromEntries(pairs);
166
+ return parsed(Object.freeze({ type: "map", value: Object.freeze(values) }));
167
+ }
@@ -0,0 +1,14 @@
1
+ import { type Uri } from "./identifiers.js";
2
+ import { type FactValue } from "./fact-value.js";
3
+ import { type ParseResult } from "./result.js";
4
+ export type FactDraft = Readonly<{
5
+ source: Uri;
6
+ entity: Uri;
7
+ field: Uri;
8
+ value: FactValue;
9
+ retraction: boolean;
10
+ }>;
11
+ export type NonEmptyReadonlyArray<T> = readonly [T, ...T[]];
12
+ export declare function parseFactDraft(input: unknown, path?: string): ParseResult<FactDraft>;
13
+ /** A transaction's facts: a non-empty list, each parsed, where a missing `retraction` asserts. */
14
+ export declare function parseFactDrafts(input: unknown, path?: string): ParseResult<NonEmptyReadonlyArray<FactDraft>>;
@@ -0,0 +1,47 @@
1
+ import { parseUri } from "./identifiers.js";
2
+ import { parseFactValue } from "./fact-value.js";
3
+ import { isRecord, parsed, rejected } from "./result.js";
4
+ export function parseFactDraft(input, path = "fact") {
5
+ if (!isRecord(input))
6
+ return rejected(path, "expected a fact object");
7
+ const source = parseUri(input["source"], `${path}.source`);
8
+ if (!source.ok)
9
+ return source;
10
+ const entity = parseUri(input["entity"], `${path}.entity`);
11
+ if (!entity.ok)
12
+ return entity;
13
+ const field = parseUri(input["field"], `${path}.field`);
14
+ if (!field.ok)
15
+ return field;
16
+ const value = parseFactValue(input["value"], `${path}.value`);
17
+ if (!value.ok)
18
+ return value;
19
+ if (typeof input["retraction"] !== "boolean") {
20
+ return rejected(`${path}.retraction`, "expected a boolean");
21
+ }
22
+ return parsed(Object.freeze({
23
+ source: source.value,
24
+ entity: entity.value,
25
+ field: field.value,
26
+ value: value.value,
27
+ retraction: input["retraction"],
28
+ }));
29
+ }
30
+ /** A transaction's facts: a non-empty list, each parsed, where a missing `retraction` asserts. */
31
+ export function parseFactDrafts(input, path = "facts") {
32
+ if (!Array.isArray(input) || input.length === 0)
33
+ return rejected(path, "expected a non-empty array of facts");
34
+ const facts = [];
35
+ for (const [index, raw] of input.entries()) {
36
+ const withDefault = isRecord(raw) && raw["retraction"] === undefined ? { ...raw, retraction: false } : raw;
37
+ const fact = parseFactDraft(withDefault, `${path}[${index}]`);
38
+ if (!fact.ok)
39
+ return fact;
40
+ facts.push(fact.value);
41
+ }
42
+ const [first, ...rest] = facts;
43
+ if (first === undefined)
44
+ return rejected(path, "expected a non-empty array of facts");
45
+ const frozen = Object.freeze([first, ...rest]);
46
+ return parsed(frozen);
47
+ }
@@ -0,0 +1,44 @@
1
+ import type { ParseError } from "./result.js";
2
+ /** The request cannot be right, and fails the same way again: it may say where (`path`, `offset`). */
3
+ type Invalid = Readonly<{
4
+ kind: "invalid";
5
+ message: string;
6
+ path?: string;
7
+ offset?: number;
8
+ }>;
9
+ /** The app's grants do not allow it. */
10
+ type Denied = Readonly<{
11
+ kind: "denied";
12
+ message: string;
13
+ }>;
14
+ /** Past a limit: split the write, or narrow the query. */
15
+ type TooLarge = Readonly<{
16
+ kind: "too-large";
17
+ message: string;
18
+ }>;
19
+ /** The client request token was used with different facts. */
20
+ type Conflict = Readonly<{
21
+ kind: "conflict";
22
+ message: string;
23
+ }>;
24
+ /**
25
+ * Try again later, after `retryAfter` seconds if given. A write may have been stored: replay it
26
+ * with the same client request token and facts, and it is stored once.
27
+ */
28
+ type Unavailable = Readonly<{
29
+ kind: "unavailable";
30
+ message: string;
31
+ retryAfter?: number;
32
+ }>;
33
+ export type ReadFailure = Invalid | Denied | TooLarge | Unavailable;
34
+ export type WriteFailure = ReadFailure | Conflict;
35
+ export type Operation = "read" | "write";
36
+ export declare function invalid(error: ParseError): ReadFailure;
37
+ export declare function denied(message: string): ReadFailure;
38
+ /** A failure that is no fault of the request: the graph could not answer, or not as the API does. */
39
+ export declare function unavailable(operation: Operation, message: string, retryAfter?: number): ReadFailure;
40
+ /** An HTTP answer that is not a success, as the instance's routes give it (storage/http.ts). */
41
+ export declare function httpFailure(operation: Operation, status: number, message: string, retryAfter: string | null): WriteFailure;
42
+ /** A failure a read can have: a conflict is a write's. */
43
+ export declare function forRead(failure: WriteFailure): ReadFailure;
44
+ export {};
@@ -0,0 +1,30 @@
1
+ export function invalid(error) {
2
+ return { kind: "invalid", message: error.message, path: error.path, ...(error.offset === undefined ? {} : { offset: error.offset }) };
3
+ }
4
+ export function denied(message) {
5
+ return { kind: "denied", message };
6
+ }
7
+ /** A failure that is no fault of the request: the graph could not answer, or not as the API does. */
8
+ export function unavailable(operation, message, retryAfter) {
9
+ const said = operation === "write" ? `${message}; the write may have been stored: replay it with the same client request token and facts` : message;
10
+ return { kind: "unavailable", message: said, ...(retryAfter === undefined ? {} : { retryAfter }) };
11
+ }
12
+ /** An HTTP answer that is not a success, as the instance's routes give it (storage/http.ts). */
13
+ export function httpFailure(operation, status, message, retryAfter) {
14
+ if (status === 401 || status === 403)
15
+ return { kind: "denied", message };
16
+ if (status === 409)
17
+ return operation === "write" ? { kind: "conflict", message } : { kind: "invalid", message };
18
+ if (status === 413)
19
+ return { kind: "too-large", message };
20
+ if (status === 429 || status >= 500) {
21
+ const seconds = retryAfter !== null && /^[0-9]{1,6}$/.test(retryAfter) ? Number(retryAfter) : undefined;
22
+ // The instance's own 5xx messages already say what to do with a write.
23
+ return { kind: "unavailable", message, ...(seconds === undefined ? {} : { retryAfter: seconds }) };
24
+ }
25
+ return { kind: "invalid", message };
26
+ }
27
+ /** A failure a read can have: a conflict is a write's. */
28
+ export function forRead(failure) {
29
+ return failure.kind === "conflict" ? { kind: "invalid", message: failure.message } : failure;
30
+ }
@@ -0,0 +1,7 @@
1
+ import { type ParseResult } from "./result.js";
2
+ declare const graphIdBrand: unique symbol;
3
+ export type GraphId = string & {
4
+ readonly [graphIdBrand]: "GraphId";
5
+ };
6
+ export declare function parseGraphId(input: unknown, path?: string): ParseResult<GraphId>;
7
+ export {};
@@ -0,0 +1,10 @@
1
+ import { parsed, rejected } from "./result.js";
2
+ function isGraphId(input) {
3
+ return typeof input === "string" && /^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/.test(input);
4
+ }
5
+ export function parseGraphId(input, path = "graphId") {
6
+ if (!isGraphId(input)) {
7
+ return rejected(path, "expected a lowercase graph ID using letters, digits, and hyphens");
8
+ }
9
+ return parsed(input);
10
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Latency histogram with 1 ms buckets. Stored sparsely (only non-empty buckets), so the results of
3
+ * thousands of drivers stay small enough to gather and merge.
4
+ */
5
+ export declare const MAX_BUCKET_MS = 120000;
6
+ export interface HistogramData {
7
+ /**
8
+ * Pairs of [bucket in whole milliseconds, count], sorted by bucket; the last bucket holds 120 s
9
+ * and above. Typed as plain arrays because RPC serialization doesn't preserve tuple types.
10
+ */
11
+ readonly buckets: readonly (readonly number[])[];
12
+ /** The largest latency observed, unbucketed. */
13
+ readonly maxMs: number;
14
+ }
15
+ export interface Latency {
16
+ readonly p50: number;
17
+ readonly p95: number;
18
+ readonly p99: number;
19
+ readonly max: number;
20
+ }
21
+ export declare class Histogram {
22
+ private readonly counts;
23
+ private maxMs;
24
+ record(ms: number): void;
25
+ merge(other: HistogramData): void;
26
+ toData(): HistogramData;
27
+ }
28
+ /** Percentiles are bucket estimates (1 ms resolution); max is exact. Zero samples gives zeros. */
29
+ export declare function latencyOf(data: HistogramData): Latency;
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Latency histogram with 1 ms buckets. Stored sparsely (only non-empty buckets), so the results of
3
+ * thousands of drivers stay small enough to gather and merge.
4
+ */
5
+ export const MAX_BUCKET_MS = 120_000;
6
+ export class Histogram {
7
+ counts = new Map();
8
+ maxMs = 0;
9
+ record(ms) {
10
+ if (!Number.isFinite(ms))
11
+ return;
12
+ const clamped = Math.max(0, ms);
13
+ const bucket = Math.min(MAX_BUCKET_MS, Math.floor(clamped));
14
+ this.counts.set(bucket, (this.counts.get(bucket) ?? 0) + 1);
15
+ if (clamped > this.maxMs)
16
+ this.maxMs = clamped;
17
+ }
18
+ merge(other) {
19
+ for (const [bucket = 0, count = 0] of other.buckets) {
20
+ if (!Number.isFinite(bucket) || !Number.isFinite(count) || count <= 0)
21
+ continue;
22
+ const clampedBucket = Math.min(MAX_BUCKET_MS, Math.max(0, Math.floor(bucket)));
23
+ this.counts.set(clampedBucket, (this.counts.get(clampedBucket) ?? 0) + count);
24
+ }
25
+ if (Number.isFinite(other.maxMs) && other.maxMs > this.maxMs)
26
+ this.maxMs = other.maxMs;
27
+ }
28
+ toData() {
29
+ return { buckets: [...this.counts].sort((a, b) => a[0] - b[0]), maxMs: this.maxMs };
30
+ }
31
+ }
32
+ /** Percentiles are bucket estimates (1 ms resolution); max is exact. Zero samples gives zeros. */
33
+ export function latencyOf(data) {
34
+ const total = data.buckets.reduce((sum, [, count = 0]) => sum + count, 0);
35
+ const at = (p) => {
36
+ if (total === 0)
37
+ return 0;
38
+ const rank = Math.ceil(p * total);
39
+ let seen = 0;
40
+ for (const [bucket = 0, count = 0] of data.buckets) {
41
+ seen += count;
42
+ if (seen >= rank)
43
+ return bucket;
44
+ }
45
+ return data.buckets.at(-1)?.[0] ?? 0;
46
+ };
47
+ return { p50: at(0.5), p95: at(0.95), p99: at(0.99), max: Math.round(data.maxMs * 100) / 100 };
48
+ }
@@ -0,0 +1,26 @@
1
+ import { type ParseResult } from "./result.js";
2
+ declare const uriBrand: unique symbol;
3
+ declare const transactionIdBrand: unique symbol;
4
+ declare const clientRequestTokenBrand: unique symbol;
5
+ export type Uri = string & {
6
+ readonly [uriBrand]: "Uri";
7
+ };
8
+ export type TransactionId = Uri & {
9
+ readonly [transactionIdBrand]: "TransactionId";
10
+ };
11
+ export type ClientRequestToken = string & {
12
+ readonly [clientRequestTokenBrand]: "ClientRequestToken";
13
+ };
14
+ export declare const MAX_URI_LENGTH = 2048;
15
+ export declare const MAX_TRANSACTION_ID_BYTES = 256;
16
+ export declare const MAX_CLIENT_REQUEST_TOKEN_BYTES = 256;
17
+ export declare function parseUri(input: unknown, path?: string): ParseResult<Uri>;
18
+ export declare function parseTransactionId(input: unknown, path?: string): ParseResult<TransactionId>;
19
+ export declare function parseClientRequestToken(input: unknown, path?: string): ParseResult<ClientRequestToken>;
20
+ /** Base62 digits of a 128-bit id at fixed width: 62^22 > 2^128, and fixed width sorts like the number. */
21
+ export declare const BASE62_ID_LENGTH = 22;
22
+ /** A 128-bit id (16 bytes, such as a UUID) in fixed-width base62, in the alphabet's ASCII order. */
23
+ export declare function encodeBase62Id(bytes: Uint8Array): string;
24
+ /** A new transaction id, `fatedb:tx:` and 22 base62 digits of a random 128-bit id. */
25
+ export declare function newTransactionId(): TransactionId;
26
+ export {};
@@ -0,0 +1,75 @@
1
+ import { parsed, rejected } from "./result.js";
2
+ export const MAX_URI_LENGTH = 2_048;
3
+ export const MAX_TRANSACTION_ID_BYTES = 256;
4
+ export const MAX_CLIENT_REQUEST_TOKEN_BYTES = 256;
5
+ function isCanonicalUri(value) {
6
+ return value.length > 0 && value.length <= MAX_URI_LENGTH;
7
+ }
8
+ function isTransactionUri(value) {
9
+ return new TextEncoder().encode(value).byteLength <= MAX_TRANSACTION_ID_BYTES;
10
+ }
11
+ function isClientRequestToken(value) {
12
+ return value.length > 0 && new TextEncoder().encode(value).byteLength <= MAX_CLIENT_REQUEST_TOKEN_BYTES;
13
+ }
14
+ export function parseUri(input, path = "uri") {
15
+ if (typeof input !== "string" || input.length === 0) {
16
+ return rejected(path, "expected a non-empty URI string");
17
+ }
18
+ if (input.length > MAX_URI_LENGTH) {
19
+ return rejected(path, `URI cannot exceed ${MAX_URI_LENGTH} characters`);
20
+ }
21
+ try {
22
+ const href = new URL(input).href;
23
+ if (!isCanonicalUri(href))
24
+ return rejected(path, `URI cannot exceed ${MAX_URI_LENGTH} characters`);
25
+ return parsed(href);
26
+ }
27
+ catch {
28
+ return rejected(path, "expected an absolute URI with a scheme");
29
+ }
30
+ }
31
+ export function parseTransactionId(input, path = "txId") {
32
+ if (typeof input === "string" && new TextEncoder().encode(input).byteLength > MAX_TRANSACTION_ID_BYTES) {
33
+ return rejected(path, `transaction ID cannot exceed ${MAX_TRANSACTION_ID_BYTES} UTF-8 bytes`);
34
+ }
35
+ const uri = parseUri(input, path);
36
+ if (!uri.ok)
37
+ return uri;
38
+ if (!isTransactionUri(uri.value)) {
39
+ return rejected(path, `transaction ID cannot exceed ${MAX_TRANSACTION_ID_BYTES} UTF-8 bytes`);
40
+ }
41
+ return parsed(uri.value);
42
+ }
43
+ export function parseClientRequestToken(input, path = "clientRequestToken") {
44
+ if (typeof input !== "string" || input.length === 0) {
45
+ return rejected(path, "expected a non-empty client request token");
46
+ }
47
+ if (!isClientRequestToken(input)) {
48
+ return rejected(path, `client request token cannot exceed ${MAX_CLIENT_REQUEST_TOKEN_BYTES} UTF-8 bytes`);
49
+ }
50
+ return parsed(input);
51
+ }
52
+ const BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
53
+ /** Base62 digits of a 128-bit id at fixed width: 62^22 > 2^128, and fixed width sorts like the number. */
54
+ export const BASE62_ID_LENGTH = 22;
55
+ /** A 128-bit id (16 bytes, such as a UUID) in fixed-width base62, in the alphabet's ASCII order. */
56
+ export function encodeBase62Id(bytes) {
57
+ if (bytes.byteLength !== 16)
58
+ throw new RangeError("a base62 id encodes exactly 16 bytes");
59
+ let value = 0n;
60
+ for (const byte of bytes)
61
+ value = (value << 8n) | BigInt(byte);
62
+ let digits = "";
63
+ for (let i = 0; i < BASE62_ID_LENGTH; i++) {
64
+ digits = (BASE62[Number(value % 62n)] ?? "0") + digits;
65
+ value /= 62n;
66
+ }
67
+ return digits;
68
+ }
69
+ /** A new transaction id, `fatedb:tx:` and 22 base62 digits of a random 128-bit id. */
70
+ export function newTransactionId() {
71
+ const generated = parseTransactionId(`fatedb:tx:${encodeBase62Id(crypto.getRandomValues(new Uint8Array(16)))}`);
72
+ if (!generated.ok)
73
+ throw new Error(generated.error.message);
74
+ return generated.value;
75
+ }
@@ -0,0 +1,12 @@
1
+ import { type ParseResult } from "./result.js";
2
+ /**
3
+ * Digits a decimal may have once written out. A transaction's facts are at most 1,000,000 bytes of
4
+ * JSON anyway; the bound stops "1e999999999" from being written out before that is checked.
5
+ */
6
+ export declare const MAX_DECIMAL_DIGITS = 1000000;
7
+ /** An integer from a bigint, a safe integer, or its canonical digits. */
8
+ export declare function parseInteger(input: unknown, path: string): ParseResult<string>;
9
+ /** A decimal from a finite number, or a string in JSON's number syntax, in its canonical form. */
10
+ export declare function parseDecimal(input: unknown, path: string): ParseResult<string>;
11
+ /** Orders two canonical numbers, integers or decimals, by value. */
12
+ export declare function compareNumbers(left: string, right: string): number;
@@ -0,0 +1,77 @@
1
+ // Numbers as FateDB keeps them: an integer of any size, and a decimal of any precision. Each has
2
+ // one canonical form, so equal numbers are equal strings, and a fact's identity is its number.
3
+ //
4
+ // An integer is its decimal digits: -?(0|[1-9][0-9]*), never -0. A decimal is written out, without
5
+ // an exponent: an integer part as above, then, when it has a fraction, a point and digits that do
6
+ // not end in 0. So 1.50 and 15e-1 are both 1.5. Two canonical forms compare without arithmetic, in
7
+ // time linear in their digits, whatever their size.
8
+ import { parsed, rejected } from "./result.js";
9
+ /**
10
+ * Digits a decimal may have once written out. A transaction's facts are at most 1,000,000 bytes of
11
+ * JSON anyway; the bound stops "1e999999999" from being written out before that is checked.
12
+ */
13
+ export const MAX_DECIMAL_DIGITS = 1_000_000;
14
+ const INTEGER = /^-?(?:0|[1-9][0-9]*)$/;
15
+ const DECIMAL = /^(-?)(0|[1-9][0-9]*)(?:\.([0-9]+))?(?:[eE]([+-]?[0-9]+))?$/;
16
+ /** An integer from a bigint, a safe integer, or its canonical digits. */
17
+ export function parseInteger(input, path) {
18
+ if (typeof input === "bigint")
19
+ return parsed(input.toString());
20
+ if (typeof input === "number") {
21
+ if (Number.isSafeInteger(input))
22
+ return parsed(String(input));
23
+ return rejected(path, Number.isInteger(input)
24
+ ? "past 2^53 a JavaScript number is not exact: pass a bigint, or the digits as a string"
25
+ : "expected an integer, not a fraction: a decimal holds fractions");
26
+ }
27
+ if (typeof input !== "string" || !INTEGER.test(input) || input === "-0") {
28
+ return rejected(path, 'expected an integer: a bigint, a safe integer, or its digits as a string, such as "-42"');
29
+ }
30
+ return parsed(input);
31
+ }
32
+ /** A decimal from a finite number, or a string in JSON's number syntax, in its canonical form. */
33
+ export function parseDecimal(input, path) {
34
+ const text = typeof input === "string" ? input : typeof input === "number" && Number.isFinite(input) ? String(input) : null;
35
+ const match = text === null ? null : DECIMAL.exec(text);
36
+ if (match === null) {
37
+ return rejected(path, 'expected a decimal: a finite number, or a string of digits with an optional point and exponent, such as "-12.50" or "1.5e-3"');
38
+ }
39
+ const [, sign, whole = "", fraction = "", exponent = "0"] = match;
40
+ const all = whole + fraction;
41
+ const leading = all.length - all.replace(/^0+/, "").length;
42
+ const digits = all.slice(leading).replace(/0+$/, "");
43
+ if (digits === "")
44
+ return parsed("0");
45
+ // The value is 0.<digits> × 10^point.
46
+ const point = whole.length + Number(exponent) - leading;
47
+ const written = point >= digits.length ? point : point > 0 ? digits.length : digits.length - point + 1;
48
+ if (!(written <= MAX_DECIMAL_DIGITS))
49
+ return rejected(path, `a decimal cannot have more than ${MAX_DECIMAL_DIGITS} digits written out`);
50
+ const magnitude = point >= digits.length
51
+ ? digits + "0".repeat(point - digits.length)
52
+ : point > 0
53
+ ? `${digits.slice(0, point)}.${digits.slice(point)}`
54
+ : `0.${"0".repeat(-point)}${digits}`;
55
+ return parsed(sign === "-" ? `-${magnitude}` : magnitude);
56
+ }
57
+ /** Orders two canonical numbers, integers or decimals, by value. */
58
+ export function compareNumbers(left, right) {
59
+ const negative = left.startsWith("-");
60
+ if (negative !== right.startsWith("-"))
61
+ return negative ? -1 : 1;
62
+ const order = compareMagnitudes(negative ? left.slice(1) : left, negative ? right.slice(1) : right);
63
+ // Between negatives the larger magnitude is the smaller number; equal stays 0, not -0.
64
+ return negative && order !== 0 ? -order : order;
65
+ }
66
+ function compareMagnitudes(left, right) {
67
+ const [leftWhole = "", leftFraction = ""] = left.split(".");
68
+ const [rightWhole = "", rightFraction = ""] = right.split(".");
69
+ if (leftWhole.length !== rightWhole.length)
70
+ return leftWhole.length < rightWhole.length ? -1 : 1;
71
+ if (leftWhole !== rightWhole)
72
+ return leftWhole < rightWhole ? -1 : 1;
73
+ // Canonical fractions do not end in 0, so a fraction that is a prefix of another is smaller.
74
+ if (leftFraction === rightFraction)
75
+ return 0;
76
+ return leftFraction < rightFraction ? -1 : 1;
77
+ }