UNPKG

fraci

Version:

Fractional indexing that's robust, performant, and secure, with first-class support for Drizzle ORM and Prisma ORM.

766 lines (753 loc) 16.6 kB
"use strict"; var v = Object.defineProperty; var _n = Object.getOwnPropertyDescriptor; var Pn = Object.getOwnPropertyNames; var Bn = Object.prototype.hasOwnProperty; var bn = (n, e) => { for (var r in e) v(n, r, { get: e[r], enumerable: !0 }); }, wn = (n, e, r, t) => { if (e && typeof e == "object" || typeof e == "function") for (let o of Pn(e)) !Bn.call(n, o) && o !== r && v(n, o, { get: () => e[o], enumerable: !(t = _n(e, o)) || t.enumerable }); return n; }; var Tn = (n) => wn(v({}, "__esModule", { value: !0 }), n); // src/prisma.ts var Un = {}; bn(Un, { definePrismaFraci: () => Mn, prismaFraci: () => Rn }); module.exports = Tn(Un); // src/prisma/extension.ts var xn = require("@prisma/client/extension.js"); // src/lib/decimal-binary.ts var W = new Uint8Array([128, 0]), Nn = new Uint8Array([127, 255]); function b(n, e) { let r = Math.min(n.length, e.length), t = 0; for (let o = 0; !t && o < r; o++) t = n[o] - e[o]; return t || n.length - e.length; } function x(n, e) { let r = new Uint8Array(n.length + e.length); return r.set(n), r.set(e, n.length), r; } function Z(n) { let [e] = n; return e - (e >= 128 ? 127 : 128); } function rn(n) { return n + (n < 0 ? 128 : 127); } function R(n) { return n.length === 129 && n.every((e) => e === 0); } function w(n) { let e = Math.abs(Z(n)) + 1; if (!(Number.isNaN(e) || n.length < e)) return [n.subarray(0, e), n.subarray(e)]; } function q(n) { if (!n.length) return; let e = Z(n), r = n.slice(0, Math.abs(e) + 1); for (let i = r.length - 1; i >= 1; i--) if (r[i]++ < 255) return r; if (e === -1) return W.slice(); let t = e + 1; if (t > 128) return null; let o = new Uint8Array(Math.abs(t) + 1); return o[0] = rn(t), o; } function tn(n) { let e = Z(n); if (Number.isNaN(e)) return; let r = n.slice(0, Math.abs(e) + 1); for (let i = r.length - 1; i >= 1; i--) if (r[i]--) return r; if (e === 1) return Nn.slice(); let t = e - 1; if (t < -128) return null; let o = new Uint8Array(Math.abs(t) + 1).fill(255); return o[0] = rn(t), o; } function M(n, e) { if (e != null && b(n, e) >= 0) return; if (e) { let a = e.findIndex((s, l) => s !== (n[l] ?? 0)); if (a > 0) { let s = M( n.subarray(a), e.subarray(a) ); return s ? x(e.subarray(0, a), s) : void 0; } } let r = n[0] ?? 0, t = e ? e[0] : 256; if (t == null) return; if (r + 1 !== t) { let a = r + t >> 1; return new Uint8Array([a]); } if (e && e.length > 1) return new Uint8Array([e[0]]); let o = M(n.subarray(1), null); if (!o) return; let i = new Uint8Array(1 + o.length); return i[0] = r, i.set(o, 1), i; } // src/lib/decimal-string.ts function H(n, e) { return e.get(n[0]); } function T(n, e) { let r = Math.abs(H(n, e) ?? 0) + 1; if (!(r < 2 || n.length < r)) return [n.slice(0, r), n.slice(r)]; } function on(n, e) { return e.get(1) + n[0]; } function an(n, e) { let r = Math.min(...Array.from(e.keys())); return `${e.get(r)}${n[0].repeat(Math.abs(r))}`; } function z(n, e, r, t, o) { let i = H(n, o); if (!i) return; let a = e[0], [s, ...l] = n.slice(0, Math.abs(i) + 1); for (let f = l.length - 1; f >= 0; f--) { let g = r.get(l[f]); if (g == null) return; if (g < e.length - 1) return l[f] = e[g + 1], `${s}${l.join("")}`; l[f] = a; } if (i === -1) return `${t.get(1)}${a}`; let c = i + 1, d = t.get(c); return d ? `${d}${a.repeat(Math.abs(c))}` : null; } function sn(n, e, r, t, o) { let i = H(n, o); if (!i) return; let a = e[e.length - 1], [s, ...l] = n.slice(0, Math.abs(i) + 1); for (let f = l.length - 1; f >= 0; f--) { let g = r.get(l[f]); if (g == null) return; if (g > 0) return l[f] = e[g - 1], `${s}${l.join("")}`; l[f] = a; } if (i === 1) return `${t.get(-1)}${a}`; let c = i - 1, d = t.get(c); return d ? `${d}${a.repeat(Math.abs(c))}` : null; } function O(n, e, r, t) { if (e != null && e <= n) return; if (e) { let a = n.padEnd(e.length, r[0]), s = Array.prototype.findIndex.call( e, (l, c) => l !== a[c] ); if (s > 0) return `${e.slice(0, s)}${O( n.slice(s), e.slice(s), r, t )}`; } let o = n ? t.get(n[0]) : 0, i = e ? t.get(e[0]) : r.length; if (!(o == null || i == null)) { if (o + 1 !== i) { let a = o + i >> 1; return r[a]; } return e && e.length > 1 ? e[0] : `${r[o]}${O( n.slice(1), null, r, t )}`; } } // src/lib/errors.ts var u = class extends Error { constructor(r, t) { super(`[${r}] ${t}`); this.code = r; this.message = t; this.name = "FraciError"; } name; }; // src/lib/fractional-indexing-binary.ts function U(n) { return n?.constructor.name === "Buffer" ? new Uint8Array(n.buffer, n.byteOffset, n.length) : n; } function S(n) { if (!n.length || R(n)) return !1; let e = w(n); if (!e) return !1; let [, r] = e; return r?.at(-1) !== 0; } function I(n) { if (n === void 0) throw new u("INTERNAL_ERROR", "Unexpected undefined"); return n; } function N(n, e) { if (!n) { if (!e) return W.slice(); let [s, l] = I(w(e)); if (R(s)) return x( s, I(M(new Uint8Array(), l)) ); if (l.length) return s.slice(); let c = I( tn(s) ); if (!R(c)) return c; let d = new Uint8Array(c.length + 1); return d.set(c), d[c.length] = 255, d; } if (!e) { let s = I(w(n)), [l, c] = s, d = I(q(l)); return d || x(l, I(M(c, null))); } let [r, t] = I(w(n)), [o, i] = I(w(e)); if (!b(r, o)) return x( r, I(M(t, i)) ); let a = I(q(r)); return a && b(a, o) ? ( // 1. If incrementing a's integer doesn't reach b's integer, // we can use the incremented value (shorter key) a ) : ( // 2. If incrementing a's integer equals b's integer or we can't increment, // we need to use a's integer with a fractional part that sorts after a's fractional part x(r, I(M(t, null))) ); } function ln(n, e) { return n != null && !S(n) || e != null && !S(e) || n != null && e != null && b(n, e) >= 0 ? void 0 : N(U(n), U(e)); } function J(n, e, r) { if (r < 1) return []; if (r === 1) return [N(n, e)]; if (e == null) { let i = n; return Array.from( { length: r }, () => i = N(i, e) ); } if (n == null) { let i = e; return Array.from( { length: r }, () => i = N(n, i) ).reverse(); } let t = r >> 1, o = N(n, e); return [ ...J(n, o, t), o, ...J(o, e, r - t - 1) ]; } function cn(n, e, r) { return n != null && !S(n) || e != null && !S(e) || n != null && e != null && b(n, e) >= 0 ? void 0 : J(U(n), U(e), r); } function Y(n) { let e = []; for (; n > 0; ) e.push(n & 255), n >>= 8; return new Uint8Array(e); } // src/lib/fractional-indexing-string.ts function L(n, e, r, t, o) { if (!n || n === o) return !1; let i = T(n, t); if (!i) return !1; let [a, s] = i; if (s.endsWith(e[0])) return !1; for (let l of a.slice(1)) if (!r.has(l)) return !1; for (let l of s) if (!r.has(l)) return !1; return !0; } function A(n) { if (n === void 0) throw new u("INTERNAL_ERROR", "Unexpected undefined"); return n; } function C(n, e, r, t, o, i, a) { if (!n) { if (!e) return on(r, o); let [p, m] = A(T(e, i)); if (p === a) return `${p}${A( O("", m, r, t) )}`; if (m) return p; let F = A( sn( p, r, t, o, i ) ); return F === a ? `${F}${r[r.length - 1]}` : F; } if (!e) { let p = A(T(n, i)), [m, F] = p, y = A( z( m, r, t, o, i ) ); return y !== null ? y : `${m}${A( O(F, null, r, t) )}`; } let s = A(T(n, i)), l = A(T(e, i)), [c, d] = s, [f, g] = l; if (c === f) return `${c}${A( O(d, g, r, t) )}`; let h = A( z( c, r, t, o, i ) ); return h !== null && h !== f ? ( // 1. If incrementing a's integer doesn't reach b's integer, // we can use the incremented value (shorter key) h ) : ( // 2. If incrementing a's integer equals b's integer or we can't increment, // we need to use a's integer with a fractional part that sorts after a's fractional part `${c}${A( O(d, null, r, t) )}` ); } function dn(n, e, r, t, o, i, a) { return n != null && !L( n, r, t, i, a ) || e != null && !L( e, r, t, i, a ) || n != null && e != null && e <= n ? void 0 : C( n, e, r, t, o, i, a ); } function nn(n, e, r, ...t) { if (r < 1) return []; if (r === 1) return [C(n, e, ...t)]; if (e == null) { let a = n; return Array.from( { length: r }, () => a = C(a, e, ...t) ); } if (n == null) { let a = e; return Array.from( { length: r }, () => a = C(n, a, ...t) ).reverse(); } let o = r >> 1, i = C(n, e, ...t); return [ ...nn(n, i, o, ...t), i, ...nn(i, e, r - o - 1, ...t) ]; } function un(n, e, r, t, o, i, a, s) { return n != null && !L( n, t, o, a, s ) || e != null && !L( e, t, o, a, s ) || n != null && e != null && e <= n ? void 0 : nn( n, e, r, t, o, i, a, s ); } function en(n, e) { let r = e.length, t = ""; for (; n > 0; ) t += e[n % r], n = Math.floor(n / r); return t; } // src/lib/utils.ts var fn = "INITIALIZATION_FAILED"; function yn(n) { let e = n.split(""); if (e.length < 4) throw new u( fn, "Base string must have at least 4 unique characters" ); let r = -1; for (let t of e) { let o = t.charCodeAt(0); if (o <= r) throw new u( fn, "Base string characters must be unique and in ascending order" ); r = o; } return e; } function pn(n) { let e = yn(n); return [e, new Map(e.map((r, t) => [r, t]))]; } function gn(n) { let e = yn(n), r = e.length >> 1, t = e.map( (o, i) => [ i < r ? ( // For characters in the first half, assign negative values starting from -1 i - r ) : ( // For characters in the second half, assign positive values starting from 1 i - r + 1 ), // This maps to 1, 2, 3, etc. (skipping 0) o ] ); return [ new Map(t), new Map(t.map(([o, i]) => [i, o])) ]; } // src/factory.ts var Q = 50, V = 5, D = "INVALID_FRACTIONAL_INDEX", $ = "Invalid indices provided", X = "MAX_LENGTH_EXCEEDED", K = "Exceeded maximum length", k = "MAX_RETRIES_EXCEEDED", G = "Exceeded maximum retries"; function Fn() { return /* @__PURE__ */ new Map(); } function mn(n, e, r) { if (!n) return r(); let t = n.get(e); return t === void 0 && (t = r(), n.set(e, t)), t; } function En({ maxLength: n = Q, maxRetries: e = V } = {}) { return { base: { type: "binary" }, *generateKeyBetween(r, t, o = 0) { let i = ln(r, t); if (!i) throw new u( D, $ ); for (let a = 0; a < e; a++) { let s = x(i, Y(a + o)); if (s.length > n) throw new u( X, K ); yield s; } throw new u( k, G ); }, *generateNKeysBetween(r, t, o, i = 0) { let a = cn(r, t, o); if (!a) throw new u( D, $ ); let s = a.reduce((l, c) => Math.max(l, c.length), 0); for (let l = 0; l < e; l++) { let c = Y(l + i); if (s + c.length > n) throw new u( X, K ); yield a.map((d) => x(d, c)); } throw new u( k, G ); } }; } function hn({ lengthBase: n, digitBase: e, maxLength: r = Q, maxRetries: t = V }, o) { let [i, a] = mn( o, `L${n}`, gn.bind(null, n) ), [s, l] = mn( o, `D${e}`, pn.bind(null, e) ), c = an(s, i); return { base: { type: "string", lengthBase: n, digitBase: e }, *generateKeyBetween(d, f, g = 0) { let h = dn( d, f, s, l, i, a, c ); if (!h) throw new u( D, $ ); for (let p = 0; p < t; p++) { let m = `${h}${en(p + g, s)}`; if (m.length > r) throw new u( X, K ); yield m; } throw new u( k, G ); }, *generateNKeysBetween(d, f, g, h = 0) { let p = un( d, f, g, s, l, i, a, c ); if (!p) throw new u( D, $ ); let m = p.reduce((F, y) => Math.max(F, y.length), 0); for (let F = 0; F < t; F++) { let y = en(F + h, s); if (m + y.length > r) throw new u( X, K ); yield p.map((E) => `${E}${y}`); } throw new u( k, G ); } }; } // src/prisma/common.ts var Cn = "P2002"; function In(n, e, r) { return n instanceof Error && n.name === "PrismaClientKnownRequestError" && n.code === Cn && // P2002 is the Prisma code for unique constraint violations n.meta?.modelName === e && // Check if the error is for the correct model Array.isArray(n.meta?.target) && // Check if the target field is specified n.meta.target.includes(r); } // src/prisma/constants.ts var An = "fraci"; // src/prisma/extension.ts function Rn({ fields: n, maxLength: e = Q, maxRetries: r = V }) { return xn.Prisma.defineExtension((t) => { let o = Fn(), i = /* @__PURE__ */ new Map(); for (let [s, l] of Object.entries(n)) { let [c, d] = s.split(".", 2), { modelName: f } = t[c]?.fields?.[d] ?? {}; if (!f) throw new u( "INITIALIZATION_FAILED", `Could not get field information for ${c}.${d}` ); let g = l.type === "binary" ? En({ maxLength: e, maxRetries: r }) : hn( { ...l, maxLength: e, maxRetries: r }, o ), h = async (y, E, _, P, B = t) => { if (!E) { let On = await B[c].findFirst({ where: y, // Filter by group conditions select: { [d]: !0 }, // Only select the fractional index field orderBy: { [d]: _ } // Order by the fractional index in appropriate direction }); return P(null, On?.[d] ?? null); } let j = await B[c].findMany({ cursor: E, // Start from the cursor position where: y, // Filter by group conditions select: { [d]: !0 }, // Only select the fractional index field orderBy: { [d]: _ }, // Order by the fractional index in appropriate direction take: 2 // Get the cursor item and the adjacent item }); return j.length < 1 ? ( // Return undefined if cursor not found void 0 ) : ( // Return the indices in the appropriate order based on direction P(j[0][d], j[1]?.[d] ?? null) ); }, p = (y, E, _) => h(y, E, "asc", (P, B) => [P, B], _), m = (y, E, _) => h(y, E, "desc", (P, B) => [B, P], _), F = { ...g, // Include all methods from the base fraci helper isIndexConflictError: (y) => In(y, f, d), indicesForAfter: p, indicesForBefore: m, indicesForFirst: (y, E) => p(y, null, E), indicesForLast: (y, E) => m(y, null, E) }; i.set(`${c}\0${d}`, F); } let a = /* @__PURE__ */ Object.create(null); for (let s of Object.keys(t)) s.startsWith("$") || s.startsWith("_") || (a[s] = { // This method retrieves the appropriate helper for the specified field fraci(l) { return i.get(`${s}\0${l}`); } }); return t.$extends({ name: An, model: a }); }); } // src/prisma/schema.ts function Mn(n) { return n; } // Annotate the CommonJS export names for ESM import in node: 0 && (module.exports = { definePrismaFraci, prismaFraci }); //# sourceMappingURL=prisma.cjs.map