@nice-code/commander 0.77.0 → 0.79.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/build/cli.cjs +1004 -271
- package/build/cli.cjs.map +1 -1
- package/build/cli.mjs +1004 -271
- package/build/cli.mjs.map +1 -1
- package/build/client/assets/index-Cw6AoXd7.js +19 -0
- package/build/client/assets/index-Cw6AoXd7.js.map +1 -0
- package/build/client/index.html +1 -1
- package/package.json +6 -6
- package/build/client/assets/index-DvBR18K2.js +0 -18
- package/build/client/assets/index-DvBR18K2.js.map +0 -1
package/build/cli.mjs
CHANGED
|
@@ -2694,12 +2694,309 @@ const encryptTextDataWithAesGcmKey = async ({ aesGcmKey, dataToEncrypt }) => {
|
|
|
2694
2694
|
};
|
|
2695
2695
|
};
|
|
2696
2696
|
//#endregion
|
|
2697
|
+
//#region ../nice-util/src/crypto/canonical/stringifyCanonicalJson.ts
|
|
2698
|
+
/**
|
|
2699
|
+
* Deterministic, signing-grade JSON serialization: the same data always produces the same bytes,
|
|
2700
|
+
* regardless of key insertion order — the foundation for content hashes, idempotency keys, and
|
|
2701
|
+
* signed challenges. This is a **frozen project contract** (guarded by byte-level test vectors),
|
|
2702
|
+
* not RFC 8785/JCS. The exact rules:
|
|
2703
|
+
*
|
|
2704
|
+
* - `null`, booleans, strings, and finite numbers serialize with native `JSON.stringify` spelling
|
|
2705
|
+
* and escaping (so `-0` emits `0`).
|
|
2706
|
+
* - Objects contribute their **own enumerable string-keyed** entries only, sorted by UTF-16
|
|
2707
|
+
* code-unit order; entries whose value is `undefined` are omitted. Symbol keys and prototype
|
|
2708
|
+
* properties are ignored. `toJSON` is **never** invoked — a Date/Map/Set/class instance
|
|
2709
|
+
* contributes only its own enumerable entries.
|
|
2710
|
+
* - Arrays retain element order. A sparse **hole** serializes as `null` (native JSON behavior); an
|
|
2711
|
+
* **explicit** `undefined`/function/symbol/bigint element throws.
|
|
2712
|
+
* - Non-finite numbers, bigints, functions/symbols as values, top-level `undefined`, and circular
|
|
2713
|
+
* references throw. Repeated (non-cyclic) references are allowed.
|
|
2714
|
+
*
|
|
2715
|
+
* Error *messages* are not part of the contract; accepted-value bytes are.
|
|
2716
|
+
*/
|
|
2717
|
+
function stringifyCanonicalJson(value) {
|
|
2718
|
+
return writeCanonical(value, "$", /* @__PURE__ */ new Set());
|
|
2719
|
+
}
|
|
2720
|
+
function writeCanonical(value, path, ancestors) {
|
|
2721
|
+
if (value === null) return "null";
|
|
2722
|
+
switch (typeof value) {
|
|
2723
|
+
case "string": return JSON.stringify(value);
|
|
2724
|
+
case "boolean": return value ? "true" : "false";
|
|
2725
|
+
case "number":
|
|
2726
|
+
if (!Number.isFinite(value)) throw new Error(`stringifyCanonicalJson: non-finite number at ${path}`);
|
|
2727
|
+
return JSON.stringify(value);
|
|
2728
|
+
case "undefined":
|
|
2729
|
+
case "bigint":
|
|
2730
|
+
case "function":
|
|
2731
|
+
case "symbol": throw new Error(`stringifyCanonicalJson: unsupported ${typeof value} at ${path}`);
|
|
2732
|
+
default: break;
|
|
2733
|
+
}
|
|
2734
|
+
const obj = value;
|
|
2735
|
+
if (ancestors.has(obj)) throw new Error(`stringifyCanonicalJson: circular reference at ${path}`);
|
|
2736
|
+
ancestors.add(obj);
|
|
2737
|
+
try {
|
|
2738
|
+
if (Array.isArray(obj)) {
|
|
2739
|
+
let out = "[";
|
|
2740
|
+
for (let i = 0; i < obj.length; i++) {
|
|
2741
|
+
if (i > 0) out += ",";
|
|
2742
|
+
out += i in obj ? writeCanonical(obj[i], `${path}[${i}]`, ancestors) : "null";
|
|
2743
|
+
}
|
|
2744
|
+
return `${out}]`;
|
|
2745
|
+
}
|
|
2746
|
+
const record = obj;
|
|
2747
|
+
const keys = Object.keys(record).sort();
|
|
2748
|
+
const parts = [];
|
|
2749
|
+
for (const key of keys) {
|
|
2750
|
+
const entry = record[key];
|
|
2751
|
+
if (entry === void 0) continue;
|
|
2752
|
+
parts.push(`${JSON.stringify(key)}:${writeCanonical(entry, `${path}.${key}`, ancestors)}`);
|
|
2753
|
+
}
|
|
2754
|
+
return `{${parts.join(",")}}`;
|
|
2755
|
+
} finally {
|
|
2756
|
+
ancestors.delete(obj);
|
|
2757
|
+
}
|
|
2758
|
+
}
|
|
2759
|
+
//#endregion
|
|
2760
|
+
//#region ../nice-util/src/crypto/canonical/buildCanonicalChallenge.ts
|
|
2761
|
+
/**
|
|
2762
|
+
* The canonical string a {@link ICanonicalChallenge} signs:
|
|
2763
|
+
* `stringifyCanonicalJson({ domainTag, version, fields })`. Both signer and verifier call this,
|
|
2764
|
+
* so the signed bytes are constructed one way, everywhere.
|
|
2765
|
+
*
|
|
2766
|
+
* Unlike the general serializer (which accepts `unknown` with documented compatibility
|
|
2767
|
+
* behaviors), this **rejects** anything that is not a strict {@link TCanonicalJsonValue}: values
|
|
2768
|
+
* that alias to the same JSON (`undefined` entries, sparse arrays, non-plain objects) are refused
|
|
2769
|
+
* rather than normalized — a signing API must not guess. An empty `domainTag` or a non-positive /
|
|
2770
|
+
* unsafe `version` throws.
|
|
2771
|
+
*/
|
|
2772
|
+
function buildCanonicalChallenge(challenge) {
|
|
2773
|
+
if (typeof challenge.domainTag !== "string" || challenge.domainTag.length === 0) throw new Error("buildCanonicalChallenge: domainTag must be a non-empty string");
|
|
2774
|
+
if (typeof challenge.version !== "number" || !Number.isSafeInteger(challenge.version) || challenge.version < 1) throw new Error("buildCanonicalChallenge: version must be a positive safe integer");
|
|
2775
|
+
if (!isPlainObject$3(challenge.fields)) throw new Error("buildCanonicalChallenge: fields must be a plain object");
|
|
2776
|
+
for (const [key, value] of Object.entries(challenge.fields)) assertStrictCanonicalValue(value, `fields.${key}`);
|
|
2777
|
+
return stringifyCanonicalJson({
|
|
2778
|
+
domainTag: challenge.domainTag,
|
|
2779
|
+
version: challenge.version,
|
|
2780
|
+
fields: challenge.fields
|
|
2781
|
+
});
|
|
2782
|
+
}
|
|
2783
|
+
function isPlainObject$3(value) {
|
|
2784
|
+
if (typeof value !== "object" || value === null) return false;
|
|
2785
|
+
const proto = Object.getPrototypeOf(value);
|
|
2786
|
+
return proto === Object.prototype || proto === null;
|
|
2787
|
+
}
|
|
2788
|
+
function assertStrictCanonicalValue(value, path) {
|
|
2789
|
+
if (value === void 0) throw new Error(`buildCanonicalChallenge: undefined entry at ${path}`);
|
|
2790
|
+
if (value === null || typeof value === "string" || typeof value === "boolean") return;
|
|
2791
|
+
if (typeof value === "number") {
|
|
2792
|
+
if (!Number.isFinite(value)) throw new Error(`buildCanonicalChallenge: non-finite number at ${path}`);
|
|
2793
|
+
return;
|
|
2794
|
+
}
|
|
2795
|
+
if (Array.isArray(value)) {
|
|
2796
|
+
for (let i = 0; i < value.length; i++) {
|
|
2797
|
+
if (!(i in value)) throw new Error(`buildCanonicalChallenge: sparse array hole at ${path}[${i}]`);
|
|
2798
|
+
assertStrictCanonicalValue(value[i], `${path}[${i}]`);
|
|
2799
|
+
}
|
|
2800
|
+
return;
|
|
2801
|
+
}
|
|
2802
|
+
if (isPlainObject$3(value)) {
|
|
2803
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
2804
|
+
if (entry === void 0) throw new Error(`buildCanonicalChallenge: undefined entry at ${path}.${key}`);
|
|
2805
|
+
assertStrictCanonicalValue(entry, `${path}.${key}`);
|
|
2806
|
+
}
|
|
2807
|
+
return;
|
|
2808
|
+
}
|
|
2809
|
+
throw new Error(`buildCanonicalChallenge: unsupported value at ${path} — strict JSON values only (null, boolean, finite number, string, dense array, plain object)`);
|
|
2810
|
+
}
|
|
2811
|
+
//#endregion
|
|
2812
|
+
//#region ../nice-util/src/data_type/bytes/base64.ts
|
|
2813
|
+
/**
|
|
2814
|
+
* Byte ⇄ base64 conversions that work in **every** JavaScript runtime — browsers, Node, Cloudflare
|
|
2815
|
+
* Workers, Deno, Bun, and React Native (Hermes) — without leaning on environment-specific interfaces:
|
|
2816
|
+
* the browser-only `btoa`/`atob` globals (absent in Hermes), or Node's `Buffer` (absent in browsers /
|
|
2817
|
+
* Workers / RN). Built on `@scure/base` (pure JS, audited, zero-dependency) — the same base64
|
|
2818
|
+
* implementation the crypto layer already uses, so the whole library stays consistent.
|
|
2819
|
+
*
|
|
2820
|
+
* Produces / consumes **standard** base64 (RFC 4648 §4: `+` and `/`, `=` padding) — byte-for-byte
|
|
2821
|
+
* interchangeable with `btoa`/`atob` and Node's `Buffer.toString("base64")`, so it interoperates with
|
|
2822
|
+
* any peer regardless of how that peer encodes.
|
|
2823
|
+
*
|
|
2824
|
+
* NOTE: the TC39 `Uint8Array.prototype.toBase64()` / `Uint8Array.fromBase64()` methods would be the
|
|
2825
|
+
* "native" choice, but as of 2026 they are not yet available across all target runtimes (notably Hermes),
|
|
2826
|
+
* so a pure-JS implementation remains the portable option.
|
|
2827
|
+
*/
|
|
2828
|
+
function bytesToBase64(bytes) {
|
|
2829
|
+
return base64$1.encode(bytes);
|
|
2830
|
+
}
|
|
2831
|
+
function base64ToBytes(encoded) {
|
|
2832
|
+
return base64$1.decode(encoded);
|
|
2833
|
+
}
|
|
2834
|
+
//#endregion
|
|
2835
|
+
//#region ../nice-util/src/crypto/canonical/sha256.ts
|
|
2836
|
+
/**
|
|
2837
|
+
* Synchronous SHA-256 (FIPS 180-4) over a UTF-8 string or raw bytes. Synchronous on purpose:
|
|
2838
|
+
* definition-time hashes (e.g. nice-realm's schema hash at `defineRealm`) must be computable
|
|
2839
|
+
* during module evaluation in both Node and workerd, and `crypto.subtle.digest` is async — a
|
|
2840
|
+
* small pure implementation keeps callers synchronous and platform-stable. Moved here from
|
|
2841
|
+
* nice-realm (which re-exports `sha256Hex` from its `/internals` for compatibility); verified
|
|
2842
|
+
* against the FIPS 180-4 test vectors in `canonical.test.ts`.
|
|
2843
|
+
*/
|
|
2844
|
+
const K = new Uint32Array([
|
|
2845
|
+
1116352408,
|
|
2846
|
+
1899447441,
|
|
2847
|
+
3049323471,
|
|
2848
|
+
3921009573,
|
|
2849
|
+
961987163,
|
|
2850
|
+
1508970993,
|
|
2851
|
+
2453635748,
|
|
2852
|
+
2870763221,
|
|
2853
|
+
3624381080,
|
|
2854
|
+
310598401,
|
|
2855
|
+
607225278,
|
|
2856
|
+
1426881987,
|
|
2857
|
+
1925078388,
|
|
2858
|
+
2162078206,
|
|
2859
|
+
2614888103,
|
|
2860
|
+
3248222580,
|
|
2861
|
+
3835390401,
|
|
2862
|
+
4022224774,
|
|
2863
|
+
264347078,
|
|
2864
|
+
604807628,
|
|
2865
|
+
770255983,
|
|
2866
|
+
1249150122,
|
|
2867
|
+
1555081692,
|
|
2868
|
+
1996064986,
|
|
2869
|
+
2554220882,
|
|
2870
|
+
2821834349,
|
|
2871
|
+
2952996808,
|
|
2872
|
+
3210313671,
|
|
2873
|
+
3336571891,
|
|
2874
|
+
3584528711,
|
|
2875
|
+
113926993,
|
|
2876
|
+
338241895,
|
|
2877
|
+
666307205,
|
|
2878
|
+
773529912,
|
|
2879
|
+
1294757372,
|
|
2880
|
+
1396182291,
|
|
2881
|
+
1695183700,
|
|
2882
|
+
1986661051,
|
|
2883
|
+
2177026350,
|
|
2884
|
+
2456956037,
|
|
2885
|
+
2730485921,
|
|
2886
|
+
2820302411,
|
|
2887
|
+
3259730800,
|
|
2888
|
+
3345764771,
|
|
2889
|
+
3516065817,
|
|
2890
|
+
3600352804,
|
|
2891
|
+
4094571909,
|
|
2892
|
+
275423344,
|
|
2893
|
+
430227734,
|
|
2894
|
+
506948616,
|
|
2895
|
+
659060556,
|
|
2896
|
+
883997877,
|
|
2897
|
+
958139571,
|
|
2898
|
+
1322822218,
|
|
2899
|
+
1537002063,
|
|
2900
|
+
1747873779,
|
|
2901
|
+
1955562222,
|
|
2902
|
+
2024104815,
|
|
2903
|
+
2227730452,
|
|
2904
|
+
2361852424,
|
|
2905
|
+
2428436474,
|
|
2906
|
+
2756734187,
|
|
2907
|
+
3204031479,
|
|
2908
|
+
3329325298
|
|
2909
|
+
]);
|
|
2910
|
+
function rotr(x, n) {
|
|
2911
|
+
return x >>> n | x << 32 - n;
|
|
2912
|
+
}
|
|
2913
|
+
/** SHA-256 of a UTF-8 string or raw bytes, as the 32-byte digest. */
|
|
2914
|
+
function sha256Bytes(input) {
|
|
2915
|
+
const bytes = typeof input === "string" ? new TextEncoder().encode(input) : input;
|
|
2916
|
+
const bitLen = bytes.length * 8;
|
|
2917
|
+
const paddedLen = (bytes.length + 8 >> 6) + 1 << 6;
|
|
2918
|
+
const padded = new Uint8Array(paddedLen);
|
|
2919
|
+
padded.set(bytes);
|
|
2920
|
+
padded[bytes.length] = 128;
|
|
2921
|
+
const view = new DataView(padded.buffer);
|
|
2922
|
+
view.setUint32(paddedLen - 8, Math.floor(bitLen / 4294967296), false);
|
|
2923
|
+
view.setUint32(paddedLen - 4, bitLen >>> 0, false);
|
|
2924
|
+
const h = new Uint32Array([
|
|
2925
|
+
1779033703,
|
|
2926
|
+
3144134277,
|
|
2927
|
+
1013904242,
|
|
2928
|
+
2773480762,
|
|
2929
|
+
1359893119,
|
|
2930
|
+
2600822924,
|
|
2931
|
+
528734635,
|
|
2932
|
+
1541459225
|
|
2933
|
+
]);
|
|
2934
|
+
const w = new Uint32Array(64);
|
|
2935
|
+
for (let offset = 0; offset < paddedLen; offset += 64) {
|
|
2936
|
+
for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4, false);
|
|
2937
|
+
for (let i = 16; i < 64; i++) {
|
|
2938
|
+
const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ w[i - 15] >>> 3;
|
|
2939
|
+
const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ w[i - 2] >>> 10;
|
|
2940
|
+
w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
|
|
2941
|
+
}
|
|
2942
|
+
let a = h[0];
|
|
2943
|
+
let b = h[1];
|
|
2944
|
+
let c = h[2];
|
|
2945
|
+
let d = h[3];
|
|
2946
|
+
let e = h[4];
|
|
2947
|
+
let f = h[5];
|
|
2948
|
+
let g = h[6];
|
|
2949
|
+
let hh = h[7];
|
|
2950
|
+
for (let i = 0; i < 64; i++) {
|
|
2951
|
+
const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
|
2952
|
+
const ch = e & f ^ ~e & g;
|
|
2953
|
+
const temp1 = hh + s1 + ch + K[i] + w[i] >>> 0;
|
|
2954
|
+
const temp2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
|
|
2955
|
+
hh = g;
|
|
2956
|
+
g = f;
|
|
2957
|
+
f = e;
|
|
2958
|
+
e = d + temp1 >>> 0;
|
|
2959
|
+
d = c;
|
|
2960
|
+
c = b;
|
|
2961
|
+
b = a;
|
|
2962
|
+
a = temp1 + temp2 >>> 0;
|
|
2963
|
+
}
|
|
2964
|
+
h[0] = h[0] + a >>> 0;
|
|
2965
|
+
h[1] = h[1] + b >>> 0;
|
|
2966
|
+
h[2] = h[2] + c >>> 0;
|
|
2967
|
+
h[3] = h[3] + d >>> 0;
|
|
2968
|
+
h[4] = h[4] + e >>> 0;
|
|
2969
|
+
h[5] = h[5] + f >>> 0;
|
|
2970
|
+
h[6] = h[6] + g >>> 0;
|
|
2971
|
+
h[7] = h[7] + hh >>> 0;
|
|
2972
|
+
}
|
|
2973
|
+
const digest = new Uint8Array(32);
|
|
2974
|
+
const digestView = new DataView(digest.buffer);
|
|
2975
|
+
for (let i = 0; i < 8; i++) digestView.setUint32(i * 4, h[i], false);
|
|
2976
|
+
return digest;
|
|
2977
|
+
}
|
|
2978
|
+
/** SHA-256 of a UTF-8 string or raw bytes, as lowercase hex. */
|
|
2979
|
+
function sha256Hex(input) {
|
|
2980
|
+
const digest = sha256Bytes(input);
|
|
2981
|
+
let hex = "";
|
|
2982
|
+
for (const byte of digest) hex += byte.toString(16).padStart(2, "0");
|
|
2983
|
+
return hex;
|
|
2984
|
+
}
|
|
2985
|
+
//#endregion
|
|
2697
2986
|
//#region ../nice-util/src/crypto/ed25519/signTextDataWithKeyEd25519.ts
|
|
2698
2987
|
const signTextDataWithKeyEd25519 = async (data, cryptoKey) => {
|
|
2699
2988
|
const dataBuffer = new TextEncoder().encode(data);
|
|
2700
2989
|
const signature = await crypto.subtle.sign({ name: "ED25519" }, cryptoKey, dataBuffer);
|
|
2701
2990
|
return new Uint8Array(signature);
|
|
2702
2991
|
};
|
|
2992
|
+
/**
|
|
2993
|
+
* ⚠ Separator-joining caller-controlled strings is a **concatenation-ambiguity** hazard: the parts
|
|
2994
|
+
* have no escaping, so `["a::b"]` and `["a","b"]` sign identical bytes, and two operations'
|
|
2995
|
+
* challenges can collide unless every call site adds its own fixed tag. For new signing surfaces
|
|
2996
|
+
* prefer the canonical challenge form (`buildCanonicalChallenge` /
|
|
2997
|
+
* `ClientCryptoKeyLink.signChallengeCanonical`) — exact field boundaries by construction. This
|
|
2998
|
+
* helper stays byte-for-byte for deployed contracts.
|
|
2999
|
+
*/
|
|
2703
3000
|
const signCombinedTextDataWithKeyEd25519 = async (data, cryptoKey, separator = "::") => {
|
|
2704
3001
|
return await signTextDataWithKeyEd25519(data.join(separator), cryptoKey);
|
|
2705
3002
|
};
|
|
@@ -2723,25 +3020,79 @@ const buildVerifyKeyBoundInfoString = ({ infoString, verifyPublicKeys }) => {
|
|
|
2723
3020
|
return [...infoString != null ? [infoString] : [], ...sortedKeys].join("::");
|
|
2724
3021
|
};
|
|
2725
3022
|
//#endregion
|
|
3023
|
+
//#region ../nice-util/src/storage_adapter/typed_storage/StorageValidationError.ts
|
|
3024
|
+
/**
|
|
3025
|
+
* A typed-storage read, default, write, or update failed schema validation. Always thrown —
|
|
3026
|
+
* validation is fail-closed; the `onInvalid` option observes, it never suppresses. Carries the
|
|
3027
|
+
* storage `key` and the schema's `issues` so callers can branch (e.g. treat a corrupt record as
|
|
3028
|
+
* absent, run a migration, or surface telemetry).
|
|
3029
|
+
*/
|
|
3030
|
+
var StorageValidationError = class extends Error {
|
|
3031
|
+
key;
|
|
3032
|
+
issues;
|
|
3033
|
+
constructor(key, issues) {
|
|
3034
|
+
const rendered = issues.map((issue, index) => {
|
|
3035
|
+
const path = issue.path?.map((segment) => typeof segment === "object" ? String(segment.key) : String(segment)).join(".");
|
|
3036
|
+
return ` (issue ${index + 1})${path ? ` [${path}]` : ""}: ${issue.message}`;
|
|
3037
|
+
}).join("\n");
|
|
3038
|
+
super(`Typed storage validation failed for key "${key}":\n${rendered}`);
|
|
3039
|
+
this.name = "StorageValidationError";
|
|
3040
|
+
this.key = key;
|
|
3041
|
+
this.issues = issues;
|
|
3042
|
+
}
|
|
3043
|
+
};
|
|
3044
|
+
//#endregion
|
|
2726
3045
|
//#region ../nice-util/src/storage_adapter/typed_storage/createTypedStorage.ts
|
|
2727
|
-
|
|
3046
|
+
/**
|
|
3047
|
+
* A typed view over a {@link StorageAdapter}. Without `schemas` it is types-only (the stored value
|
|
3048
|
+
* is trusted to match `T` — fine for values only your own code writes). With `schemas`, the
|
|
3049
|
+
* storage boundary gets the same treatment the action layer gives the wire: values are validated
|
|
3050
|
+
* on the way out **and** in, because durable storage is where stale shapes live longest — a value
|
|
3051
|
+
* written by version N and read by version N+3 has crossed every schema change in between.
|
|
3052
|
+
*/
|
|
3053
|
+
function createTypedStorage({ storageAdapter, schemas, onInvalid }) {
|
|
3054
|
+
const validate = (key, value) => {
|
|
3055
|
+
const schema = schemas?.[key];
|
|
3056
|
+
if (schema == null) return value;
|
|
3057
|
+
const result = schema["~standard"].validate(value);
|
|
3058
|
+
let issues;
|
|
3059
|
+
if (result instanceof Promise) issues = [{ message: "async schema validation is not supported for typed storage" }];
|
|
3060
|
+
else if (result.issues != null) issues = result.issues;
|
|
3061
|
+
else return result.value;
|
|
3062
|
+
const error = new StorageValidationError(key, issues);
|
|
3063
|
+
onInvalid?.(error);
|
|
3064
|
+
throw error;
|
|
3065
|
+
};
|
|
3066
|
+
const hasSchema = (key) => schemas?.[key] != null;
|
|
2728
3067
|
const getJson = async (key) => {
|
|
2729
|
-
|
|
3068
|
+
const stored = await storageAdapter.getJson(key);
|
|
3069
|
+
if (stored === void 0 || !hasSchema(key)) return stored;
|
|
3070
|
+
return validate(key, stored);
|
|
2730
3071
|
};
|
|
2731
3072
|
const getJsonOrDef = async (key, defVal) => {
|
|
2732
|
-
|
|
3073
|
+
const value = await storageAdapter.getJson(key) ?? defVal;
|
|
3074
|
+
if (!hasSchema(key)) return value;
|
|
3075
|
+
return validate(key, value);
|
|
2733
3076
|
};
|
|
2734
3077
|
const setJson = async (key, val) => {
|
|
2735
|
-
return storageAdapter.setJson(key, val);
|
|
3078
|
+
return storageAdapter.setJson(key, hasSchema(key) ? validate(key, val) : val);
|
|
2736
3079
|
};
|
|
2737
3080
|
const removeItem = async (key) => {
|
|
2738
3081
|
await storageAdapter.removeItem(key);
|
|
2739
3082
|
};
|
|
2740
3083
|
const updateJson = async (key, updater) => {
|
|
2741
|
-
|
|
3084
|
+
if (!hasSchema(key)) {
|
|
3085
|
+
await storageAdapter.updateJson(key, updater);
|
|
3086
|
+
return;
|
|
3087
|
+
}
|
|
3088
|
+
await storageAdapter.updateJson(key, (currentVal) => validate(key, updater(currentVal === void 0 ? void 0 : validate(key, currentVal))));
|
|
2742
3089
|
};
|
|
2743
3090
|
const updateJsonWithDef = async (key, defaultVal, updater) => {
|
|
2744
|
-
|
|
3091
|
+
if (!hasSchema(key)) {
|
|
3092
|
+
await storageAdapter.updateJsonOrDef(key, defaultVal, updater);
|
|
3093
|
+
return;
|
|
3094
|
+
}
|
|
3095
|
+
await storageAdapter.updateJsonOrDef(key, defaultVal, (currentVal) => validate(key, updater(validate(key, currentVal))));
|
|
2745
3096
|
};
|
|
2746
3097
|
return {
|
|
2747
3098
|
getJson,
|
|
@@ -4024,6 +4375,13 @@ var ClientCryptoKeyLink = class {
|
|
|
4024
4375
|
})
|
|
4025
4376
|
};
|
|
4026
4377
|
}
|
|
4378
|
+
/**
|
|
4379
|
+
* ⚠ Multi-part challenges join with `"::"` — a **concatenation-ambiguity** hazard: when a caller
|
|
4380
|
+
* controls two adjacent parts, distinct tuples can produce identical signed bytes (`["a::b"]`
|
|
4381
|
+
* vs `["a","b"]`), and two operations' challenges can collide unless every call site remembers
|
|
4382
|
+
* its own fixed tag. Prefer {@link signChallengeCanonical}: domain-tagged, versioned, exact
|
|
4383
|
+
* field boundaries by construction. This method stays byte-for-byte for deployed contracts.
|
|
4384
|
+
*/
|
|
4027
4385
|
async signChallenge(challenge) {
|
|
4028
4386
|
if (challenge.length === 0) throw new Error("Challenge must contain at least one string");
|
|
4029
4387
|
const localVerifyKeyPair = await this.ensureLocalVerifyKeyPair();
|
|
@@ -4031,6 +4389,27 @@ var ClientCryptoKeyLink = class {
|
|
|
4031
4389
|
return { signatureBase64: base64$1.encode(signature) };
|
|
4032
4390
|
}
|
|
4033
4391
|
/**
|
|
4392
|
+
* Sign a {@link ICanonicalChallenge} — the canonical, domain-tagged, versioned challenge form
|
|
4393
|
+
* ({@link buildCanonicalChallenge} defines the signed bytes). Same key and signature scheme as
|
|
4394
|
+
* {@link signChallenge}, safer byte layout; the verify dual is
|
|
4395
|
+
* {@link verifyChallengeCanonicalFromLinkedClient}, which takes the same structured challenge.
|
|
4396
|
+
*/
|
|
4397
|
+
async signChallengeCanonical(challenge) {
|
|
4398
|
+
return this.signChallenge([buildCanonicalChallenge(challenge)]);
|
|
4399
|
+
}
|
|
4400
|
+
/**
|
|
4401
|
+
* Verify a signature produced by {@link signChallengeCanonical} against the linked client's
|
|
4402
|
+
* verify key. Takes the **structured** challenge and rebuilds the canonical string itself, so
|
|
4403
|
+
* signer and verifier can never disagree on byte construction.
|
|
4404
|
+
*/
|
|
4405
|
+
async verifyChallengeCanonicalFromLinkedClient({ linkedClientId, challenge, signatureBase64 }) {
|
|
4406
|
+
return this.verifyChallengeFromLinkedClient({
|
|
4407
|
+
linkedClientId,
|
|
4408
|
+
challenge: buildCanonicalChallenge(challenge),
|
|
4409
|
+
signatureBase64
|
|
4410
|
+
});
|
|
4411
|
+
}
|
|
4412
|
+
/**
|
|
4034
4413
|
* Verifies a signature over `challenge` against the linked client's verify (Ed25519) public key.
|
|
4035
4414
|
*/
|
|
4036
4415
|
async verifyChallengeFromLinkedClient({ linkedClientId, challenge, signatureBase64 }) {
|
|
@@ -4044,29 +4423,6 @@ var ClientCryptoKeyLink = class {
|
|
|
4044
4423
|
}
|
|
4045
4424
|
};
|
|
4046
4425
|
//#endregion
|
|
4047
|
-
//#region ../nice-util/src/data_type/bytes/base64.ts
|
|
4048
|
-
/**
|
|
4049
|
-
* Byte ⇄ base64 conversions that work in **every** JavaScript runtime — browsers, Node, Cloudflare
|
|
4050
|
-
* Workers, Deno, Bun, and React Native (Hermes) — without leaning on environment-specific interfaces:
|
|
4051
|
-
* the browser-only `btoa`/`atob` globals (absent in Hermes), or Node's `Buffer` (absent in browsers /
|
|
4052
|
-
* Workers / RN). Built on `@scure/base` (pure JS, audited, zero-dependency) — the same base64
|
|
4053
|
-
* implementation the crypto layer already uses, so the whole library stays consistent.
|
|
4054
|
-
*
|
|
4055
|
-
* Produces / consumes **standard** base64 (RFC 4648 §4: `+` and `/`, `=` padding) — byte-for-byte
|
|
4056
|
-
* interchangeable with `btoa`/`atob` and Node's `Buffer.toString("base64")`, so it interoperates with
|
|
4057
|
-
* any peer regardless of how that peer encodes.
|
|
4058
|
-
*
|
|
4059
|
-
* NOTE: the TC39 `Uint8Array.prototype.toBase64()` / `Uint8Array.fromBase64()` methods would be the
|
|
4060
|
-
* "native" choice, but as of 2026 they are not yet available across all target runtimes (notably Hermes),
|
|
4061
|
-
* so a pure-JS implementation remains the portable option.
|
|
4062
|
-
*/
|
|
4063
|
-
function bytesToBase64(bytes) {
|
|
4064
|
-
return base64$1.encode(bytes);
|
|
4065
|
-
}
|
|
4066
|
-
function base64ToBytes(encoded) {
|
|
4067
|
-
return base64$1.decode(encoded);
|
|
4068
|
-
}
|
|
4069
|
-
//#endregion
|
|
4070
4426
|
//#region ../nice-util/src/storage_adapter/StorageAdapter.ts
|
|
4071
4427
|
var StorageAdapter = class StorageAdapter {
|
|
4072
4428
|
implementation;
|
|
@@ -4077,6 +4433,7 @@ var StorageAdapter = class StorageAdapter {
|
|
|
4077
4433
|
* `true` on localStorage / Durable Object / KV, `undefined` (unknown) on custom methods.
|
|
4078
4434
|
*/
|
|
4079
4435
|
durable;
|
|
4436
|
+
trackKeysForClearing;
|
|
4080
4437
|
adapterStorage;
|
|
4081
4438
|
/**
|
|
4082
4439
|
* Serializes mutations of the `__usedKeys__` index so its read-modify-write cycles can't
|
|
@@ -4092,6 +4449,7 @@ var StorageAdapter = class StorageAdapter {
|
|
|
4092
4449
|
this.durable = methods.durable;
|
|
4093
4450
|
this.keyPrefix = keyPrefix ?? "";
|
|
4094
4451
|
const _trackKeys = trackKeys ?? true;
|
|
4452
|
+
this.trackKeysForClearing = _trackKeys;
|
|
4095
4453
|
this.adapterStorage = _trackKeys ? createTypedStorage({ storageAdapter: new StorageAdapter({
|
|
4096
4454
|
methods,
|
|
4097
4455
|
keyPrefix,
|
|
@@ -4114,12 +4472,14 @@ var StorageAdapter = class StorageAdapter {
|
|
|
4114
4472
|
/**
|
|
4115
4473
|
* Derive a new adapter over the *same* backing store with an extra key-prefix segment appended.
|
|
4116
4474
|
* Lets an independent namespace (e.g. a second crypto identity) share one underlying storage without
|
|
4117
|
-
* key collisions
|
|
4475
|
+
* key collisions. Key-tracking policy is inherited: deriving from an intentionally untracked
|
|
4476
|
+
* adapter must not silently create a `__usedKeys__` index.
|
|
4118
4477
|
*/
|
|
4119
4478
|
withKeyPrefix(extraPrefix) {
|
|
4120
4479
|
return new StorageAdapter({
|
|
4121
4480
|
methods: this.implementation,
|
|
4122
|
-
keyPrefix: `${this.keyPrefix}${extraPrefix}
|
|
4481
|
+
keyPrefix: `${this.keyPrefix}${extraPrefix}`,
|
|
4482
|
+
trackKeysForClearing: this.trackKeysForClearing
|
|
4123
4483
|
});
|
|
4124
4484
|
}
|
|
4125
4485
|
async trackUsedKey(rawKey) {
|
|
@@ -4544,6 +4904,14 @@ function createInMemoryTofuVerifyKeyResolver() {
|
|
|
4544
4904
|
};
|
|
4545
4905
|
} };
|
|
4546
4906
|
}
|
|
4907
|
+
const tofuPinStorageKey = async (identity) => {
|
|
4908
|
+
return `pin:${[...new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(`nice-wire-tofu-v1:${identity}`)))].map((byte) => byte.toString(16).padStart(2, "0")).join("")}`;
|
|
4909
|
+
};
|
|
4910
|
+
const pinMismatch = () => ({
|
|
4911
|
+
trusted: false,
|
|
4912
|
+
reason: "verify key changed for client identity (pin mismatch)",
|
|
4913
|
+
rejectId: HANDSHAKE_REJECT_ID_PIN_MISMATCH
|
|
4914
|
+
});
|
|
4547
4915
|
/**
|
|
4548
4916
|
* Storage-backed trust-on-first-use resolver: pins survive process restarts / Durable Object eviction
|
|
4549
4917
|
* (e.g. back it with `createDurableObjectStorageAdapter`). Same policy as the in-memory variant — trust
|
|
@@ -4558,8 +4926,46 @@ function createInMemoryTofuVerifyKeyResolver() {
|
|
|
4558
4926
|
* On an *eventually-consistent* store a stale "absent" read re-pins the **same** verify key the client
|
|
4559
4927
|
* just presented (it is signature-verified before this runs), so the worst case is a harmless re-write,
|
|
4560
4928
|
* never a weakened trust decision. Cross-isolate-strong pinning still wants a strongly-consistent store.
|
|
4929
|
+
*
|
|
4930
|
+
* Switching an existing host from `document` to `per_identity` is safe: on each identity's next
|
|
4931
|
+
* contact the legacy pin is honored and migrated to its per-identity record. The reverse switch is
|
|
4932
|
+
* NOT migrated — pins recorded per-identity are invisible to the `document` layout.
|
|
4561
4933
|
*/
|
|
4562
|
-
function createStorageTofuVerifyKeyResolver(storageAdapter) {
|
|
4934
|
+
function createStorageTofuVerifyKeyResolver(storageAdapter, options = {}) {
|
|
4935
|
+
if (options.layout === "per_identity") {
|
|
4936
|
+
const identityLocks = /* @__PURE__ */ new Map();
|
|
4937
|
+
return { async resolve({ client, verifyPublicKey }) {
|
|
4938
|
+
const identity = tofuPinKey(client);
|
|
4939
|
+
const storageKey = await tofuPinStorageKey(identity);
|
|
4940
|
+
const operation = (identityLocks.get(storageKey) ?? Promise.resolve()).catch(() => void 0).then(async () => {
|
|
4941
|
+
const existing = await storageAdapter.getJson(storageKey);
|
|
4942
|
+
if (existing == null) {
|
|
4943
|
+
const legacy = (await storageAdapter.getJson("pins"))?.[identity];
|
|
4944
|
+
if (legacy != null) {
|
|
4945
|
+
await storageAdapter.setJson(storageKey, {
|
|
4946
|
+
identity,
|
|
4947
|
+
verifyPublicKey: legacy
|
|
4948
|
+
});
|
|
4949
|
+
return legacy === verifyPublicKey ? { trusted: true } : pinMismatch();
|
|
4950
|
+
}
|
|
4951
|
+
await storageAdapter.setJson(storageKey, {
|
|
4952
|
+
identity,
|
|
4953
|
+
verifyPublicKey
|
|
4954
|
+
});
|
|
4955
|
+
return { trusted: true };
|
|
4956
|
+
}
|
|
4957
|
+
if (existing.identity === identity && existing.verifyPublicKey === verifyPublicKey) return { trusted: true };
|
|
4958
|
+
return pinMismatch();
|
|
4959
|
+
});
|
|
4960
|
+
const tail = operation.then(() => void 0, () => void 0);
|
|
4961
|
+
identityLocks.set(storageKey, tail);
|
|
4962
|
+
try {
|
|
4963
|
+
return await operation;
|
|
4964
|
+
} finally {
|
|
4965
|
+
if (identityLocks.get(storageKey) === tail) identityLocks.delete(storageKey);
|
|
4966
|
+
}
|
|
4967
|
+
} };
|
|
4968
|
+
}
|
|
4563
4969
|
const storage = createTypedStorage({ storageAdapter });
|
|
4564
4970
|
return { async resolve({ client, verifyPublicKey }) {
|
|
4565
4971
|
const key = tofuPinKey(client);
|
|
@@ -4572,11 +4978,7 @@ function createStorageTofuVerifyKeyResolver(storageAdapter) {
|
|
|
4572
4978
|
return { trusted: true };
|
|
4573
4979
|
}
|
|
4574
4980
|
if (existing === verifyPublicKey) return { trusted: true };
|
|
4575
|
-
return
|
|
4576
|
-
trusted: false,
|
|
4577
|
-
reason: "verify key changed for client identity (pin mismatch)",
|
|
4578
|
-
rejectId: HANDSHAKE_REJECT_ID_PIN_MISMATCH
|
|
4579
|
-
};
|
|
4981
|
+
return pinMismatch();
|
|
4580
4982
|
} };
|
|
4581
4983
|
}
|
|
4582
4984
|
function createClientHandshake(config) {
|
|
@@ -8622,6 +9024,7 @@ var WireAcceptor = class {
|
|
|
8622
9024
|
_noneAllowed;
|
|
8623
9025
|
_handshakeMode;
|
|
8624
9026
|
_onConnectionBound;
|
|
9027
|
+
_disposed = false;
|
|
8625
9028
|
_connByClient = /* @__PURE__ */ new Map();
|
|
8626
9029
|
_clientByConn = /* @__PURE__ */ new Map();
|
|
8627
9030
|
_levelByConn = /* @__PURE__ */ new Map();
|
|
@@ -8648,6 +9051,7 @@ var WireAcceptor = class {
|
|
|
8648
9051
|
}
|
|
8649
9052
|
/** Feed one inbound frame from a connection: keepalive, then handshake/session, then dispatch. */
|
|
8650
9053
|
receive(connection, frame) {
|
|
9054
|
+
if (this._disposed) return;
|
|
8651
9055
|
const wireBytes = this._tap != null ? wireFrameByteSize(frame) : 0;
|
|
8652
9056
|
if (frame === KEEPALIVE_PING) {
|
|
8653
9057
|
this._tapIn(connection, wireBytes, "keepalive");
|
|
@@ -8662,12 +9066,14 @@ var WireAcceptor = class {
|
|
|
8662
9066
|
this._sessionFor(connection, security).receive(frame, wireBytes);
|
|
8663
9067
|
}
|
|
8664
9068
|
_receivePlain(connection, frame, wireBytes = 0) {
|
|
9069
|
+
if (this._disposed) return;
|
|
8665
9070
|
this._tapIn(connection, wireBytes, this._laneFor(frame));
|
|
8666
9071
|
if (this._dispatchProtocolFrame(connection, frame)) return;
|
|
8667
9072
|
this._lane.onFrame(connection, frame, "none");
|
|
8668
9073
|
}
|
|
8669
9074
|
/** Route a decrypted frame from an authenticated connection: protocols first, then the lane. */
|
|
8670
9075
|
_routeAuthed(connection, bytes, wireBytes = 0) {
|
|
9076
|
+
if (this._disposed) return;
|
|
8671
9077
|
this._tapIn(connection, wireBytes, this._laneFor(bytes));
|
|
8672
9078
|
if (this._dispatchProtocolFrame(connection, bytes)) return;
|
|
8673
9079
|
this._lane.onFrame(connection, bytes, this._levelByConn.get(connection) ?? "authenticated");
|
|
@@ -8798,6 +9204,7 @@ var WireAcceptor = class {
|
|
|
8798
9204
|
}
|
|
8799
9205
|
/** Bind + persist a connection's authenticated identity once its handshake completes. */
|
|
8800
9206
|
_onAuthenticated(connection, auth) {
|
|
9207
|
+
if (this._disposed) return;
|
|
8801
9208
|
this._bind(connection, auth.client);
|
|
8802
9209
|
this._levelByConn.set(connection, auth.securityLevel);
|
|
8803
9210
|
this._lane.onAuthenticated?.(connection, auth);
|
|
@@ -8825,6 +9232,7 @@ var WireAcceptor = class {
|
|
|
8825
9232
|
* Secure mode never calls this — the handshake binds the authenticated coordinate instead.
|
|
8826
9233
|
*/
|
|
8827
9234
|
bindPlainConnection(connection, client) {
|
|
9235
|
+
if (this._disposed) return;
|
|
8828
9236
|
const isNewBinding = this._clientByConn.get(connection)?.stringId !== client.stringId;
|
|
8829
9237
|
this._bind(connection, client);
|
|
8830
9238
|
if (isNewBinding) this._persist(connection, {
|
|
@@ -8841,6 +9249,7 @@ var WireAcceptor = class {
|
|
|
8841
9249
|
* is ignored with a warning — the socket is simply treated as fresh (its client re-handshakes).
|
|
8842
9250
|
*/
|
|
8843
9251
|
rehydrate(connection, binding) {
|
|
9252
|
+
if (this._disposed) return;
|
|
8844
9253
|
if (binding.v !== 1) {
|
|
8845
9254
|
console.warn(`[wire-acceptor] ignored a persisted connection binding of unknown schema version ${JSON.stringify(binding.v)} (expected 1) — treating the connection as fresh (err_nice_wire_connect.binding_version_mismatch).`);
|
|
8846
9255
|
return;
|
|
@@ -8857,6 +9266,7 @@ var WireAcceptor = class {
|
|
|
8857
9266
|
this._attachProtocols(connection, new Set(binding.protocols ?? []));
|
|
8858
9267
|
}
|
|
8859
9268
|
_persist(connection, binding) {
|
|
9269
|
+
if (this._disposed) return;
|
|
8860
9270
|
this._bindingByConn.set(connection, binding);
|
|
8861
9271
|
this._onConnectionBound?.(connection, binding);
|
|
8862
9272
|
}
|
|
@@ -8866,6 +9276,11 @@ var WireAcceptor = class {
|
|
|
8866
9276
|
}
|
|
8867
9277
|
/** Forget a connection (call on socket close) so stale entries don't misroute later traffic. */
|
|
8868
9278
|
drop(connection) {
|
|
9279
|
+
if (this._disposed) return;
|
|
9280
|
+
this._drop(connection);
|
|
9281
|
+
}
|
|
9282
|
+
/** Internal detach path used once during terminal disposal after public entry points are closed. */
|
|
9283
|
+
_drop(connection) {
|
|
8869
9284
|
const client = this._clientByConn.get(connection);
|
|
8870
9285
|
if (client != null && this._connByClient.get(client.stringId) === connection) this._connByClient.delete(client.stringId);
|
|
8871
9286
|
this._lane.onDrop?.(connection, client);
|
|
@@ -8878,6 +9293,7 @@ var WireAcceptor = class {
|
|
|
8878
9293
|
}
|
|
8879
9294
|
/** Send a raw (already lane/protocol-encoded) frame — through the secure session when present. */
|
|
8880
9295
|
sendTo(connection, frame) {
|
|
9296
|
+
if (this._disposed) return;
|
|
8881
9297
|
const lane = this._laneFor(frame);
|
|
8882
9298
|
const session = this._sessionByConn.get(connection);
|
|
8883
9299
|
if (session == null) {
|
|
@@ -8918,6 +9334,20 @@ var WireAcceptor = class {
|
|
|
8918
9334
|
bindingFor(connection) {
|
|
8919
9335
|
return this._bindingByConn.get(connection);
|
|
8920
9336
|
}
|
|
9337
|
+
/** Quiesce permanently: detach every known connection and ignore late/in-flight traffic. */
|
|
9338
|
+
dispose() {
|
|
9339
|
+
if (this._disposed) return;
|
|
9340
|
+
this._disposed = true;
|
|
9341
|
+
const connections = new Set([
|
|
9342
|
+
...this._clientByConn.keys(),
|
|
9343
|
+
...this._sessionByConn.keys(),
|
|
9344
|
+
...this._bindingByConn.keys()
|
|
9345
|
+
]);
|
|
9346
|
+
for (const connection of connections) this._drop(connection);
|
|
9347
|
+
}
|
|
9348
|
+
get disposed() {
|
|
9349
|
+
return this._disposed;
|
|
9350
|
+
}
|
|
8921
9351
|
};
|
|
8922
9352
|
//#endregion
|
|
8923
9353
|
//#region ../nice-wire/src/SecureSession/exchangeTicketSeal.ts
|
|
@@ -10141,6 +10571,7 @@ const err_nice_action = err_nice.createChildDomain({
|
|
|
10141
10571
|
["not_implemented"]: err({ message: ({ label }) => `The "${label}" functionality is not implemented yet.` }),
|
|
10142
10572
|
["action_id_not_in_domain"]: err({ message: ({ actionId, domain }) => `Action with id "${actionId}" does not exist in domain "${domain}".` }),
|
|
10143
10573
|
["domain_already_exists_in_hierarchy"]: err({ message: ({ domain, allParentDomains, parentDomain }) => `Domain "${domain}" already exists in the hierarchy under the parent "${parentDomain}". All parent domains ["${allParentDomains.join(", ")}"]` }),
|
|
10574
|
+
["domain_name_collision"]: err({ message: ({ domain, existingParentDomains, incomingParentDomains }) => `Two different domain definitions named "${domain}" were registered on one runtime router (existing under [${existingParentDomains.join(" > ")}], incoming under [${incomingParentDomains.join(" > ")}]). Wire routing is by name only, so the later registration would silently shadow the earlier one — give the domains distinct names, or register the same instance.` }),
|
|
10144
10575
|
["domain_no_handler"]: err({ message: ({ domain }) => `Domain "${domain}" has no action handler registered.` }),
|
|
10145
10576
|
["hydration_domain_mismatch"]: err({ message: ({ expected, received }) => `Cannot hydrate action: domain mismatch. Expected "${expected}", got "${received}".` }),
|
|
10146
10577
|
["hydration_action_state_mismatch"]: err({ message: ({ expected, received }) => `Cannot hydrate action: action state type mismatch. Expected "${expected}", got "${received}".` }),
|
|
@@ -11568,6 +11999,11 @@ var ActionSchema = class {
|
|
|
11568
11999
|
* Declare the input schema (JSON-native or with explicit SERDE type param).
|
|
11569
12000
|
* For non-JSON-native inputs, prefer the 3-argument form below to avoid
|
|
11570
12001
|
* needing explicit type parameters.
|
|
12002
|
+
*
|
|
12003
|
+
* The schema runs at `request()` AND again on the receiving runtime before the handler executes,
|
|
12004
|
+
* so it must accept its own validated output. Plain validators always do; a `transform` whose
|
|
12005
|
+
* output fails its own input schema will reject valid requests on arrival — type conversion
|
|
12006
|
+
* belongs in the SERDE pack/unpack arguments, not in schema transforms.
|
|
11571
12007
|
*/
|
|
11572
12008
|
input(options) {
|
|
11573
12009
|
this.inputOptions = options;
|
|
@@ -11928,6 +12364,13 @@ var ConnectionTransportManager = class extends ConnectionTransportManager$1 {
|
|
|
11928
12364
|
var ActionDomainManager = class {
|
|
11929
12365
|
_domains = /* @__PURE__ */ new Map();
|
|
11930
12366
|
addDomain(domain) {
|
|
12367
|
+
const existing = this._domains.get(domain.domain);
|
|
12368
|
+
if (existing === domain) return;
|
|
12369
|
+
if (existing != null) throw err_nice_action.fromId("domain_name_collision", {
|
|
12370
|
+
domain: domain.domain,
|
|
12371
|
+
existingParentDomains: existing.allDomains,
|
|
12372
|
+
incomingParentDomains: domain.allDomains
|
|
12373
|
+
});
|
|
11931
12374
|
this._domains.set(domain.domain, domain);
|
|
11932
12375
|
}
|
|
11933
12376
|
getDomains() {
|
|
@@ -12941,7 +13384,21 @@ var ActionRuntime = class {
|
|
|
12941
13384
|
runningAction._completeWithResult(action.errorResult(castNiceError(err)));
|
|
12942
13385
|
return runningAction;
|
|
12943
13386
|
}
|
|
12944
|
-
|
|
13387
|
+
let validatedAction;
|
|
13388
|
+
try {
|
|
13389
|
+
validatedAction = new ActionPayload_Request({ context: action.context }, action.context.validateInput(action.input), { time: action.time });
|
|
13390
|
+
validatedAction._callSite = action._callSite;
|
|
13391
|
+
} catch (err) {
|
|
13392
|
+
const runningAction = new RunningAction({
|
|
13393
|
+
context: action.context,
|
|
13394
|
+
request: action
|
|
13395
|
+
});
|
|
13396
|
+
runningAction.addUpdateListeners(observers);
|
|
13397
|
+
runningAction._completeWithResult(action.errorResult(castNiceError(err)));
|
|
13398
|
+
this._trySetupReturnDispatch(runningAction);
|
|
13399
|
+
return runningAction;
|
|
13400
|
+
}
|
|
13401
|
+
const runningAction = await handlerForAction.handleActionRequest(validatedAction, {
|
|
12945
13402
|
...options,
|
|
12946
13403
|
targetLocalRuntime: this
|
|
12947
13404
|
});
|
|
@@ -14154,6 +14611,10 @@ var ChannelAcceptor = class ChannelAcceptor extends PeerLink {
|
|
|
14154
14611
|
drop(connection) {
|
|
14155
14612
|
this.wireAcceptor.drop(connection);
|
|
14156
14613
|
}
|
|
14614
|
+
/** Permanently quiesce this acceptor and detach every live/rehydrated connection. */
|
|
14615
|
+
dispose() {
|
|
14616
|
+
this.wireAcceptor.dispose();
|
|
14617
|
+
}
|
|
14157
14618
|
/** Lane cleanup when the wire acceptor drops a connection (fired with the bound client, if any). */
|
|
14158
14619
|
_onConnectionDropped(connection, client) {
|
|
14159
14620
|
if (client != null) {
|
|
@@ -15632,18 +16093,55 @@ function createHibernatableWsServerAdapter(options) {
|
|
|
15632
16093
|
* carrier factory (`wsAcceptorCarrier`, a WebRTC carrier, the Cloudflare DO helper, …) so the
|
|
15633
16094
|
* stateful-handle wiring lives in exactly one place.
|
|
15634
16095
|
*/
|
|
15635
|
-
function createDuplexCarrierLifecycle() {
|
|
16096
|
+
function createDuplexCarrierLifecycle(limits) {
|
|
15636
16097
|
let router;
|
|
16098
|
+
let disposed = false;
|
|
16099
|
+
const windows = /* @__PURE__ */ new Map();
|
|
16100
|
+
const maxFrameBytes = limits?.maxFrameBytes;
|
|
16101
|
+
const rate = limits?.rate;
|
|
16102
|
+
if (maxFrameBytes != null && (!Number.isSafeInteger(maxFrameBytes) || maxFrameBytes <= 0)) throw new Error("maxFrameBytes must be a positive safe integer");
|
|
16103
|
+
if (rate != null && (!Number.isSafeInteger(rate.maxMessages) || rate.maxMessages <= 0 || !Number.isSafeInteger(rate.windowMs) || rate.windowMs <= 0)) throw new Error("inbound rate limits must be positive safe integers");
|
|
16104
|
+
const frameBytes = (frame) => typeof frame === "string" ? new TextEncoder().encode(frame).byteLength : frame instanceof ArrayBuffer ? frame.byteLength : frame.byteLength;
|
|
15637
16105
|
return {
|
|
15638
16106
|
receive(connection, frame) {
|
|
16107
|
+
if (disposed) return;
|
|
15639
16108
|
if (router == null) throw new Error("acceptor carrier not served yet — pass it to serveChannel() before feeding frames");
|
|
16109
|
+
if (maxFrameBytes != null && frameBytes(frame) > maxFrameBytes) {
|
|
16110
|
+
limits?.onExceeded(connection, "frame_bytes");
|
|
16111
|
+
return;
|
|
16112
|
+
}
|
|
16113
|
+
if (rate != null) {
|
|
16114
|
+
const now = Date.now();
|
|
16115
|
+
let window = windows.get(connection);
|
|
16116
|
+
if (window == null || now - window.startedAt >= rate.windowMs) {
|
|
16117
|
+
window = {
|
|
16118
|
+
count: 0,
|
|
16119
|
+
startedAt: now
|
|
16120
|
+
};
|
|
16121
|
+
windows.set(connection, window);
|
|
16122
|
+
}
|
|
16123
|
+
window.count++;
|
|
16124
|
+
if (window.count > rate.maxMessages) {
|
|
16125
|
+
limits?.onExceeded(connection, "message_rate");
|
|
16126
|
+
return;
|
|
16127
|
+
}
|
|
16128
|
+
}
|
|
15640
16129
|
router.receive(connection, frame);
|
|
15641
16130
|
},
|
|
15642
16131
|
drop(connection) {
|
|
16132
|
+
if (disposed) return;
|
|
16133
|
+
windows.delete(connection);
|
|
15643
16134
|
router?.drop(connection);
|
|
15644
16135
|
},
|
|
15645
16136
|
_activate(liveRouter) {
|
|
16137
|
+
if (disposed) throw new Error("acceptor carrier already disposed");
|
|
15646
16138
|
router = liveRouter;
|
|
16139
|
+
},
|
|
16140
|
+
_dispose() {
|
|
16141
|
+
if (disposed) return;
|
|
16142
|
+
disposed = true;
|
|
16143
|
+
router = void 0;
|
|
16144
|
+
windows.clear();
|
|
15647
16145
|
}
|
|
15648
16146
|
};
|
|
15649
16147
|
}
|
|
@@ -15657,6 +16155,35 @@ function isExchangeAcceptorCarrier(carrier) {
|
|
|
15657
16155
|
}
|
|
15658
16156
|
//#endregion
|
|
15659
16157
|
//#region ../nice-action/src/ActionRuntime/Channel/serveChannel.ts
|
|
16158
|
+
/**
|
|
16159
|
+
* Build the per-connection subset resolver a multi-channel acceptor uses: advertised `hello.channels`
|
|
16160
|
+
* tags → the channel that connection speaks (its own codec + dictionary version for a single tag, the
|
|
16161
|
+
* composed union for several, the combined `channel` for none). Returns `null` — the handshake then
|
|
16162
|
+
* rejects — for an unknown tag, and for a repeated tag: a repeat would compose the same channel twice
|
|
16163
|
+
* into the positional wire dictionary and desync every later route index.
|
|
16164
|
+
*
|
|
16165
|
+
* Throws immediately (setup time, not per connection) when two served channels share a tag — a
|
|
16166
|
+
* last-write-wins registry could never route that deterministically.
|
|
16167
|
+
*/
|
|
16168
|
+
function buildChannelSubsetResolver(combined, registry) {
|
|
16169
|
+
const byTag = /* @__PURE__ */ new Map();
|
|
16170
|
+
for (const entry of registry) {
|
|
16171
|
+
if (byTag.has(entry.tag)) throw new Error(`serveChannel: duplicate channel tag "${entry.tag}" in \`channels\` — every served channel needs a distinct tag, or subset selection cannot route deterministically.`);
|
|
16172
|
+
byTag.set(entry.tag, entry);
|
|
16173
|
+
}
|
|
16174
|
+
return (tags) => {
|
|
16175
|
+
if (tags == null || tags.length === 0) return combined;
|
|
16176
|
+
const selected = [];
|
|
16177
|
+
const seen = /* @__PURE__ */ new Set();
|
|
16178
|
+
for (const tag of tags) {
|
|
16179
|
+
const found = byTag.get(tag);
|
|
16180
|
+
if (found == null || seen.has(tag)) return null;
|
|
16181
|
+
seen.add(tag);
|
|
16182
|
+
selected.push(found);
|
|
16183
|
+
}
|
|
16184
|
+
return selected.length === 1 ? selected[0] : combineChannels(selected);
|
|
16185
|
+
};
|
|
16186
|
+
}
|
|
15660
16187
|
/** Default accepted set, shared by every carrier: negotiate per connection to whatever the client picks. */
|
|
15661
16188
|
const DEFAULT_SERVER_SECURITY_LEVELS = [
|
|
15662
16189
|
"none",
|
|
@@ -15675,19 +16202,7 @@ function serveChannel(runtime, channel, options) {
|
|
|
15675
16202
|
const anyDuplexSecure = duplexCarriers.some((carrier) => carrier.secure ?? true);
|
|
15676
16203
|
const securityLevel = options.securityLevel ?? DEFAULT_SERVER_SECURITY_LEVELS;
|
|
15677
16204
|
const registry = options.channels;
|
|
15678
|
-
const resolveChannel = registry != null && registry.length > 1 ? (
|
|
15679
|
-
const byTag = new Map(registry.map((entry) => [entry.tag, entry]));
|
|
15680
|
-
return (tags) => {
|
|
15681
|
-
if (tags == null || tags.length === 0) return channel;
|
|
15682
|
-
const selected = [];
|
|
15683
|
-
for (const tag of tags) {
|
|
15684
|
-
const found = byTag.get(tag);
|
|
15685
|
-
if (found == null) return null;
|
|
15686
|
-
selected.push(found);
|
|
15687
|
-
}
|
|
15688
|
-
return selected.length === 1 ? selected[0] : combineChannels(selected);
|
|
15689
|
-
};
|
|
15690
|
-
})() : void 0;
|
|
16205
|
+
const resolveChannel = registry != null && registry.length > 1 ? buildChannelSubsetResolver(channel, registry) : void 0;
|
|
15691
16206
|
let secure;
|
|
15692
16207
|
if (anyDuplexSecure || exchangeSecure) {
|
|
15693
16208
|
const storage = options.storage;
|
|
@@ -15758,19 +16273,24 @@ function serveChannel(runtime, channel, options) {
|
|
|
15758
16273
|
}
|
|
15759
16274
|
runtime.addHandlers([...options.handlers ?? [], ...acceptors]);
|
|
15760
16275
|
const soleDuplex = singleDuplex ? duplexCarriers[0] : void 0;
|
|
16276
|
+
let disposed = false;
|
|
15761
16277
|
const receive = (connection, frame) => {
|
|
16278
|
+
if (disposed) return;
|
|
15762
16279
|
if (soleDuplex == null) throw new Error(duplexCarriers.length === 0 ? "serveChannel: no duplex carrier to receive on (this server has no socket transport)" : "serveChannel: several duplex carriers — feed each carrier handle's receive() directly");
|
|
15763
16280
|
soleDuplex.receive(connection, frame);
|
|
15764
16281
|
};
|
|
15765
16282
|
const drop = (connection) => {
|
|
16283
|
+
if (disposed) return;
|
|
15766
16284
|
soleDuplex?.drop(connection);
|
|
15767
16285
|
};
|
|
15768
16286
|
const pushToClient = (target, request, pushOptions) => {
|
|
16287
|
+
if (disposed) throw new Error("serveChannel: server disposed");
|
|
15769
16288
|
const owner = target instanceof RuntimeCoordinate ? acceptors.find((acceptor) => acceptor.ownsLiveConnectionFor(target)) : acceptors.find((acceptor) => acceptor.hasConnection(target));
|
|
15770
16289
|
if (owner == null) throw new Error("serveChannel: no duplex carrier holds a connection for the push target");
|
|
15771
16290
|
return owner.pushToClient(runtime, target, request, pushOptions);
|
|
15772
16291
|
};
|
|
15773
16292
|
const broadcast = (makeRequest, broadcastOptions) => {
|
|
16293
|
+
if (disposed) throw new Error("serveChannel: server disposed");
|
|
15774
16294
|
if (!singleDuplex) throw new Error("serveChannel: broadcast requires exactly one duplex carrier — broadcast over a specific acceptors[i] instead");
|
|
15775
16295
|
acceptors[0].broadcast(makeRequest, {
|
|
15776
16296
|
runtime,
|
|
@@ -15820,20 +16340,32 @@ function serveChannel(runtime, channel, options) {
|
|
|
15820
16340
|
upgrade: carrier.upgrade
|
|
15821
16341
|
});
|
|
15822
16342
|
}
|
|
16343
|
+
const activeFetch = createActionFetchHandler(runtime, {
|
|
16344
|
+
cors: exchangeCarrier?.cors,
|
|
16345
|
+
onWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => (upgraders.find((u) => u.isUpgrade(request, url)) ?? upgraders[0]).upgrade(request, url),
|
|
16346
|
+
isWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => upgraders.some((u) => u.isUpgrade(request, url)),
|
|
16347
|
+
isActionPath: exchangeCarrier != null ? exchangeCarrier.isActionPath ?? (() => true) : () => false,
|
|
16348
|
+
security: exchangeSecurity,
|
|
16349
|
+
useErrorStatus: exchangeCarrier?.useErrorStatus,
|
|
16350
|
+
logger: options.logger,
|
|
16351
|
+
transportLabel: exchangeCarrier?.carrierLabel
|
|
16352
|
+
});
|
|
16353
|
+
const fetch = (request) => disposed ? Promise.resolve(new Response("serveChannel: server disposed", {
|
|
16354
|
+
status: 503,
|
|
16355
|
+
headers: { "cache-control": "no-store" }
|
|
16356
|
+
})) : activeFetch(request);
|
|
16357
|
+
const dispose = () => {
|
|
16358
|
+
if (disposed) return;
|
|
16359
|
+
disposed = true;
|
|
16360
|
+
for (const carrier of duplexCarriers) carrier._dispose?.();
|
|
16361
|
+
for (const acceptor of acceptors) acceptor.dispose();
|
|
16362
|
+
};
|
|
15823
16363
|
return {
|
|
15824
16364
|
acceptors,
|
|
15825
|
-
fetch
|
|
15826
|
-
cors: exchangeCarrier?.cors,
|
|
15827
|
-
onWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => (upgraders.find((u) => u.isUpgrade(request, url)) ?? upgraders[0]).upgrade(request, url),
|
|
15828
|
-
isWebSocketUpgrade: upgraders.length === 0 ? void 0 : (request, url) => upgraders.some((u) => u.isUpgrade(request, url)),
|
|
15829
|
-
isActionPath: exchangeCarrier != null ? exchangeCarrier.isActionPath ?? (() => true) : () => false,
|
|
15830
|
-
security: exchangeSecurity,
|
|
15831
|
-
useErrorStatus: exchangeCarrier?.useErrorStatus,
|
|
15832
|
-
logger: options.logger,
|
|
15833
|
-
transportLabel: exchangeCarrier?.carrierLabel
|
|
15834
|
-
}),
|
|
16365
|
+
fetch,
|
|
15835
16366
|
receive,
|
|
15836
16367
|
drop,
|
|
16368
|
+
dispose,
|
|
15837
16369
|
pushToClient,
|
|
15838
16370
|
broadcast,
|
|
15839
16371
|
connections
|
|
@@ -15883,7 +16415,7 @@ err_nice_transport.createChildDomain({
|
|
|
15883
16415
|
*/
|
|
15884
16416
|
function wsAcceptorCarrier(options) {
|
|
15885
16417
|
return {
|
|
15886
|
-
...createDuplexCarrierLifecycle(),
|
|
16418
|
+
...createDuplexCarrierLifecycle(options.inboundLimits),
|
|
15887
16419
|
shape: "duplex",
|
|
15888
16420
|
carrierLabel: options.carrierLabel ?? "ws",
|
|
15889
16421
|
secure: options.secure,
|
|
@@ -16405,11 +16937,11 @@ var VALUE = "value";
|
|
|
16405
16937
|
var isDraft = (value) => !!value && !!value[DRAFT_STATE];
|
|
16406
16938
|
function isDraftable(value) {
|
|
16407
16939
|
if (!value) return false;
|
|
16408
|
-
return isPlainObject$
|
|
16940
|
+
return isPlainObject$2(value) || isArray(value) || !!value[DRAFTABLE] || !!value[CONSTRUCTOR]?.[DRAFTABLE] || isMap(value) || isSet(value);
|
|
16409
16941
|
}
|
|
16410
16942
|
var objectCtorString = O[PROTOTYPE][CONSTRUCTOR].toString();
|
|
16411
16943
|
var cachedCtorStrings = /* @__PURE__ */ new WeakMap();
|
|
16412
|
-
function isPlainObject$
|
|
16944
|
+
function isPlainObject$2(value) {
|
|
16413
16945
|
if (!value || !isObjectish(value)) return false;
|
|
16414
16946
|
const proto = getPrototypeOf(value);
|
|
16415
16947
|
if (proto === null || proto === O[PROTOTYPE]) return true;
|
|
@@ -16464,7 +16996,7 @@ function shallowCopy(base, strict) {
|
|
|
16464
16996
|
if (isMap(base)) return new Map(base);
|
|
16465
16997
|
if (isSet(base)) return new Set(base);
|
|
16466
16998
|
if (isArray(base)) return Array[PROTOTYPE].slice.call(base);
|
|
16467
|
-
const isPlain = isPlainObject$
|
|
16999
|
+
const isPlain = isPlainObject$2(base);
|
|
16468
17000
|
if (strict === true || strict === "class_only" && !isPlain) {
|
|
16469
17001
|
const descriptors = O.getOwnPropertyDescriptors(base);
|
|
16470
17002
|
delete descriptors[DRAFT_STATE];
|
|
@@ -17748,20 +18280,44 @@ const err_realm = err_nice.createChildDomain({
|
|
|
17748
18280
|
});
|
|
17749
18281
|
//#endregion
|
|
17750
18282
|
//#region ../nice-realm/src/RealmDefinition/Schema/validateValue.ts
|
|
17751
|
-
function isPlainObject(value) {
|
|
18283
|
+
function isPlainObject$1(value) {
|
|
17752
18284
|
return typeof value === "object" && value != null && !Array.isArray(value) && !(value instanceof Uint8Array);
|
|
17753
18285
|
}
|
|
17754
18286
|
/** `undefined` = valid; otherwise where and what was expected. */
|
|
17755
18287
|
function validateValue(node, value) {
|
|
17756
18288
|
switch (node.kind) {
|
|
17757
|
-
case "string":
|
|
17758
|
-
|
|
17759
|
-
|
|
17760
|
-
|
|
17761
|
-
|
|
17762
|
-
|
|
17763
|
-
|
|
17764
|
-
|
|
18289
|
+
case "string":
|
|
18290
|
+
if (typeof value !== "string") return {
|
|
18291
|
+
path: [],
|
|
18292
|
+
expected: "string"
|
|
18293
|
+
};
|
|
18294
|
+
if (node.maxLength != null && value.length > node.maxLength) return {
|
|
18295
|
+
path: [],
|
|
18296
|
+
expected: `a string of at most ${node.maxLength} characters`
|
|
18297
|
+
};
|
|
18298
|
+
return;
|
|
18299
|
+
case "number":
|
|
18300
|
+
if (typeof value !== "number") return {
|
|
18301
|
+
path: [],
|
|
18302
|
+
expected: "number"
|
|
18303
|
+
};
|
|
18304
|
+
if ((node.min != null || node.max != null || node.integer === true) && !Number.isFinite(value)) return {
|
|
18305
|
+
path: [],
|
|
18306
|
+
expected: "a finite number"
|
|
18307
|
+
};
|
|
18308
|
+
if (node.integer === true && !Number.isInteger(value)) return {
|
|
18309
|
+
path: [],
|
|
18310
|
+
expected: "an integer"
|
|
18311
|
+
};
|
|
18312
|
+
if (node.min != null && value < node.min) return {
|
|
18313
|
+
path: [],
|
|
18314
|
+
expected: `a number >= ${node.min}`
|
|
18315
|
+
};
|
|
18316
|
+
if (node.max != null && value > node.max) return {
|
|
18317
|
+
path: [],
|
|
18318
|
+
expected: `a number <= ${node.max}`
|
|
18319
|
+
};
|
|
18320
|
+
return;
|
|
17765
18321
|
case "boolean": return typeof value === "boolean" ? void 0 : {
|
|
17766
18322
|
path: [],
|
|
17767
18323
|
expected: "boolean"
|
|
@@ -17778,7 +18334,7 @@ function validateValue(node, value) {
|
|
|
17778
18334
|
expected: "one of the union options"
|
|
17779
18335
|
};
|
|
17780
18336
|
case "object":
|
|
17781
|
-
if (!isPlainObject(value)) return {
|
|
18337
|
+
if (!isPlainObject$1(value)) return {
|
|
17782
18338
|
path: [],
|
|
17783
18339
|
expected: "object"
|
|
17784
18340
|
};
|
|
@@ -17803,10 +18359,14 @@ function validateValue(node, value) {
|
|
|
17803
18359
|
}
|
|
17804
18360
|
return;
|
|
17805
18361
|
case "record":
|
|
17806
|
-
if (!isPlainObject(value)) return {
|
|
18362
|
+
if (!isPlainObject$1(value)) return {
|
|
17807
18363
|
path: [],
|
|
17808
18364
|
expected: "record"
|
|
17809
18365
|
};
|
|
18366
|
+
if (node.maxKeys != null && Object.keys(value).length > node.maxKeys) return {
|
|
18367
|
+
path: [],
|
|
18368
|
+
expected: `a record with at most ${node.maxKeys} entries`
|
|
18369
|
+
};
|
|
17810
18370
|
for (const [key, entry] of Object.entries(value)) {
|
|
17811
18371
|
const invalid = validateValue(node.value, entry);
|
|
17812
18372
|
if (invalid != null) return {
|
|
@@ -17820,6 +18380,10 @@ function validateValue(node, value) {
|
|
|
17820
18380
|
path: [],
|
|
17821
18381
|
expected: "array"
|
|
17822
18382
|
};
|
|
18383
|
+
if (node.maxItems != null && value.length > node.maxItems) return {
|
|
18384
|
+
path: [],
|
|
18385
|
+
expected: `an array of at most ${node.maxItems} items`
|
|
18386
|
+
};
|
|
17823
18387
|
for (let i = 0; i < value.length; i++) {
|
|
17824
18388
|
const invalid = validateValue(node.item, value[i]);
|
|
17825
18389
|
if (invalid != null) return {
|
|
@@ -18304,8 +18868,8 @@ const WIRE_OP_TO_IMMER = {
|
|
|
18304
18868
|
[REALM_OP.add]: "add",
|
|
18305
18869
|
[REALM_OP.remove]: "remove"
|
|
18306
18870
|
};
|
|
18307
|
-
function unwrapOptional$
|
|
18308
|
-
return node.kind === "optional" ? unwrapOptional$
|
|
18871
|
+
function unwrapOptional$6(node) {
|
|
18872
|
+
return node.kind === "optional" ? unwrapOptional$6(node.inner) : node;
|
|
18309
18873
|
}
|
|
18310
18874
|
/** The schema node a name path addresses (undefined when the path leaves the schema). */
|
|
18311
18875
|
function schemaNodeAtPath(root, path) {
|
|
@@ -18316,7 +18880,7 @@ function schemaNodeAtPath(root, path) {
|
|
|
18316
18880
|
node = typeof seg === "string" ? entries[seg] : void 0;
|
|
18317
18881
|
entries = void 0;
|
|
18318
18882
|
} else if (node != null) {
|
|
18319
|
-
const inner = unwrapOptional$
|
|
18883
|
+
const inner = unwrapOptional$6(node);
|
|
18320
18884
|
if (inner.kind === "object") node = inner.entries[seg];
|
|
18321
18885
|
else if (inner.kind === "record") node = inner.value;
|
|
18322
18886
|
else return void 0;
|
|
@@ -18325,7 +18889,7 @@ function schemaNodeAtPath(root, path) {
|
|
|
18325
18889
|
}
|
|
18326
18890
|
return node;
|
|
18327
18891
|
}
|
|
18328
|
-
function getAtPath$
|
|
18892
|
+
function getAtPath$6(state, path) {
|
|
18329
18893
|
let current = state;
|
|
18330
18894
|
for (const seg of path) {
|
|
18331
18895
|
if (current == null || typeof current !== "object") return void 0;
|
|
@@ -18337,7 +18901,7 @@ function getAtPath$5(state, path) {
|
|
|
18337
18901
|
function arrayCutIndex(root, path) {
|
|
18338
18902
|
for (let i = 1; i < path.length; i++) {
|
|
18339
18903
|
const node = schemaNodeAtPath(root, path.slice(0, i));
|
|
18340
|
-
if (node != null && unwrapOptional$
|
|
18904
|
+
if (node != null && unwrapOptional$6(node).kind === "array") return i;
|
|
18341
18905
|
}
|
|
18342
18906
|
}
|
|
18343
18907
|
/**
|
|
@@ -18361,7 +18925,7 @@ function canonicalizeStatePatches(patches, stateAfter, schemaRoot) {
|
|
|
18361
18925
|
out.push({
|
|
18362
18926
|
op: "replace",
|
|
18363
18927
|
path: arrayPath,
|
|
18364
|
-
value: getAtPath$
|
|
18928
|
+
value: getAtPath$6(stateAfter, arrayPath)
|
|
18365
18929
|
});
|
|
18366
18930
|
}
|
|
18367
18931
|
return out;
|
|
@@ -18561,10 +19125,10 @@ function viewSignatureKey(avatar) {
|
|
|
18561
19125
|
* leaves are covered too). For `remove`, from the current state alone. Expansion is bounded by
|
|
18562
19126
|
* `maxLeaves` (an ingress limit — a hostile deep-subtree write must not become CPU).
|
|
18563
19127
|
*/
|
|
18564
|
-
function unwrapOptional$
|
|
18565
|
-
return node.kind === "optional" ? unwrapOptional$
|
|
19128
|
+
function unwrapOptional$5(node) {
|
|
19129
|
+
return node.kind === "optional" ? unwrapOptional$5(node.inner) : node;
|
|
18566
19130
|
}
|
|
18567
|
-
function getAtPath$
|
|
19131
|
+
function getAtPath$5(state, path) {
|
|
18568
19132
|
let current = state;
|
|
18569
19133
|
for (const seg of path) {
|
|
18570
19134
|
if (current == null || typeof current !== "object") return void 0;
|
|
@@ -18586,7 +19150,7 @@ function expandWriteToLeaves(options) {
|
|
|
18586
19150
|
leaves.push(leaf);
|
|
18587
19151
|
};
|
|
18588
19152
|
const walk = (schemaNode, path, value, prev) => {
|
|
18589
|
-
const inner = unwrapOptional$
|
|
19153
|
+
const inner = unwrapOptional$5(schemaNode);
|
|
18590
19154
|
if (inner.kind === "object") {
|
|
18591
19155
|
for (const [key, child] of Object.entries(inner.entries)) walk(child, [...path, key], value == null ? void 0 : value[key], prev == null ? void 0 : prev[key]);
|
|
18592
19156
|
return;
|
|
@@ -18600,7 +19164,7 @@ function expandWriteToLeaves(options) {
|
|
|
18600
19164
|
}
|
|
18601
19165
|
push(path);
|
|
18602
19166
|
};
|
|
18603
|
-
const prev = getAtPath$
|
|
19167
|
+
const prev = getAtPath$5(options.state, options.path);
|
|
18604
19168
|
walk(node, [...options.path], options.op === "remove" ? void 0 : options.value, prev);
|
|
18605
19169
|
return leaves;
|
|
18606
19170
|
}
|
|
@@ -18612,6 +19176,14 @@ function expandWriteToLeaves(options) {
|
|
|
18612
19176
|
* slice of optimism that can later roll back), `prev`/`state` come from the writer's projected
|
|
18613
19177
|
* view. A NiceError here rejects the write in the same tick, before anything renders.
|
|
18614
19178
|
*/
|
|
19179
|
+
function getProjectedAtPath(state, path) {
|
|
19180
|
+
let current = state;
|
|
19181
|
+
for (const seg of path) {
|
|
19182
|
+
if (current == null || typeof current !== "object") return void 0;
|
|
19183
|
+
current = current[seg];
|
|
19184
|
+
}
|
|
19185
|
+
return current;
|
|
19186
|
+
}
|
|
18615
19187
|
function predictWrite(options) {
|
|
18616
19188
|
const { realm, avatar, state, basisVersion } = options;
|
|
18617
19189
|
for (const patch of options.patches) {
|
|
@@ -18627,6 +19199,17 @@ function predictWrite(options) {
|
|
|
18627
19199
|
path: [...path, ...invalid.path].join("."),
|
|
18628
19200
|
expected: invalid.expected
|
|
18629
19201
|
});
|
|
19202
|
+
for (let i = 1; i < path.length; i++) {
|
|
19203
|
+
let ancestor = schemaNodeAtPath(realm.stateDef, path.slice(0, i));
|
|
19204
|
+
while (ancestor?.kind === "optional") ancestor = ancestor.inner;
|
|
19205
|
+
if (ancestor?.kind !== "record" || ancestor.maxKeys == null) continue;
|
|
19206
|
+
const container = getProjectedAtPath(state, path.slice(0, i));
|
|
19207
|
+
if (container == null || typeof container !== "object" || Array.isArray(container)) continue;
|
|
19208
|
+
if (!(path[i] in container) && Object.keys(container).length >= ancestor.maxKeys) return err_realm.fromId("value_invalid", {
|
|
19209
|
+
path: path.slice(0, i).join("."),
|
|
19210
|
+
expected: `a record with at most ${ancestor.maxKeys} entries`
|
|
19211
|
+
});
|
|
19212
|
+
}
|
|
18630
19213
|
}
|
|
18631
19214
|
const leaves = expandWriteToLeaves({
|
|
18632
19215
|
schemaRoot: realm.stateDef,
|
|
@@ -18643,8 +19226,8 @@ function predictWrite(options) {
|
|
|
18643
19226
|
const verdict = evalAlterCond(match.rule.alter, {
|
|
18644
19227
|
avatar,
|
|
18645
19228
|
params: match.params,
|
|
18646
|
-
prev: getAtPath$
|
|
18647
|
-
next: patch.op === "remove" ? void 0 : getAtPath$
|
|
19229
|
+
prev: getAtPath$4(state, leafPath),
|
|
19230
|
+
next: patch.op === "remove" ? void 0 : getAtPath$4(patch.value, rel),
|
|
18648
19231
|
state,
|
|
18649
19232
|
basisVersion
|
|
18650
19233
|
}, void 0);
|
|
@@ -18654,7 +19237,7 @@ function predictWrite(options) {
|
|
|
18654
19237
|
}
|
|
18655
19238
|
return true;
|
|
18656
19239
|
}
|
|
18657
|
-
function getAtPath$
|
|
19240
|
+
function getAtPath$4(state, path) {
|
|
18658
19241
|
let current = state;
|
|
18659
19242
|
for (const seg of path) {
|
|
18660
19243
|
if (current == null || typeof current !== "object") return void 0;
|
|
@@ -18686,10 +19269,10 @@ function withStructuralParents(state, patches, schemaRoot) {
|
|
|
18686
19269
|
const prefix = patch.path.slice(0, depth);
|
|
18687
19270
|
if (prefixResolves(state, out ?? patches.slice(0, index), prefix)) continue;
|
|
18688
19271
|
const parentNode = depth === 1 ? void 0 : schemaNodeAtPath(schemaRoot, prefix.slice(0, -1));
|
|
18689
|
-
if (parentNode != null && unwrapOptional$
|
|
19272
|
+
if (parentNode != null && unwrapOptional$4(parentNode).kind === "record") break;
|
|
18690
19273
|
const node = schemaNodeAtPath(schemaRoot, prefix);
|
|
18691
19274
|
if (node == null) break;
|
|
18692
|
-
const kind = unwrapOptional$
|
|
19275
|
+
const kind = unwrapOptional$4(node).kind;
|
|
18693
19276
|
if (kind !== "object" && kind !== "record") break;
|
|
18694
19277
|
out ??= patches.slice(0, index);
|
|
18695
19278
|
out.push({
|
|
@@ -18709,14 +19292,14 @@ function prefixResolves(state, earlier, prefix) {
|
|
|
18709
19292
|
if (patch.path.length > prefix.length) continue;
|
|
18710
19293
|
if (!patch.path.every((seg, j) => String(seg) === String(prefix[j]))) continue;
|
|
18711
19294
|
if (patch.op === "remove") return false;
|
|
18712
|
-
return getAtPath$
|
|
19295
|
+
return getAtPath$3(patch.value, prefix.slice(patch.path.length)) !== void 0;
|
|
18713
19296
|
}
|
|
18714
|
-
return getAtPath$
|
|
19297
|
+
return getAtPath$3(state, prefix) !== void 0;
|
|
18715
19298
|
}
|
|
18716
|
-
function unwrapOptional$
|
|
18717
|
-
return node.kind === "optional" ? unwrapOptional$
|
|
19299
|
+
function unwrapOptional$4(node) {
|
|
19300
|
+
return node.kind === "optional" ? unwrapOptional$4(node.inner) : node;
|
|
18718
19301
|
}
|
|
18719
|
-
function getAtPath$
|
|
19302
|
+
function getAtPath$3(value, path) {
|
|
18720
19303
|
let current = value;
|
|
18721
19304
|
for (const seg of path) {
|
|
18722
19305
|
if (current == null || typeof current !== "object") return void 0;
|
|
@@ -20271,20 +20854,20 @@ function assertTransientRoots(root, dotPaths) {
|
|
|
20271
20854
|
/** Walk a concrete (literal-only) path through the schema; `undefined` if it leaves the schema. */
|
|
20272
20855
|
function resolveConcretePath(node, segments, index) {
|
|
20273
20856
|
if (index >= segments.length) return node;
|
|
20274
|
-
const inner = unwrapOptional$
|
|
20857
|
+
const inner = unwrapOptional$3(node);
|
|
20275
20858
|
if (inner.kind === "object") {
|
|
20276
20859
|
const child = inner.entries[segments[index]];
|
|
20277
20860
|
return child == null ? void 0 : resolveConcretePath(child, segments, index + 1);
|
|
20278
20861
|
}
|
|
20279
20862
|
if (inner.kind === "record") return resolveConcretePath(inner.value, segments, index + 1);
|
|
20280
20863
|
}
|
|
20281
|
-
function unwrapOptional$
|
|
20282
|
-
return node.kind === "optional" ? unwrapOptional$
|
|
20864
|
+
function unwrapOptional$3(node) {
|
|
20865
|
+
return node.kind === "optional" ? unwrapOptional$3(node.inner) : node;
|
|
20283
20866
|
}
|
|
20284
20867
|
/** `undefined` = the pattern can match; otherwise a description of why it never will. */
|
|
20285
20868
|
function checkSegments(node, segments, index) {
|
|
20286
20869
|
if (index >= segments.length) return void 0;
|
|
20287
|
-
const inner = unwrapOptional$
|
|
20870
|
+
const inner = unwrapOptional$3(node);
|
|
20288
20871
|
const seg = segments[index];
|
|
20289
20872
|
const at = describePrefix(segments, index);
|
|
20290
20873
|
if (inner.kind === "object") {
|
|
@@ -20403,147 +20986,6 @@ var RealmRuleTrie = class {
|
|
|
20403
20986
|
}
|
|
20404
20987
|
};
|
|
20405
20988
|
//#endregion
|
|
20406
|
-
//#region ../nice-realm/src/RealmDefinition/Schema/sha256.ts
|
|
20407
|
-
/**
|
|
20408
|
-
* Synchronous SHA-256 over a UTF-8 string → lowercase hex. The schema hash must be computable at
|
|
20409
|
-
* `defineRealm` time (module evaluation, both Node and workerd) — `crypto.subtle.digest` is async,
|
|
20410
|
-
* so a small pure implementation keeps the definition object synchronous and platform-stable.
|
|
20411
|
-
* Verified against the FIPS 180-4 test vectors in `sha256.test.ts`.
|
|
20412
|
-
*/
|
|
20413
|
-
const K = new Uint32Array([
|
|
20414
|
-
1116352408,
|
|
20415
|
-
1899447441,
|
|
20416
|
-
3049323471,
|
|
20417
|
-
3921009573,
|
|
20418
|
-
961987163,
|
|
20419
|
-
1508970993,
|
|
20420
|
-
2453635748,
|
|
20421
|
-
2870763221,
|
|
20422
|
-
3624381080,
|
|
20423
|
-
310598401,
|
|
20424
|
-
607225278,
|
|
20425
|
-
1426881987,
|
|
20426
|
-
1925078388,
|
|
20427
|
-
2162078206,
|
|
20428
|
-
2614888103,
|
|
20429
|
-
3248222580,
|
|
20430
|
-
3835390401,
|
|
20431
|
-
4022224774,
|
|
20432
|
-
264347078,
|
|
20433
|
-
604807628,
|
|
20434
|
-
770255983,
|
|
20435
|
-
1249150122,
|
|
20436
|
-
1555081692,
|
|
20437
|
-
1996064986,
|
|
20438
|
-
2554220882,
|
|
20439
|
-
2821834349,
|
|
20440
|
-
2952996808,
|
|
20441
|
-
3210313671,
|
|
20442
|
-
3336571891,
|
|
20443
|
-
3584528711,
|
|
20444
|
-
113926993,
|
|
20445
|
-
338241895,
|
|
20446
|
-
666307205,
|
|
20447
|
-
773529912,
|
|
20448
|
-
1294757372,
|
|
20449
|
-
1396182291,
|
|
20450
|
-
1695183700,
|
|
20451
|
-
1986661051,
|
|
20452
|
-
2177026350,
|
|
20453
|
-
2456956037,
|
|
20454
|
-
2730485921,
|
|
20455
|
-
2820302411,
|
|
20456
|
-
3259730800,
|
|
20457
|
-
3345764771,
|
|
20458
|
-
3516065817,
|
|
20459
|
-
3600352804,
|
|
20460
|
-
4094571909,
|
|
20461
|
-
275423344,
|
|
20462
|
-
430227734,
|
|
20463
|
-
506948616,
|
|
20464
|
-
659060556,
|
|
20465
|
-
883997877,
|
|
20466
|
-
958139571,
|
|
20467
|
-
1322822218,
|
|
20468
|
-
1537002063,
|
|
20469
|
-
1747873779,
|
|
20470
|
-
1955562222,
|
|
20471
|
-
2024104815,
|
|
20472
|
-
2227730452,
|
|
20473
|
-
2361852424,
|
|
20474
|
-
2428436474,
|
|
20475
|
-
2756734187,
|
|
20476
|
-
3204031479,
|
|
20477
|
-
3329325298
|
|
20478
|
-
]);
|
|
20479
|
-
function rotr(x, n) {
|
|
20480
|
-
return x >>> n | x << 32 - n;
|
|
20481
|
-
}
|
|
20482
|
-
/** SHA-256 of a UTF-8 string, as lowercase hex. */
|
|
20483
|
-
function sha256Hex(input) {
|
|
20484
|
-
const bytes = new TextEncoder().encode(input);
|
|
20485
|
-
const bitLen = bytes.length * 8;
|
|
20486
|
-
const paddedLen = (bytes.length + 8 >> 6) + 1 << 6;
|
|
20487
|
-
const padded = new Uint8Array(paddedLen);
|
|
20488
|
-
padded.set(bytes);
|
|
20489
|
-
padded[bytes.length] = 128;
|
|
20490
|
-
const view = new DataView(padded.buffer);
|
|
20491
|
-
view.setUint32(paddedLen - 8, Math.floor(bitLen / 4294967296), false);
|
|
20492
|
-
view.setUint32(paddedLen - 4, bitLen >>> 0, false);
|
|
20493
|
-
const h = new Uint32Array([
|
|
20494
|
-
1779033703,
|
|
20495
|
-
3144134277,
|
|
20496
|
-
1013904242,
|
|
20497
|
-
2773480762,
|
|
20498
|
-
1359893119,
|
|
20499
|
-
2600822924,
|
|
20500
|
-
528734635,
|
|
20501
|
-
1541459225
|
|
20502
|
-
]);
|
|
20503
|
-
const w = new Uint32Array(64);
|
|
20504
|
-
for (let offset = 0; offset < paddedLen; offset += 64) {
|
|
20505
|
-
for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4, false);
|
|
20506
|
-
for (let i = 16; i < 64; i++) {
|
|
20507
|
-
const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ w[i - 15] >>> 3;
|
|
20508
|
-
const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ w[i - 2] >>> 10;
|
|
20509
|
-
w[i] = w[i - 16] + s0 + w[i - 7] + s1 >>> 0;
|
|
20510
|
-
}
|
|
20511
|
-
let a = h[0];
|
|
20512
|
-
let b = h[1];
|
|
20513
|
-
let c = h[2];
|
|
20514
|
-
let d = h[3];
|
|
20515
|
-
let e = h[4];
|
|
20516
|
-
let f = h[5];
|
|
20517
|
-
let g = h[6];
|
|
20518
|
-
let hh = h[7];
|
|
20519
|
-
for (let i = 0; i < 64; i++) {
|
|
20520
|
-
const s1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25);
|
|
20521
|
-
const ch = e & f ^ ~e & g;
|
|
20522
|
-
const temp1 = hh + s1 + ch + K[i] + w[i] >>> 0;
|
|
20523
|
-
const temp2 = (rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + (a & b ^ a & c ^ b & c) >>> 0;
|
|
20524
|
-
hh = g;
|
|
20525
|
-
g = f;
|
|
20526
|
-
f = e;
|
|
20527
|
-
e = d + temp1 >>> 0;
|
|
20528
|
-
d = c;
|
|
20529
|
-
c = b;
|
|
20530
|
-
b = a;
|
|
20531
|
-
a = temp1 + temp2 >>> 0;
|
|
20532
|
-
}
|
|
20533
|
-
h[0] = h[0] + a >>> 0;
|
|
20534
|
-
h[1] = h[1] + b >>> 0;
|
|
20535
|
-
h[2] = h[2] + c >>> 0;
|
|
20536
|
-
h[3] = h[3] + d >>> 0;
|
|
20537
|
-
h[4] = h[4] + e >>> 0;
|
|
20538
|
-
h[5] = h[5] + f >>> 0;
|
|
20539
|
-
h[6] = h[6] + g >>> 0;
|
|
20540
|
-
h[7] = h[7] + hh >>> 0;
|
|
20541
|
-
}
|
|
20542
|
-
let hex = "";
|
|
20543
|
-
for (let i = 0; i < 8; i++) hex += h[i].toString(16).padStart(8, "0");
|
|
20544
|
-
return hex;
|
|
20545
|
-
}
|
|
20546
|
-
//#endregion
|
|
20547
20989
|
//#region ../nice-realm/src/RealmDefinition/Schema/schemaHash.ts
|
|
20548
20990
|
/**
|
|
20549
20991
|
* The realm schema hash (plan §4.1/§7.1-of-proposal): SHA-256 over a canonical serialization of
|
|
@@ -20553,13 +20995,24 @@ function sha256Hex(input) {
|
|
|
20553
20995
|
* stale mobile client would be data corruption, not an error.
|
|
20554
20996
|
*
|
|
20555
20997
|
* Known, documented limitation: an embedded standard-schema validator (`t.schema(...)`) is opaque
|
|
20556
|
-
* — its internals don't affect the hash (canonicalized as just `std`)
|
|
20557
|
-
*
|
|
20998
|
+
* — its internals don't affect the hash (canonicalized as just `std`) unless the leaf opts in
|
|
20999
|
+
* with `t.schema(v, { hashTag })`, which the consumer bumps on contract changes. Untagged, treat
|
|
21000
|
+
* embedded-validator edits as value-rule changes, not shape changes.
|
|
20558
21001
|
*/
|
|
20559
21002
|
function canonNode(node) {
|
|
20560
21003
|
switch (node.kind) {
|
|
20561
|
-
case "string":
|
|
21004
|
+
case "string": return node.maxLength == null ? node.kind : {
|
|
21005
|
+
k: "string",
|
|
21006
|
+
max: node.maxLength
|
|
21007
|
+
};
|
|
20562
21008
|
case "number":
|
|
21009
|
+
if (node.min == null && node.max == null && node.integer !== true) return node.kind;
|
|
21010
|
+
return {
|
|
21011
|
+
k: "number",
|
|
21012
|
+
...node.min != null ? { min: node.min } : {},
|
|
21013
|
+
...node.max != null ? { max: node.max } : {},
|
|
21014
|
+
...node.integer === true ? { int: true } : {}
|
|
21015
|
+
};
|
|
20563
21016
|
case "boolean": return node.kind;
|
|
20564
21017
|
case "literal": return {
|
|
20565
21018
|
k: "lit",
|
|
@@ -20577,16 +21030,31 @@ function canonNode(node) {
|
|
|
20577
21030
|
k: "obj",
|
|
20578
21031
|
e: Object.keys(node.entries).sort().map((n) => [n, canonNode(node.entries[n])])
|
|
20579
21032
|
};
|
|
20580
|
-
case "record":
|
|
20581
|
-
|
|
20582
|
-
|
|
20583
|
-
|
|
20584
|
-
|
|
20585
|
-
|
|
20586
|
-
|
|
20587
|
-
|
|
21033
|
+
case "record": {
|
|
21034
|
+
const base = {
|
|
21035
|
+
k: "rec",
|
|
21036
|
+
id: node.keyVar,
|
|
21037
|
+
v: canonNode(node.value)
|
|
21038
|
+
};
|
|
21039
|
+
return node.maxKeys == null ? base : {
|
|
21040
|
+
...base,
|
|
21041
|
+
max: node.maxKeys
|
|
21042
|
+
};
|
|
21043
|
+
}
|
|
21044
|
+
case "array": {
|
|
21045
|
+
const base = {
|
|
21046
|
+
k: "arr",
|
|
21047
|
+
i: canonNode(node.item)
|
|
21048
|
+
};
|
|
21049
|
+
return node.maxItems == null ? base : {
|
|
21050
|
+
...base,
|
|
21051
|
+
max: node.maxItems
|
|
21052
|
+
};
|
|
21053
|
+
}
|
|
21054
|
+
case "standard": return node.hashTag == null ? { k: "std" } : {
|
|
21055
|
+
k: "std",
|
|
21056
|
+
tag: node.hashTag
|
|
20588
21057
|
};
|
|
20589
|
-
case "standard": return { k: "std" };
|
|
20590
21058
|
}
|
|
20591
21059
|
}
|
|
20592
21060
|
/** Canonical serialization (deterministic across platforms — everything sorted). */
|
|
@@ -20605,11 +21073,11 @@ function computeSchemaHash(inputs) {
|
|
|
20605
21073
|
}
|
|
20606
21074
|
//#endregion
|
|
20607
21075
|
//#region ../nice-realm/src/RealmDefinition/Schema/tokenMap.ts
|
|
20608
|
-
function unwrapOptional$
|
|
20609
|
-
return node.kind === "optional" ? unwrapOptional$
|
|
21076
|
+
function unwrapOptional$2(node) {
|
|
21077
|
+
return node.kind === "optional" ? unwrapOptional$2(node.inner) : node;
|
|
20610
21078
|
}
|
|
20611
21079
|
function buildLevelForNode(node) {
|
|
20612
|
-
const inner = unwrapOptional$
|
|
21080
|
+
const inner = unwrapOptional$2(node);
|
|
20613
21081
|
if (inner.kind === "object") return buildLevel(inner.entries);
|
|
20614
21082
|
if (inner.kind === "record") return {
|
|
20615
21083
|
toToken: /* @__PURE__ */ new Map(),
|
|
@@ -20731,6 +21199,24 @@ function defineRealm(input) {
|
|
|
20731
21199
|
}
|
|
20732
21200
|
//#endregion
|
|
20733
21201
|
//#region ../nice-realm/src/RealmDefinition/Schema/t.ts
|
|
21202
|
+
/** Bounds are declaration errors when malformed — caught at `defineRealm` time, not at runtime. */
|
|
21203
|
+
function checkCount(name, value) {
|
|
21204
|
+
if (value == null) return void 0;
|
|
21205
|
+
if (!Number.isSafeInteger(value) || value < 0) throw new Error(`t: ${name} must be a non-negative safe integer, got ${value}`);
|
|
21206
|
+
return value;
|
|
21207
|
+
}
|
|
21208
|
+
function checkNumberOptions(options) {
|
|
21209
|
+
const { min, max, integer } = options;
|
|
21210
|
+
if (min != null && !Number.isFinite(min)) throw new Error(`t: number min must be finite, got ${min}`);
|
|
21211
|
+
if (max != null && !Number.isFinite(max)) throw new Error(`t: number max must be finite, got ${max}`);
|
|
21212
|
+
if (min != null && max != null && min > max) throw new Error(`t: number min (${min}) must be <= max (${max})`);
|
|
21213
|
+
if (integer != null && typeof integer !== "boolean") throw new Error(`t: number integer must be a boolean`);
|
|
21214
|
+
return {
|
|
21215
|
+
...min != null ? { min } : {},
|
|
21216
|
+
...max != null ? { max } : {},
|
|
21217
|
+
...integer === true ? { integer: true } : {}
|
|
21218
|
+
};
|
|
21219
|
+
}
|
|
20734
21220
|
function union(...args) {
|
|
20735
21221
|
const options = args.flatMap((arg) => Array.isArray(arg) ? arg : [arg]);
|
|
20736
21222
|
if (options.length < 2) throw new Error(`t.union needs at least 2 options, got ${options.length}`);
|
|
@@ -20745,11 +21231,18 @@ function union(...args) {
|
|
|
20745
21231
|
* schema hash, and (M4) the server-side value validator.
|
|
20746
21232
|
*/
|
|
20747
21233
|
const t = {
|
|
20748
|
-
string() {
|
|
20749
|
-
|
|
21234
|
+
string(options = {}) {
|
|
21235
|
+
const maxLength = checkCount("string maxLength", options.maxLength);
|
|
21236
|
+
return {
|
|
21237
|
+
kind: "string",
|
|
21238
|
+
...maxLength != null ? { maxLength } : {}
|
|
21239
|
+
};
|
|
20750
21240
|
},
|
|
20751
|
-
number() {
|
|
20752
|
-
return {
|
|
21241
|
+
number(options = {}) {
|
|
21242
|
+
return {
|
|
21243
|
+
kind: "number",
|
|
21244
|
+
...checkNumberOptions(options)
|
|
21245
|
+
};
|
|
20753
21246
|
},
|
|
20754
21247
|
boolean() {
|
|
20755
21248
|
return { kind: "boolean" };
|
|
@@ -20780,29 +21273,36 @@ const t = {
|
|
|
20780
21273
|
varName
|
|
20781
21274
|
};
|
|
20782
21275
|
},
|
|
20783
|
-
record(key, value) {
|
|
21276
|
+
record(key, value, options = {}) {
|
|
21277
|
+
const maxKeys = checkCount("record maxKeys", options.maxKeys);
|
|
20784
21278
|
return {
|
|
20785
21279
|
kind: "record",
|
|
20786
21280
|
keyVar: key.varName,
|
|
20787
|
-
value
|
|
21281
|
+
value,
|
|
21282
|
+
...maxKeys != null ? { maxKeys } : {}
|
|
20788
21283
|
};
|
|
20789
21284
|
},
|
|
20790
21285
|
/** Leaf-replace semantics only in v1 (proposal §7.8) — prefer keyed {@link t.record} collections. */
|
|
20791
|
-
array(item) {
|
|
21286
|
+
array(item, options = {}) {
|
|
21287
|
+
const maxItems = checkCount("array maxItems", options.maxItems);
|
|
20792
21288
|
return {
|
|
20793
21289
|
kind: "array",
|
|
20794
|
-
item
|
|
21290
|
+
item,
|
|
21291
|
+
...maxItems != null ? { maxItems } : {}
|
|
20795
21292
|
};
|
|
20796
21293
|
},
|
|
20797
21294
|
/**
|
|
20798
|
-
* Embed a standard-schema validator (e.g. valibot) at a leaf.
|
|
20799
|
-
*
|
|
20800
|
-
*
|
|
21295
|
+
* Embed a standard-schema validator (e.g. valibot) at a leaf. The embedded schema's internals
|
|
21296
|
+
* are opaque to the schema hash — editing it does NOT change the realm's schemaHash. Pass a
|
|
21297
|
+
* `hashTag` (and bump it on every contract change) to opt the leaf's contract into the hash;
|
|
21298
|
+
* untagged, treat embedded-validator changes as value-rule changes, not shape changes.
|
|
20801
21299
|
*/
|
|
20802
|
-
schema(schema) {
|
|
21300
|
+
schema(schema, options = {}) {
|
|
21301
|
+
if (options.hashTag != null && (typeof options.hashTag !== "string" || options.hashTag === "")) throw new Error("t.schema: hashTag must be a non-empty string");
|
|
20803
21302
|
return {
|
|
20804
21303
|
kind: "standard",
|
|
20805
|
-
schema
|
|
21304
|
+
schema,
|
|
21305
|
+
...options.hashTag != null ? { hashTag: options.hashTag } : {}
|
|
20806
21306
|
};
|
|
20807
21307
|
},
|
|
20808
21308
|
/**
|
|
@@ -20815,6 +21315,202 @@ const t = {
|
|
|
20815
21315
|
}
|
|
20816
21316
|
};
|
|
20817
21317
|
//#endregion
|
|
21318
|
+
//#region ../nice-realm/src/RealmDefinition/Schema/boundedState.ts
|
|
21319
|
+
/**
|
|
21320
|
+
* State-aware bound enforcement (the second layer over `validateValue`'s per-value checks).
|
|
21321
|
+
* `validateValue` only ever sees the value being written, so it cannot catch a bound whose truth
|
|
21322
|
+
* lives in the *surrounding* state — the canonical case: `t.record(…, { maxKeys: 8 })` filled one
|
|
21323
|
+
* incremental `record.$id` add at a time, where each child value is individually valid. These
|
|
21324
|
+
* walks run against the **candidate next state** after a whole patch batch (so remove+add nets
|
|
21325
|
+
* out), and once over the full tree at boot/restore/migration.
|
|
21326
|
+
*
|
|
21327
|
+
* Everything here is bounds-only and skip-fast: a schema without bounds costs one memoized lookup
|
|
21328
|
+
* and nothing else, and subtrees carrying no bounds are never entered.
|
|
21329
|
+
*/
|
|
21330
|
+
const HAS_BOUNDS = /* @__PURE__ */ new WeakMap();
|
|
21331
|
+
function nodeHasBounds(node) {
|
|
21332
|
+
const cached = HAS_BOUNDS.get(node);
|
|
21333
|
+
if (cached != null) return cached;
|
|
21334
|
+
let result;
|
|
21335
|
+
switch (node.kind) {
|
|
21336
|
+
case "string":
|
|
21337
|
+
result = node.maxLength != null;
|
|
21338
|
+
break;
|
|
21339
|
+
case "number":
|
|
21340
|
+
result = node.min != null || node.max != null || node.integer === true;
|
|
21341
|
+
break;
|
|
21342
|
+
case "boolean":
|
|
21343
|
+
case "literal":
|
|
21344
|
+
case "standard":
|
|
21345
|
+
result = false;
|
|
21346
|
+
break;
|
|
21347
|
+
case "optional":
|
|
21348
|
+
result = nodeHasBounds(node.inner);
|
|
21349
|
+
break;
|
|
21350
|
+
case "union":
|
|
21351
|
+
result = node.options.some(nodeHasBounds);
|
|
21352
|
+
break;
|
|
21353
|
+
case "object":
|
|
21354
|
+
result = Object.values(node.entries).some(nodeHasBounds);
|
|
21355
|
+
break;
|
|
21356
|
+
case "record":
|
|
21357
|
+
result = node.maxKeys != null || nodeHasBounds(node.value);
|
|
21358
|
+
break;
|
|
21359
|
+
case "array":
|
|
21360
|
+
result = node.maxItems != null || nodeHasBounds(node.item);
|
|
21361
|
+
break;
|
|
21362
|
+
}
|
|
21363
|
+
HAS_BOUNDS.set(node, result);
|
|
21364
|
+
return result;
|
|
21365
|
+
}
|
|
21366
|
+
/** Whether any node in the state tree declares a bound — the engine's do-nothing fast path. */
|
|
21367
|
+
function schemaRootHasBounds(root) {
|
|
21368
|
+
return Object.values(root).some(nodeHasBounds);
|
|
21369
|
+
}
|
|
21370
|
+
function unwrapOptional$1(node) {
|
|
21371
|
+
return node.kind === "optional" ? unwrapOptional$1(node.inner) : node;
|
|
21372
|
+
}
|
|
21373
|
+
function isPlainObject(value) {
|
|
21374
|
+
return typeof value === "object" && value != null && !Array.isArray(value);
|
|
21375
|
+
}
|
|
21376
|
+
function getAtPath$2(state, path) {
|
|
21377
|
+
let current = state;
|
|
21378
|
+
for (const seg of path) {
|
|
21379
|
+
if (current == null || typeof current !== "object") return void 0;
|
|
21380
|
+
current = current[seg];
|
|
21381
|
+
}
|
|
21382
|
+
return current;
|
|
21383
|
+
}
|
|
21384
|
+
/**
|
|
21385
|
+
* Bounds-only walk of a value against its node. Type mismatches are NOT reported here — shape
|
|
21386
|
+
* validation belongs to `validateValue` on the paths that run it; this walk only answers "does
|
|
21387
|
+
* any declared bound fail". The one exception is a union carrying bounds: bounds inside a union
|
|
21388
|
+
* are only checkable by structurally matching an option, so `validateValue` (which includes
|
|
21389
|
+
* bounds) is the matcher and a value matching no option reports as invalid.
|
|
21390
|
+
*/
|
|
21391
|
+
function checkBoundsDeep(node, value) {
|
|
21392
|
+
if (!nodeHasBounds(node)) return void 0;
|
|
21393
|
+
switch (node.kind) {
|
|
21394
|
+
case "string":
|
|
21395
|
+
if (typeof value === "string" && node.maxLength != null && value.length > node.maxLength) return {
|
|
21396
|
+
path: [],
|
|
21397
|
+
expected: `a string of at most ${node.maxLength} characters`
|
|
21398
|
+
};
|
|
21399
|
+
return;
|
|
21400
|
+
case "number": return typeof value === "number" ? validateValue(node, value) : void 0;
|
|
21401
|
+
case "optional": return value === void 0 ? void 0 : checkBoundsDeep(node.inner, value);
|
|
21402
|
+
case "union": return validateValue(node, value);
|
|
21403
|
+
case "object":
|
|
21404
|
+
if (!isPlainObject(value)) return void 0;
|
|
21405
|
+
for (const [key, child] of Object.entries(node.entries)) {
|
|
21406
|
+
const childValue = value[key];
|
|
21407
|
+
if (childValue === void 0) continue;
|
|
21408
|
+
const invalid = checkBoundsDeep(child, childValue);
|
|
21409
|
+
if (invalid != null) return {
|
|
21410
|
+
path: [key, ...invalid.path],
|
|
21411
|
+
expected: invalid.expected
|
|
21412
|
+
};
|
|
21413
|
+
}
|
|
21414
|
+
return;
|
|
21415
|
+
case "record":
|
|
21416
|
+
if (!isPlainObject(value)) return void 0;
|
|
21417
|
+
if (node.maxKeys != null && Object.keys(value).length > node.maxKeys) return {
|
|
21418
|
+
path: [],
|
|
21419
|
+
expected: `a record with at most ${node.maxKeys} entries`
|
|
21420
|
+
};
|
|
21421
|
+
if (!nodeHasBounds(node.value)) return void 0;
|
|
21422
|
+
for (const [key, entry] of Object.entries(value)) {
|
|
21423
|
+
const invalid = checkBoundsDeep(node.value, entry);
|
|
21424
|
+
if (invalid != null) return {
|
|
21425
|
+
path: [key, ...invalid.path],
|
|
21426
|
+
expected: invalid.expected
|
|
21427
|
+
};
|
|
21428
|
+
}
|
|
21429
|
+
return;
|
|
21430
|
+
case "array":
|
|
21431
|
+
if (!Array.isArray(value)) return void 0;
|
|
21432
|
+
if (node.maxItems != null && value.length > node.maxItems) return {
|
|
21433
|
+
path: [],
|
|
21434
|
+
expected: `an array of at most ${node.maxItems} items`
|
|
21435
|
+
};
|
|
21436
|
+
if (!nodeHasBounds(node.item)) return void 0;
|
|
21437
|
+
for (let i = 0; i < value.length; i++) {
|
|
21438
|
+
const invalid = checkBoundsDeep(node.item, value[i]);
|
|
21439
|
+
if (invalid != null) return {
|
|
21440
|
+
path: [i, ...invalid.path],
|
|
21441
|
+
expected: invalid.expected
|
|
21442
|
+
};
|
|
21443
|
+
}
|
|
21444
|
+
return;
|
|
21445
|
+
default: return;
|
|
21446
|
+
}
|
|
21447
|
+
}
|
|
21448
|
+
/** Full-tree bounds walk — boot, restore, and migration output, before any client attaches. */
|
|
21449
|
+
function validateBoundedStateTree(root, state) {
|
|
21450
|
+
for (const [name, node] of Object.entries(root)) {
|
|
21451
|
+
if (!nodeHasBounds(node)) continue;
|
|
21452
|
+
const invalid = checkBoundsDeep(node, state[name]);
|
|
21453
|
+
if (invalid != null) return {
|
|
21454
|
+
path: [name, ...invalid.path],
|
|
21455
|
+
expected: invalid.expected
|
|
21456
|
+
};
|
|
21457
|
+
}
|
|
21458
|
+
}
|
|
21459
|
+
/**
|
|
21460
|
+
* Bounds gate for one commit: given the **candidate next state** and the batch's canonical patch
|
|
21461
|
+
* paths, check (a) `maxKeys` on every record *ancestor* a path descends into — the constraint an
|
|
21462
|
+
* incremental entry add changes without ever writing the record itself — and (b) all bounds
|
|
21463
|
+
* within each patched subtree's final value. Checks dedupe across the batch and run against the
|
|
21464
|
+
* final state, so remove+add sequences net out and multi-patch frames are judged once, atomically.
|
|
21465
|
+
*/
|
|
21466
|
+
function validateBoundedPatches(root, stateAfter, paths) {
|
|
21467
|
+
const checked = /* @__PURE__ */ new Set();
|
|
21468
|
+
for (const path of paths) {
|
|
21469
|
+
let entries = root;
|
|
21470
|
+
let node;
|
|
21471
|
+
for (let i = 0; i < path.length; i++) {
|
|
21472
|
+
const seg = path[i];
|
|
21473
|
+
if (entries != null) {
|
|
21474
|
+
node = typeof seg === "string" ? entries[seg] : void 0;
|
|
21475
|
+
entries = void 0;
|
|
21476
|
+
} else if (node != null) {
|
|
21477
|
+
const inner = unwrapOptional$1(node);
|
|
21478
|
+
if (inner.kind === "object") node = inner.entries[seg];
|
|
21479
|
+
else if (inner.kind === "record") node = inner.value;
|
|
21480
|
+
else node = void 0;
|
|
21481
|
+
}
|
|
21482
|
+
if (node == null) break;
|
|
21483
|
+
const inner = unwrapOptional$1(node);
|
|
21484
|
+
if (inner.kind === "record" && inner.maxKeys != null && i + 1 < path.length) {
|
|
21485
|
+
const prefix = path.slice(0, i + 1);
|
|
21486
|
+
const key = `A:${prefix.join("\0")}`;
|
|
21487
|
+
if (!checked.has(key)) {
|
|
21488
|
+
checked.add(key);
|
|
21489
|
+
const value = getAtPath$2(stateAfter, prefix);
|
|
21490
|
+
if (isPlainObject(value) && Object.keys(value).length > inner.maxKeys) return {
|
|
21491
|
+
path: [...prefix],
|
|
21492
|
+
expected: `a record with at most ${inner.maxKeys} entries`
|
|
21493
|
+
};
|
|
21494
|
+
}
|
|
21495
|
+
}
|
|
21496
|
+
}
|
|
21497
|
+
if (node != null) {
|
|
21498
|
+
const key = `T:${path.join("\0")}`;
|
|
21499
|
+
if (!checked.has(key)) {
|
|
21500
|
+
checked.add(key);
|
|
21501
|
+
const value = getAtPath$2(stateAfter, path);
|
|
21502
|
+
if (value !== void 0) {
|
|
21503
|
+
const invalid = checkBoundsDeep(node, value);
|
|
21504
|
+
if (invalid != null) return {
|
|
21505
|
+
path: [...path, ...invalid.path],
|
|
21506
|
+
expected: invalid.expected
|
|
21507
|
+
};
|
|
21508
|
+
}
|
|
21509
|
+
}
|
|
21510
|
+
}
|
|
21511
|
+
}
|
|
21512
|
+
}
|
|
21513
|
+
//#endregion
|
|
20818
21514
|
//#region ../nice-realm/src/RealmServer/viewSlice.ts
|
|
20819
21515
|
function leafVisible(ctx, path) {
|
|
20820
21516
|
const match = ctx.trie.match(path);
|
|
@@ -20972,6 +21668,8 @@ var RealmServerEngine = class {
|
|
|
20972
21668
|
_now;
|
|
20973
21669
|
_instanceId;
|
|
20974
21670
|
_state;
|
|
21671
|
+
/** Whether the schema declares any bounds — false skips every bounded-state walk. */
|
|
21672
|
+
_hasBounds;
|
|
20975
21673
|
_version = 0;
|
|
20976
21674
|
_mutating = false;
|
|
20977
21675
|
/** The log epoch (review B.3): identifies this history — replay requires an exact match. */
|
|
@@ -21056,6 +21754,14 @@ var RealmServerEngine = class {
|
|
|
21056
21754
|
this._state = typeof options.initialState === "function" ? options.initialState({ instanceId: this._instanceId }) : options.initialState;
|
|
21057
21755
|
this._epoch = mintEpoch();
|
|
21058
21756
|
}
|
|
21757
|
+
this._hasBounds = schemaRootHasBounds(this._realm.stateDef);
|
|
21758
|
+
if (this._hasBounds) {
|
|
21759
|
+
const invalid = validateBoundedStateTree(this._realm.stateDef, this._state);
|
|
21760
|
+
if (invalid != null) throw err_realm.fromId("value_invalid", {
|
|
21761
|
+
path: invalid.path.join("."),
|
|
21762
|
+
expected: invalid.expected
|
|
21763
|
+
});
|
|
21764
|
+
}
|
|
21059
21765
|
}
|
|
21060
21766
|
get state() {
|
|
21061
21767
|
return this._state;
|
|
@@ -21422,6 +22128,13 @@ var RealmServerEngine = class {
|
|
|
21422
22128
|
const [nextState, patches] = produced;
|
|
21423
22129
|
if (patches.length === 0) return;
|
|
21424
22130
|
const canonical = canonicalizeStatePatches(patches, nextState, this._realm.stateDef);
|
|
22131
|
+
if (this._hasBounds) {
|
|
22132
|
+
const bounded = validateBoundedPatches(this._realm.stateDef, nextState, canonical.map((patch) => patch.path));
|
|
22133
|
+
if (bounded != null) throw err_realm.fromId("value_invalid", {
|
|
22134
|
+
path: bounded.path.join("."),
|
|
22135
|
+
expected: bounded.expected
|
|
22136
|
+
});
|
|
22137
|
+
}
|
|
21425
22138
|
this._commit(nextState, canonical, { source: "server" });
|
|
21426
22139
|
this._flushEgress();
|
|
21427
22140
|
}
|
|
@@ -21541,6 +22254,16 @@ var RealmServerEngine = class {
|
|
|
21541
22254
|
this._reject(conn, frame.clientSeq, err_realm.fromId("write_target_missing", { path }));
|
|
21542
22255
|
return;
|
|
21543
22256
|
}
|
|
22257
|
+
if (this._hasBounds) {
|
|
22258
|
+
const bounded = validateBoundedPatches(this._realm.stateDef, nextState, namePatches.map((patch) => patch.path));
|
|
22259
|
+
if (bounded != null) {
|
|
22260
|
+
this._reject(conn, frame.clientSeq, err_realm.fromId("value_invalid", {
|
|
22261
|
+
path: bounded.path.join("."),
|
|
22262
|
+
expected: bounded.expected
|
|
22263
|
+
}));
|
|
22264
|
+
return;
|
|
22265
|
+
}
|
|
22266
|
+
}
|
|
21544
22267
|
const version = this._commit(nextState, namePatches, {
|
|
21545
22268
|
source: "write",
|
|
21546
22269
|
avatar: conn.avatar
|
|
@@ -21606,6 +22329,16 @@ var RealmServerEngine = class {
|
|
|
21606
22329
|
this._reject(conn, frame.clientSeq, err_realm.fromId("frame_invalid", { reason: "unsafe record key" }));
|
|
21607
22330
|
return;
|
|
21608
22331
|
}
|
|
22332
|
+
if (this._hasBounds) {
|
|
22333
|
+
const bounded = validateBoundedPatches(this._realm.stateDef, nextState, canonical.map((patch) => patch.path));
|
|
22334
|
+
if (bounded != null) {
|
|
22335
|
+
this._reject(conn, frame.clientSeq, err_realm.fromId("value_invalid", {
|
|
22336
|
+
path: bounded.path.join("."),
|
|
22337
|
+
expected: bounded.expected
|
|
22338
|
+
}));
|
|
22339
|
+
return;
|
|
22340
|
+
}
|
|
22341
|
+
}
|
|
21609
22342
|
const version = this._commit(nextState, canonical, {
|
|
21610
22343
|
source: "intent",
|
|
21611
22344
|
avatar: conn.avatar
|