@lunora/do 1.0.0-alpha.15 → 1.0.0-alpha.151

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/LICENSE.md +6 -0
  2. package/README.md +11 -0
  3. package/dist/index.d.mts +4952 -6091
  4. package/dist/index.d.ts +4952 -6091
  5. package/dist/index.mjs +1 -40
  6. package/dist/packem_shared/ROOT_DO_SIZE_WARN_BYTES-BGuGWp1g.mjs +15 -0
  7. package/dist/packem_shared/SESSION_DO_TTL_DEFAULT-BbU25BWj.mjs +1 -0
  8. package/dist/packem_shared/SHARD_REGISTRY_DO_NAME-DvxEa7qM.mjs +1 -0
  9. package/dist/packem_shared/constant-time-equal-BRh9yUCr.mjs +1 -0
  10. package/dist/packem_shared/json-response-0Bq2ky0N.mjs +1 -0
  11. package/dist/packem_shared/serveRelationFanout-DcSjzAZv.mjs +1 -0
  12. package/package.json +5 -2
  13. package/dist/packem_shared/ADMIN_FUNCTIONS-fMl1vyt1.mjs +0 -355
  14. package/dist/packem_shared/AGGREGATE_SQL_FUNCTION-CFk6adSu.mjs +0 -54
  15. package/dist/packem_shared/AUTH_METRICS_BUCKETS_TABLE-CiHHYeJi.mjs +0 -84
  16. package/dist/packem_shared/CDC_LOG_TABLE-DSycmnDf.mjs +0 -107
  17. package/dist/packem_shared/ConflictError-C0STs6bU.mjs +0 -13
  18. package/dist/packem_shared/CountRlsUnsupportedError-28ZvvwKS.mjs +0 -133
  19. package/dist/packem_shared/DATA_MIGRATION_STATE_TABLE-PTtTiQ7U.mjs +0 -237
  20. package/dist/packem_shared/DEFAULT_MAX_RELATION_KEYS-DU-Y4-LJ.mjs +0 -209
  21. package/dist/packem_shared/FUNCTION_METRICS_BUCKETS_TABLE-UDNVD7FS.mjs +0 -248
  22. package/dist/packem_shared/LogBuffer-B_Ezju_N.mjs +0 -37
  23. package/dist/packem_shared/MAIL_RETENTION-CPpgl-dX.mjs +0 -104
  24. package/dist/packem_shared/MAX_SQL_ROWS-dDcFE1YZ.mjs +0 -29
  25. package/dist/packem_shared/MIN_ADMIN_TOKEN_LENGTH-CCAvoFlr.mjs +0 -1
  26. package/dist/packem_shared/NotFoundError-CMuMZt81.mjs +0 -10
  27. package/dist/packem_shared/NotUniqueError-BXn2j5vu.mjs +0 -1835
  28. package/dist/packem_shared/RANK_TIEBREAK-CXhdcA1o.mjs +0 -91
  29. package/dist/packem_shared/RLS_UNWRAP_SYMBOL-EtGQdC9d.mjs +0 -132
  30. package/dist/packem_shared/ROOT_DO_SIZE_WARN_BYTES-CEVhBec2.mjs +0 -6049
  31. package/dist/packem_shared/ReactiveCache-BYlSGY0N.mjs +0 -232
  32. package/dist/packem_shared/SCAN_DEP-DLJF8dsj.mjs +0 -19
  33. package/dist/packem_shared/SESSION_DO_TTL_DEFAULT-ilPZsVwu.mjs +0 -180
  34. package/dist/packem_shared/SHARD_REGISTRY_DO_NAME-BsAbi5Mn.mjs +0 -146
  35. package/dist/packem_shared/aggregateTableName-CxNqY1Sl.mjs +0 -64
  36. package/dist/packem_shared/applyOnDelete-BQ-8ZlZ1.mjs +0 -175
  37. package/dist/packem_shared/applySelect-BvZdFUBT.mjs +0 -101
  38. package/dist/packem_shared/armRestore-BJk53Ro8.mjs +0 -55
  39. package/dist/packem_shared/backfillAggregateIndexes-BZsOqDXP.mjs +0 -81
  40. package/dist/packem_shared/buildFtsMatch-BLEMawrp.mjs +0 -38
  41. package/dist/packem_shared/compileWhereSql-CXrhFA3G.mjs +0 -127
  42. package/dist/packem_shared/createSystemReader-8CzSZP9V.mjs +0 -80
  43. package/dist/packem_shared/ctx-db-idempotency-BdcNpvY4.mjs +0 -108
  44. package/dist/packem_shared/ctx-db-shapes-BQapRFjB.mjs +0 -53
  45. package/dist/packem_shared/diffExternalSource-Cx9HUPJj.mjs +0 -44
  46. package/dist/packem_shared/do-exec-5eQy5cEi.mjs +0 -12
  47. package/dist/packem_shared/do-sql-BCHCWtrD.mjs +0 -87
  48. package/dist/packem_shared/exportShardRows-DZEhUeyI.mjs +0 -156
  49. package/dist/packem_shared/hasTrigger-5N6_Fx0A.mjs +0 -20
  50. package/dist/packem_shared/isSourceDue-BMTJv65e.mjs +0 -40
  51. package/dist/packem_shared/materializeExternalRows-uKBx9H0s.mjs +0 -23
  52. package/dist/packem_shared/renderSql-D6eUcn2N.mjs +0 -16
  53. package/dist/packem_shared/runShardMigrations-nIwoQeOK.mjs +0 -105
  54. package/dist/packem_shared/security-audit-CucgBice.mjs +0 -158
  55. package/dist/packem_shared/serialize-sql-BlRUoiQe.mjs +0 -14
  56. package/dist/packem_shared/serveRelationFanout-EZLD9-O3.mjs +0 -24
  57. package/dist/packem_shared/stableStringify-MydiuScU.mjs +0 -40
  58. package/dist/packem_shared/subscription-delivery-Z6nXHvQN.mjs +0 -340
  59. package/dist/packem_shared/subscriptionListDeltas-CXwfoEE_.mjs +0 -1
@@ -1,158 +0,0 @@
1
- const SECRET_NAME_PATTERN = /key|secret|token|password|passwd|credential|private|auth|bearer|session|cookie|salt|signature|dsn|webhook/iu;
2
- const LUNORA_INTERNAL_VARS = /* @__PURE__ */ new Set(["LUNORA_ADMIN_TOKEN", "LUNORA_WS_BEARER"]);
3
- const WORKER_URL_VARS = ["CF_PAGES_URL", "WORKER_URL", "LUNORA_WORKER_URL"];
4
- const ENVIRONMENT_VARS = ["CF_ENV", "ENVIRONMENT", "WORKER_ENV", "NODE_ENV"];
5
- const redact = (value) => {
6
- if (value.length <= 4) {
7
- return "••••";
8
- }
9
- return `${value.slice(0, 4)}${"•".repeat(Math.min(8, value.length - 4))}`;
10
- };
11
- const looksSecret = (name) => SECRET_NAME_PATTERN.test(name);
12
- const bindingType = (value) => {
13
- const has = (key) => typeof value[key] === "function";
14
- if (has("idFromName") || has("idFromString")) {
15
- return "durable-object";
16
- }
17
- if (has("createMultipartUpload") || has("put") && has("get") && has("list") && has("head")) {
18
- return "r2";
19
- }
20
- if (has("getWithMetadata")) {
21
- return "kv";
22
- }
23
- if (has("prepare") && has("dump")) {
24
- return "d1";
25
- }
26
- if (has("send") && has("sendBatch")) {
27
- return "queue";
28
- }
29
- if (has("fetch") && !has("get")) {
30
- return "service";
31
- }
32
- return "object";
33
- };
34
- const readDeployInfo = (env) => {
35
- const deploy = {};
36
- for (const key of WORKER_URL_VARS) {
37
- if (typeof env[key] === "string" && env[key] !== "") {
38
- deploy.workerUrl = env[key];
39
- break;
40
- }
41
- }
42
- for (const key of ENVIRONMENT_VARS) {
43
- if (typeof env[key] === "string" && env[key] !== "") {
44
- deploy.environment = env[key];
45
- break;
46
- }
47
- }
48
- const versionMetadata = env["CF_VERSION_METADATA"];
49
- if (versionMetadata !== null && typeof versionMetadata === "object") {
50
- const meta = versionMetadata;
51
- if (typeof meta["id"] === "string") {
52
- deploy.deploymentId = meta["id"];
53
- }
54
- if (typeof meta["tag"] === "string") {
55
- deploy.versionTag = meta["tag"];
56
- }
57
- }
58
- return deploy;
59
- };
60
- const DEV_ENVIRONMENT_PATTERN = /^(?:dev(?:elopment)?|local(?:host)?|test)$/iu;
61
- const isDevEnvironment = (rawEnv) => {
62
- const env = rawEnv ?? {};
63
- for (const key of ENVIRONMENT_VARS) {
64
- const value = env[key];
65
- if (typeof value === "string" && DEV_ENVIRONMENT_PATTERN.test(value)) {
66
- return true;
67
- }
68
- }
69
- return false;
70
- };
71
- const buildSettings = (rawEnv) => {
72
- const env = rawEnv ?? {};
73
- const settings = [];
74
- for (const [name, value] of Object.entries(env)) {
75
- if (LUNORA_INTERNAL_VARS.has(name)) {
76
- continue;
77
- }
78
- if (typeof value === "string") {
79
- const secret = looksSecret(name);
80
- settings.push({
81
- kind: secret ? "secret" : "var",
82
- name,
83
- // Both vars and secrets are masked — a "var" may still hold a
84
- // sensitive value, and the studio never needs the raw text.
85
- value: redact(value)
86
- });
87
- continue;
88
- }
89
- if (typeof value === "number" || typeof value === "boolean") {
90
- settings.push({ kind: "var", name, value: String(value) });
91
- continue;
92
- }
93
- if (value !== null && typeof value === "object") {
94
- settings.push({ bindingType: bindingType(value), kind: "binding", name, value: null });
95
- continue;
96
- }
97
- settings.push({ kind: "var", name, value: null });
98
- }
99
- settings.sort((a, b) => a.name.localeCompare(b.name));
100
- return { deploy: readDeployInfo(env), settings };
101
- };
102
-
103
- const MIN_ADMIN_TOKEN_LENGTH = 24;
104
- const MIN_AUTH_SECRET_LENGTH = 32;
105
- const LEVEL_ORDER = { error: 0, info: 2, warning: 1 };
106
- const DISABLED_ENV_VALUES = /* @__PURE__ */ new Set(["0", "disabled", "false", "no", "off"]);
107
- const ENABLED_ENV_VALUES = /* @__PURE__ */ new Set(["1", "enabled", "on", "true", "yes"]);
108
- const readFlag = (value) => typeof value === "string" ? value.trim().toLowerCase() : void 0;
109
- const auditAuthSecret = (env) => {
110
- const authSecret = env["AUTH_SECRET"] ?? env["BETTER_AUTH_SECRET"];
111
- const length = typeof authSecret === "string" ? authSecret.trim().length : 0;
112
- if (length > 0 && length < MIN_AUTH_SECRET_LENGTH) {
113
- return [{ detail: { length, min: MIN_AUTH_SECRET_LENGTH }, kind: "auth-secret-weak", level: "warning" }];
114
- }
115
- return [];
116
- };
117
- const auditCors = (env) => {
118
- const allowedOrigins = readFlag(env["LUNORA_ALLOWED_ORIGINS"]);
119
- const corsCredentials = ENABLED_ENV_VALUES.has(readFlag(env["LUNORA_CORS_ALLOW_CREDENTIALS"]) ?? "");
120
- const hasWildcard = allowedOrigins?.split(",").some((entry) => entry.trim() === "*") ?? false;
121
- return hasWildcard && corsCredentials ? [{ kind: "cors-wildcard-credentials", level: "error" }] : [];
122
- };
123
- const auditSecurityLayers = (env, dev) => {
124
- if (dev) {
125
- return [];
126
- }
127
- const findings = [];
128
- if (DISABLED_ENV_VALUES.has(readFlag(env["LUNORA_SECURITY_HEADERS"]) ?? "")) {
129
- findings.push({ kind: "security-headers-disabled", level: "warning" });
130
- }
131
- if (DISABLED_ENV_VALUES.has(readFlag(env["LUNORA_SECURITY_CSRF"]) ?? "")) {
132
- findings.push({ kind: "csrf-disabled", level: "warning" });
133
- }
134
- if (readFlag(env["BETTER_AUTH_URL"])?.startsWith("http://") === true) {
135
- findings.push({ kind: "cookies-insecure", level: "warning" });
136
- }
137
- return findings;
138
- };
139
- const buildSecurityAudit = (rawEnv) => {
140
- const env = rawEnv ?? {};
141
- const findings = [];
142
- const adminToken = env["LUNORA_ADMIN_TOKEN"];
143
- if (typeof adminToken === "string" && adminToken.length > 0 && adminToken.length < MIN_ADMIN_TOKEN_LENGTH) {
144
- findings.push({ detail: { length: adminToken.length, min: MIN_ADMIN_TOKEN_LENGTH }, kind: "admin-token-weak", level: "warning" });
145
- }
146
- const wsBearer = env["LUNORA_WS_BEARER"];
147
- const dev = isDevEnvironment(env);
148
- if (typeof wsBearer !== "string" || wsBearer === "") {
149
- findings.push({ kind: "ws-gate-open", level: dev ? "info" : "error" });
150
- }
151
- if (dev) {
152
- findings.push({ kind: "dev-args-unredacted", level: "warning" });
153
- }
154
- findings.push(...auditAuthSecret(env), ...auditCors(env), ...auditSecurityLayers(env, dev));
155
- return { findings: findings.toSorted((a, b) => LEVEL_ORDER[a.level] - LEVEL_ORDER[b.level]) };
156
- };
157
-
158
- export { MIN_ADMIN_TOKEN_LENGTH as M, MIN_AUTH_SECRET_LENGTH as a, buildSecurityAudit as b, buildSettings as c, isDevEnvironment as i };
@@ -1,14 +0,0 @@
1
- const serializeSqlValue = (value) => {
2
- if (typeof value === "boolean") {
3
- return value ? 1 : 0;
4
- }
5
- if (value === null || typeof value === "string" || typeof value === "number") {
6
- return value;
7
- }
8
- if (typeof value === "bigint") {
9
- return value.toString();
10
- }
11
- return JSON.stringify(value);
12
- };
13
-
14
- export { serializeSqlValue as s };
@@ -1,24 +0,0 @@
1
- import { RELATION_FUNCTION_PREFIX } from './ADMIN_FUNCTIONS-fMl1vyt1.mjs';
2
-
3
- const serveRelationFanout = async (schema, database, functionPath, args) => {
4
- const table = typeof args["table"] === "string" ? args["table"] : "";
5
- const definition = schema.tables[table];
6
- if (!definition) {
7
- throw Object.assign(new Error(`${RELATION_FUNCTION_PREFIX} unknown table "${table}"`), { code: "UNKNOWN_TABLE", name: "LunoraError", status: 404 });
8
- }
9
- if (definition.shardMode?.kind === "global") {
10
- throw Object.assign(new Error(`${RELATION_FUNCTION_PREFIX} table "${table}" is global, not shard-local`), {
11
- code: "BAD_REQUEST",
12
- name: "LunoraError",
13
- status: 400
14
- });
15
- }
16
- const where = args["where"] ?? void 0;
17
- if (functionPath === `${RELATION_FUNCTION_PREFIX}count`) {
18
- return database.count(table, where);
19
- }
20
- const result = await database.findMany(table, { orderBy: args["orderBy"], where, with: args["with"] });
21
- return result.page;
22
- };
23
-
24
- export { serveRelationFanout };
@@ -1,40 +0,0 @@
1
- const compareKeys = (a, b) => {
2
- if (a < b) {
3
- return -1;
4
- }
5
- return a > b ? 1 : 0;
6
- };
7
- const stableStringify = (value) => {
8
- if (value === void 0) {
9
- return "null";
10
- }
11
- if (typeof value === "bigint") {
12
- throw new TypeError("stableStringify: cannot use a bigint in a cache key (query/subscription/shape args) — pass it as a string");
13
- }
14
- if (value === null || typeof value !== "object") {
15
- return JSON.stringify(value);
16
- }
17
- if (Array.isArray(value)) {
18
- return `[${value.map((item) => stableStringify(item)).join(",")}]`;
19
- }
20
- const proto = Object.getPrototypeOf(value);
21
- if (proto !== null && proto !== Object.prototype) {
22
- const name = value.constructor?.name ?? "value";
23
- throw new TypeError(
24
- `stableStringify: cannot use a ${name} in a cache key (query/subscription/shape args) — only plain objects, arrays, and JSON primitives are supported`
25
- );
26
- }
27
- const record = value;
28
- const keys = Object.keys(record).toSorted(compareKeys);
29
- const parts = [];
30
- for (const key of keys) {
31
- const raw = record[key];
32
- if (raw === void 0) {
33
- continue;
34
- }
35
- parts.push(`${JSON.stringify(key)}:${stableStringify(raw)}`);
36
- }
37
- return `{${parts.join(",")}}`;
38
- };
39
-
40
- export { stableStringify };
@@ -1,340 +0,0 @@
1
- const TAG = "$lunora.wire$";
2
- const MAX_DEPTH = 64;
3
- const MAX_BIGINT_DIGITS = 1024;
4
- const UNSAFE_KEY = "__proto__";
5
- const TYPED_ARRAY_CTORS = {
6
- BigInt64Array,
7
- BigUint64Array,
8
- Float32Array,
9
- Float64Array,
10
- Int8Array,
11
- Int16Array,
12
- Int32Array,
13
- Uint8Array,
14
- Uint8ClampedArray,
15
- Uint16Array,
16
- Uint32Array
17
- };
18
- const ERROR_CTORS = {
19
- Error,
20
- EvalError,
21
- RangeError,
22
- ReferenceError,
23
- SyntaxError,
24
- TypeError,
25
- URIError
26
- };
27
- const toBase64 = (bytes) => {
28
- let binary = "";
29
- const chunk = 32768;
30
- for (let index = 0; index < bytes.length; index += chunk) {
31
- binary += String.fromCharCode(...bytes.subarray(index, index + chunk));
32
- }
33
- return btoa(binary);
34
- };
35
- const fromBase64 = (base64) => {
36
- const binary = atob(base64);
37
- const bytes = new Uint8Array(binary.length);
38
- for (let index = 0; index < binary.length; index += 1) {
39
- bytes[index] = binary.codePointAt(index) ?? 0;
40
- }
41
- return bytes;
42
- };
43
- const encodeWire = (value, depth = 0) => {
44
- if (depth > MAX_DEPTH) {
45
- throw new RangeError(`wire-codec: value nesting exceeds the ${MAX_DEPTH}-level limit`);
46
- }
47
- if (value === void 0) {
48
- return [TAG, "undefined"];
49
- }
50
- if (value === null) {
51
- return null;
52
- }
53
- const kind = typeof value;
54
- if (kind === "bigint") {
55
- return [TAG, "bigint", value.toString()];
56
- }
57
- if (kind === "number") {
58
- const numeric = value;
59
- if (Number.isNaN(numeric)) {
60
- return [TAG, "nan"];
61
- }
62
- if (numeric === Infinity) {
63
- return [TAG, "inf"];
64
- }
65
- if (numeric === -Infinity) {
66
- return [TAG, "-inf"];
67
- }
68
- return numeric;
69
- }
70
- if (kind !== "object") {
71
- return value;
72
- }
73
- if (value instanceof Date) {
74
- return [TAG, "date", encodeWire(value.getTime(), depth + 1)];
75
- }
76
- if (value instanceof Error) {
77
- const error = value;
78
- const properties = {};
79
- for (const key of Object.keys(error)) {
80
- if (error[key] !== void 0) {
81
- properties[key] = encodeWire(error[key], depth + 1);
82
- }
83
- }
84
- const encodedError = [TAG, "error", error.name, error.message, properties];
85
- if (error.cause !== void 0) {
86
- encodedError.push(encodeWire(error.cause, depth + 1));
87
- }
88
- return encodedError;
89
- }
90
- if (value instanceof URL) {
91
- return [TAG, "url", value.href];
92
- }
93
- if (value instanceof Map) {
94
- return [TAG, "map", [...value.entries()].map(([k, v]) => [encodeWire(k, depth + 1), encodeWire(v, depth + 1)])];
95
- }
96
- if (value instanceof Set) {
97
- return [TAG, "set", [...value].map((item) => encodeWire(item, depth + 1))];
98
- }
99
- if (value instanceof ArrayBuffer) {
100
- return [TAG, "bytes", toBase64(new Uint8Array(value)), "ArrayBuffer"];
101
- }
102
- if (ArrayBuffer.isView(value)) {
103
- const view = value;
104
- const ctorName = view.constructor.name;
105
- const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
106
- return ctorName === "Uint8Array" ? [TAG, "bytes", toBase64(bytes)] : [TAG, "bytes", toBase64(bytes), ctorName];
107
- }
108
- if (Array.isArray(value)) {
109
- const encoded = value.map((item) => encodeWire(item, depth + 1));
110
- return encoded.length > 0 && encoded[0] === TAG ? [TAG, "arr", encoded] : encoded;
111
- }
112
- const proto = Object.getPrototypeOf(value);
113
- if (proto !== null && proto !== Object.prototype) {
114
- const name = value.constructor?.name ?? "value";
115
- throw new TypeError(
116
- `wire-codec: cannot encode a ${name} over the Lunora wire — only plain objects, arrays, and the supported built-ins (Date, Error, URL, Map, Set, ArrayBuffer/typed arrays, bigint) round-trip`
117
- );
118
- }
119
- const source = value;
120
- const result = {};
121
- for (const key of Object.keys(source)) {
122
- const field = source[key];
123
- if (field !== void 0) {
124
- result[key] = encodeWire(field, depth + 1);
125
- }
126
- }
127
- return result;
128
- };
129
- const decodeWire = (value, depth = 0) => {
130
- if (depth > MAX_DEPTH) {
131
- throw new RangeError(`wire-codec: value nesting exceeds the ${MAX_DEPTH}-level limit`);
132
- }
133
- if (value === null || typeof value !== "object") {
134
- return value;
135
- }
136
- if (Array.isArray(value)) {
137
- if (value[0] === TAG) {
138
- const tag = value[1];
139
- switch (tag) {
140
- case "-inf": {
141
- return -Infinity;
142
- }
143
- case "arr": {
144
- return value[2].map((item) => decodeWire(item, depth + 1));
145
- }
146
- case "bigint": {
147
- const raw = value[2];
148
- if (typeof raw !== "string" || raw.length > MAX_BIGINT_DIGITS || !/^-?\d+$/.test(raw)) {
149
- throw new RangeError(`wire-codec: invalid or over-long bigint (max ${MAX_BIGINT_DIGITS} digits)`);
150
- }
151
- return BigInt(raw);
152
- }
153
- case "date": {
154
- return new Date(decodeWire(value[2], depth + 1));
155
- }
156
- case "map": {
157
- return new Map(value[2].map(([k, v]) => [decodeWire(k, depth + 1), decodeWire(v, depth + 1)]));
158
- }
159
- case "set": {
160
- return new Set(value[2].map((item) => decodeWire(item, depth + 1)));
161
- }
162
- case "url": {
163
- return new URL(value[2]);
164
- }
165
- case "error": {
166
- const name = value[2];
167
- const message = value[3];
168
- const Ctor = (Object.hasOwn(ERROR_CTORS, name) ? ERROR_CTORS[name] : void 0) ?? Error;
169
- const error = new Ctor(message);
170
- if (error.name !== name) {
171
- Object.defineProperty(error, "name", { configurable: true, value: name, writable: true });
172
- }
173
- Object.assign(error, decodeWire(value[4], depth + 1));
174
- if (value.length > 5) {
175
- Object.defineProperty(error, "cause", { configurable: true, value: decodeWire(value[5], depth + 1), writable: true });
176
- }
177
- return error;
178
- }
179
- case "bytes": {
180
- const bytes = fromBase64(value[2]);
181
- const ctorName = value[3] ?? "Uint8Array";
182
- if (ctorName === "ArrayBuffer") {
183
- return bytes.buffer.byteLength === bytes.byteLength ? bytes.buffer : bytes.slice().buffer;
184
- }
185
- const Ctor = Object.hasOwn(TYPED_ARRAY_CTORS, ctorName) ? TYPED_ARRAY_CTORS[ctorName] : void 0;
186
- return Ctor ? new Ctor(bytes.slice().buffer) : bytes;
187
- }
188
- case "inf": {
189
- return Infinity;
190
- }
191
- case "nan": {
192
- return Number.NaN;
193
- }
194
- case "undefined": {
195
- return void 0;
196
- }
197
- default: {
198
- return value.map((item) => decodeWire(item, depth + 1));
199
- }
200
- }
201
- }
202
- return value.map((item) => decodeWire(item, depth + 1));
203
- }
204
- const source = value;
205
- const result = {};
206
- for (const key of Object.keys(source)) {
207
- const decoded = decodeWire(source[key], depth + 1);
208
- if (key === UNSAFE_KEY) {
209
- Object.defineProperty(result, key, { configurable: true, enumerable: true, value: decoded, writable: true });
210
- } else {
211
- result[key] = decoded;
212
- }
213
- }
214
- return result;
215
- };
216
-
217
- const ROW_ID_FIELD = "_id";
218
- const DELTA_FALLBACK_TABLE = "__lunora__";
219
- const readRowId = (row) => {
220
- if (typeof row !== "object" || row === null || Array.isArray(row)) {
221
- return void 0;
222
- }
223
- const id = row[ROW_ID_FIELD];
224
- return typeof id === "string" ? id : void 0;
225
- };
226
- const indexRowsById = (rows) => {
227
- const byId = /* @__PURE__ */ new Map();
228
- const order = [];
229
- for (const row of rows) {
230
- const id = readRowId(row);
231
- if (id === void 0 || byId.has(id)) {
232
- return void 0;
233
- }
234
- byId.set(id, row);
235
- order.push(id);
236
- }
237
- return { byId, order };
238
- };
239
- const survivorsKeepOrder = (previous, next) => {
240
- const survivingPrevious = previous.order.filter((id) => next.byId.has(id));
241
- const survivingNext = next.order.filter((id) => previous.byId.has(id));
242
- if (survivingPrevious.length !== survivingNext.length) {
243
- return false;
244
- }
245
- return survivingPrevious.every((id, index) => survivingNext[index] === id);
246
- };
247
- const collectDeleteDeltas = (previous, next, deltaTable, tableJson) => {
248
- const out = [];
249
- for (const id of previous.order) {
250
- if (!next.byId.has(id)) {
251
- out.push({
252
- delta: { key: id, op: "delete", table: deltaTable },
253
- frame: `{"key":${JSON.stringify(id)},"op":"delete","table":${tableJson}}`
254
- });
255
- }
256
- }
257
- return out;
258
- };
259
- const collectUpsertDeltas = (previous, next, deltaTable, tableJson) => {
260
- const out = [];
261
- for (const id of next.order) {
262
- const nextRow = next.byId.get(id);
263
- const previousRow = previous.byId.get(id);
264
- const nextFingerprint = JSON.stringify(encodeWire(nextRow));
265
- const previousFingerprint = previousRow === void 0 ? void 0 : JSON.stringify(previousRow);
266
- if (previousFingerprint === nextFingerprint) {
267
- continue;
268
- }
269
- const op = previousFingerprint === void 0 ? "insert" : "update";
270
- out.push({
271
- delta: { key: id, op, row: nextRow, table: deltaTable },
272
- frame: `{"key":${JSON.stringify(id)},"op":"${op}","row":${nextFingerprint},"table":${tableJson}}`
273
- });
274
- }
275
- return out;
276
- };
277
- const subscriptionListDeltas = (previousJson, nextResult, table, frames) => {
278
- let parsed;
279
- try {
280
- parsed = JSON.parse(previousJson);
281
- } catch {
282
- return void 0;
283
- }
284
- if (!Array.isArray(parsed) || !Array.isArray(nextResult)) {
285
- return void 0;
286
- }
287
- const previous = indexRowsById(parsed);
288
- const next = indexRowsById(nextResult);
289
- if (previous === void 0 || next === void 0) {
290
- return void 0;
291
- }
292
- if (!survivorsKeepOrder(previous, next)) {
293
- return void 0;
294
- }
295
- const deltaTable = table === "" ? DELTA_FALLBACK_TABLE : table;
296
- const tableJson = JSON.stringify(deltaTable);
297
- const framed = [...collectDeleteDeltas(previous, next, deltaTable, tableJson), ...collectUpsertDeltas(previous, next, deltaTable, tableJson)];
298
- if (framed.length > next.order.length) {
299
- return void 0;
300
- }
301
- if (frames !== void 0) {
302
- for (const { frame } of framed) {
303
- frames.push(frame);
304
- }
305
- }
306
- return framed.map(({ delta }) => delta);
307
- };
308
- const trySendFrame = (ws, frame) => {
309
- try {
310
- ws.send(frame);
311
- return true;
312
- } catch {
313
- return false;
314
- }
315
- };
316
- const sendDeltaFrames = (ws, subId, deltaFrames, cursorSuffix) => {
317
- const idJson = JSON.stringify(subId);
318
- let delivered = true;
319
- for (const deltaBody of deltaFrames) {
320
- if (!trySendFrame(ws, `{"type":"delta","id":${idJson},"delta":${deltaBody}${cursorSuffix}}`)) {
321
- delivered = false;
322
- }
323
- }
324
- return delivered;
325
- };
326
- const awaitWsDrain = async (ws) => {
327
- let attempts = 0;
328
- while (attempts < 100) {
329
- attempts += 1;
330
- const buffered = ws.bufferedAmount;
331
- if (typeof buffered !== "number" || buffered < 1048576) {
332
- return;
333
- }
334
- await new Promise((resolve) => {
335
- setTimeout(resolve, 20);
336
- });
337
- }
338
- };
339
-
340
- export { awaitWsDrain as a, sendDeltaFrames as b, decodeWire as d, encodeWire as e, subscriptionListDeltas as s, trySendFrame as t };
@@ -1 +0,0 @@
1
- export { a as awaitWsDrain, b as sendDeltaFrames, s as subscriptionListDeltas, t as trySendFrame } from './subscription-delivery-Z6nXHvQN.mjs';