UNPKG

react-use-anywhere

Version:

Use React hooks anywhere in your codebase - in services, utilities, and business logic. Router-agnostic, hook-agnostic, and works with any React hooks (auth, navigation, state, custom hooks, etc.).

824 lines (820 loc) 26.1 kB
import * as Sr from "react"; import $e, { createContext as mr, useContext as wr, useRef as kr, useEffect as Oe } from "react"; var B = { exports: {} }, I = {}; var Pe; function Cr() { if (Pe) return I; Pe = 1; var t = $e, a = /* @__PURE__ */ Symbol.for("react.element"), v = /* @__PURE__ */ Symbol.for("react.fragment"), l = Object.prototype.hasOwnProperty, p = t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, _ = { key: !0, ref: !0, __self: !0, __source: !0 }; function g(m, y, h) { var S, C = {}, P = null, Y = null; h !== void 0 && (P = "" + h), y.key !== void 0 && (P = "" + y.key), y.ref !== void 0 && (Y = y.ref); for (S in y) l.call(y, S) && !_.hasOwnProperty(S) && (C[S] = y[S]); if (m && m.defaultProps) for (S in y = m.defaultProps, y) C[S] === void 0 && (C[S] = y[S]); return { $$typeof: a, type: m, key: P, ref: Y, props: C, _owner: p.current }; } return I.Fragment = v, I.jsx = g, I.jsxs = g, I; } var L = {}; var xe; function Tr() { return xe || (xe = 1, process.env.NODE_ENV !== "production" && (function() { var t = $e, a = /* @__PURE__ */ Symbol.for("react.element"), v = /* @__PURE__ */ Symbol.for("react.portal"), l = /* @__PURE__ */ Symbol.for("react.fragment"), p = /* @__PURE__ */ Symbol.for("react.strict_mode"), _ = /* @__PURE__ */ Symbol.for("react.profiler"), g = /* @__PURE__ */ Symbol.for("react.provider"), m = /* @__PURE__ */ Symbol.for("react.context"), y = /* @__PURE__ */ Symbol.for("react.forward_ref"), h = /* @__PURE__ */ Symbol.for("react.suspense"), S = /* @__PURE__ */ Symbol.for("react.suspense_list"), C = /* @__PURE__ */ Symbol.for("react.memo"), P = /* @__PURE__ */ Symbol.for("react.lazy"), Y = /* @__PURE__ */ Symbol.for("react.offscreen"), te = Symbol.iterator, Le = "@@iterator"; function We(e) { if (e === null || typeof e != "object") return null; var r = te && e[te] || e[Le]; return typeof r == "function" ? r : null; } var $ = t.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; function E(e) { { for (var r = arguments.length, n = new Array(r > 1 ? r - 1 : 0), o = 1; o < r; o++) n[o - 1] = arguments[o]; Ye("error", e, n); } } function Ye(e, r, n) { { var o = $.ReactDebugCurrentFrame, s = o.getStackAddendum(); s !== "" && (r += "%s", n = n.concat([s])); var c = n.map(function(u) { return String(u); }); c.unshift("Warning: " + r), Function.prototype.apply.call(console[e], console, c); } } var Me = !1, Ue = !1, qe = !1, Je = !1, Be = !1, ne; ne = /* @__PURE__ */ Symbol.for("react.module.reference"); function Ke(e) { return !!(typeof e == "string" || typeof e == "function" || e === l || e === _ || Be || e === p || e === h || e === S || Je || e === Y || Me || Ue || qe || typeof e == "object" && e !== null && (e.$$typeof === P || e.$$typeof === C || e.$$typeof === g || e.$$typeof === m || e.$$typeof === y || // This needs to include all possible module reference object // types supported by any Flight configuration anywhere since // we don't know which Flight build this will end up being used // with. e.$$typeof === ne || e.getModuleId !== void 0)); } function Ge(e, r, n) { var o = e.displayName; if (o) return o; var s = r.displayName || r.name || ""; return s !== "" ? n + "(" + s + ")" : n; } function oe(e) { return e.displayName || "Context"; } function T(e) { if (e == null) return null; if (typeof e.tag == "number" && E("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."), typeof e == "function") return e.displayName || e.name || null; if (typeof e == "string") return e; switch (e) { case l: return "Fragment"; case v: return "Portal"; case _: return "Profiler"; case p: return "StrictMode"; case h: return "Suspense"; case S: return "SuspenseList"; } if (typeof e == "object") switch (e.$$typeof) { case m: var r = e; return oe(r) + ".Consumer"; case g: var n = e; return oe(n._context) + ".Provider"; case y: return Ge(e, e.render, "ForwardRef"); case C: var o = e.displayName || null; return o !== null ? o : T(e.type) || "Memo"; case P: { var s = e, c = s._payload, u = s._init; try { return T(u(c)); } catch { return null; } } } return null; } var x = Object.assign, F = 0, ae, ie, ue, se, ce, le, fe; function de() { } de.__reactDisabledLog = !0; function ze() { { if (F === 0) { ae = console.log, ie = console.info, ue = console.warn, se = console.error, ce = console.group, le = console.groupCollapsed, fe = console.groupEnd; var e = { configurable: !0, enumerable: !0, value: de, writable: !0 }; Object.defineProperties(console, { info: e, log: e, warn: e, error: e, group: e, groupCollapsed: e, groupEnd: e }); } F++; } } function Xe() { { if (F--, F === 0) { var e = { configurable: !0, enumerable: !0, writable: !0 }; Object.defineProperties(console, { log: x({}, e, { value: ae }), info: x({}, e, { value: ie }), warn: x({}, e, { value: ue }), error: x({}, e, { value: se }), group: x({}, e, { value: ce }), groupCollapsed: x({}, e, { value: le }), groupEnd: x({}, e, { value: fe }) }); } F < 0 && E("disabledDepth fell below zero. This is a bug in React. Please file an issue."); } } var K = $.ReactCurrentDispatcher, G; function M(e, r, n) { { if (G === void 0) try { throw Error(); } catch (s) { var o = s.stack.trim().match(/\n( *(at )?)/); G = o && o[1] || ""; } return ` ` + G + e; } } var z = !1, U; { var Ze = typeof WeakMap == "function" ? WeakMap : Map; U = new Ze(); } function ve(e, r) { if (!e || z) return ""; { var n = U.get(e); if (n !== void 0) return n; } var o; z = !0; var s = Error.prepareStackTrace; Error.prepareStackTrace = void 0; var c; c = K.current, K.current = null, ze(); try { if (r) { var u = function() { throw Error(); }; if (Object.defineProperty(u.prototype, "props", { set: function() { throw Error(); } }), typeof Reflect == "object" && Reflect.construct) { try { Reflect.construct(u, []); } catch (R) { o = R; } Reflect.construct(e, [], u); } else { try { u.call(); } catch (R) { o = R; } e.call(u.prototype); } } else { try { throw Error(); } catch (R) { o = R; } e(); } } catch (R) { if (R && o && typeof R.stack == "string") { for (var i = R.stack.split(` `), b = o.stack.split(` `), f = i.length - 1, d = b.length - 1; f >= 1 && d >= 0 && i[f] !== b[d]; ) d--; for (; f >= 1 && d >= 0; f--, d--) if (i[f] !== b[d]) { if (f !== 1 || d !== 1) do if (f--, d--, d < 0 || i[f] !== b[d]) { var w = ` ` + i[f].replace(" at new ", " at "); return e.displayName && w.includes("<anonymous>") && (w = w.replace("<anonymous>", e.displayName)), typeof e == "function" && U.set(e, w), w; } while (f >= 1 && d >= 0); break; } } } finally { z = !1, K.current = c, Xe(), Error.prepareStackTrace = s; } var D = e ? e.displayName || e.name : "", j = D ? M(D) : ""; return typeof e == "function" && U.set(e, j), j; } function Qe(e, r, n) { return ve(e, !1); } function Ne(e) { var r = e.prototype; return !!(r && r.isReactComponent); } function q(e, r, n) { if (e == null) return ""; if (typeof e == "function") return ve(e, Ne(e)); if (typeof e == "string") return M(e); switch (e) { case h: return M("Suspense"); case S: return M("SuspenseList"); } if (typeof e == "object") switch (e.$$typeof) { case y: return Qe(e.render); case C: return q(e.type, r, n); case P: { var o = e, s = o._payload, c = o._init; try { return q(c(s), r, n); } catch { } } } return ""; } var V = Object.prototype.hasOwnProperty, pe = {}, ge = $.ReactDebugCurrentFrame; function J(e) { if (e) { var r = e._owner, n = q(e.type, e._source, r ? r.type : null); ge.setExtraStackFrame(n); } else ge.setExtraStackFrame(null); } function er(e, r, n, o, s) { { var c = Function.call.bind(V); for (var u in e) if (c(e, u)) { var i = void 0; try { if (typeof e[u] != "function") { var b = Error((o || "React class") + ": " + n + " type `" + u + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof e[u] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); throw b.name = "Invariant Violation", b; } i = e[u](r, u, o, n, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); } catch (f) { i = f; } i && !(i instanceof Error) && (J(s), E("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", o || "React class", n, u, typeof i), J(null)), i instanceof Error && !(i.message in pe) && (pe[i.message] = !0, J(s), E("Failed %s type: %s", n, i.message), J(null)); } } } var rr = Array.isArray; function X(e) { return rr(e); } function tr(e) { { var r = typeof Symbol == "function" && Symbol.toStringTag, n = r && e[Symbol.toStringTag] || e.constructor.name || "Object"; return n; } } function nr(e) { try { return ye(e), !1; } catch { return !0; } } function ye(e) { return "" + e; } function Ee(e) { if (nr(e)) return E("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", tr(e)), ye(e); } var be = $.ReactCurrentOwner, or = { key: !0, ref: !0, __self: !0, __source: !0 }, _e, Re; function ar(e) { if (V.call(e, "ref")) { var r = Object.getOwnPropertyDescriptor(e, "ref").get; if (r && r.isReactWarning) return !1; } return e.ref !== void 0; } function ir(e) { if (V.call(e, "key")) { var r = Object.getOwnPropertyDescriptor(e, "key").get; if (r && r.isReactWarning) return !1; } return e.key !== void 0; } function ur(e, r) { typeof e.ref == "string" && be.current; } function sr(e, r) { { var n = function() { _e || (_e = !0, E("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", r)); }; n.isReactWarning = !0, Object.defineProperty(e, "key", { get: n, configurable: !0 }); } } function cr(e, r) { { var n = function() { Re || (Re = !0, E("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", r)); }; n.isReactWarning = !0, Object.defineProperty(e, "ref", { get: n, configurable: !0 }); } } var lr = function(e, r, n, o, s, c, u) { var i = { // This tag allows us to uniquely identify this as a React Element $$typeof: a, // Built-in properties that belong on the element type: e, key: r, ref: n, props: u, // Record the component responsible for creating this element. _owner: c }; return i._store = {}, Object.defineProperty(i._store, "validated", { configurable: !1, enumerable: !1, writable: !0, value: !1 }), Object.defineProperty(i, "_self", { configurable: !1, enumerable: !1, writable: !1, value: o }), Object.defineProperty(i, "_source", { configurable: !1, enumerable: !1, writable: !1, value: s }), Object.freeze && (Object.freeze(i.props), Object.freeze(i)), i; }; function fr(e, r, n, o, s) { { var c, u = {}, i = null, b = null; n !== void 0 && (Ee(n), i = "" + n), ir(r) && (Ee(r.key), i = "" + r.key), ar(r) && (b = r.ref, ur(r, s)); for (c in r) V.call(r, c) && !or.hasOwnProperty(c) && (u[c] = r[c]); if (e && e.defaultProps) { var f = e.defaultProps; for (c in f) u[c] === void 0 && (u[c] = f[c]); } if (i || b) { var d = typeof e == "function" ? e.displayName || e.name || "Unknown" : e; i && sr(u, d), b && cr(u, d); } return lr(e, i, b, s, o, be.current, u); } } var Z = $.ReactCurrentOwner, he = $.ReactDebugCurrentFrame; function H(e) { if (e) { var r = e._owner, n = q(e.type, e._source, r ? r.type : null); he.setExtraStackFrame(n); } else he.setExtraStackFrame(null); } var Q; Q = !1; function N(e) { return typeof e == "object" && e !== null && e.$$typeof === a; } function Se() { { if (Z.current) { var e = T(Z.current.type); if (e) return ` Check the render method of \`` + e + "`."; } return ""; } } function dr(e) { return ""; } var me = {}; function vr(e) { { var r = Se(); if (!r) { var n = typeof e == "string" ? e : e.displayName || e.name; n && (r = ` Check the top-level render call using <` + n + ">."); } return r; } } function we(e, r) { { if (!e._store || e._store.validated || e.key != null) return; e._store.validated = !0; var n = vr(r); if (me[n]) return; me[n] = !0; var o = ""; e && e._owner && e._owner !== Z.current && (o = " It was passed a child from " + T(e._owner.type) + "."), H(e), E('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', n, o), H(null); } } function ke(e, r) { { if (typeof e != "object") return; if (X(e)) for (var n = 0; n < e.length; n++) { var o = e[n]; N(o) && we(o, r); } else if (N(e)) e._store && (e._store.validated = !0); else if (e) { var s = We(e); if (typeof s == "function" && s !== e.entries) for (var c = s.call(e), u; !(u = c.next()).done; ) N(u.value) && we(u.value, r); } } } function pr(e) { { var r = e.type; if (r == null || typeof r == "string") return; var n; if (typeof r == "function") n = r.propTypes; else if (typeof r == "object" && (r.$$typeof === y || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. r.$$typeof === C)) n = r.propTypes; else return; if (n) { var o = T(r); er(n, e.props, "prop", o, e); } else if (r.PropTypes !== void 0 && !Q) { Q = !0; var s = T(r); E("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", s || "Unknown"); } typeof r.getDefaultProps == "function" && !r.getDefaultProps.isReactClassApproved && E("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); } } function gr(e) { { for (var r = Object.keys(e.props), n = 0; n < r.length; n++) { var o = r[n]; if (o !== "children" && o !== "key") { H(e), E("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", o), H(null); break; } } e.ref !== null && (H(e), E("Invalid attribute `ref` supplied to `React.Fragment`."), H(null)); } } var Ce = {}; function Te(e, r, n, o, s, c) { { var u = Ke(e); if (!u) { var i = ""; (e === void 0 || typeof e == "object" && e !== null && Object.keys(e).length === 0) && (i += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."); var b = dr(); b ? i += b : i += Se(); var f; e === null ? f = "null" : X(e) ? f = "array" : e !== void 0 && e.$$typeof === a ? (f = "<" + (T(e.type) || "Unknown") + " />", i = " Did you accidentally export a JSX literal instead of a component?") : f = typeof e, E("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", f, i); } var d = fr(e, r, n, s, c); if (d == null) return d; if (u) { var w = r.children; if (w !== void 0) if (o) if (X(w)) { for (var D = 0; D < w.length; D++) ke(w[D], e); Object.freeze && Object.freeze(w); } else E("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."); else ke(w, e); } if (V.call(r, "key")) { var j = T(e), R = Object.keys(r).filter(function(hr) { return hr !== "key"; }), ee = R.length > 0 ? "{key: someKey, " + R.join(": ..., ") + ": ...}" : "{key: someKey}"; if (!Ce[j + ee]) { var Rr = R.length > 0 ? "{" + R.join(": ..., ") + ": ...}" : "{}"; E(`A props object containing a "key" prop is being spread into JSX: let props = %s; <%s {...props} /> React keys must be passed directly to JSX without using spread: let props = %s; <%s key={someKey} {...props} />`, ee, j, Rr, j), Ce[j + ee] = !0; } } return e === l ? gr(d) : pr(d), d; } } function yr(e, r, n) { return Te(e, r, n, !0); } function Er(e, r, n) { return Te(e, r, n, !1); } var br = Er, _r = yr; L.Fragment = l, L.jsx = br, L.jsxs = _r; })()), L; } var je; function Or() { return je || (je = 1, process.env.NODE_ENV === "production" ? B.exports = Cr() : B.exports = Tr()), B.exports; } var Pr = Or(); let A = { enabled: !1 }; function Dr(t) { A = { ...A, ...t }; } function Ar() { return { ...A }; } const k = { log(...t) { A.enabled && process.env.NODE_ENV !== "production" && console.log(...t); }, warn(...t) { A.enabled && process.env.NODE_ENV !== "production" && console.warn(...t); }, error(...t) { A.enabled && process.env.NODE_ENV !== "production" && console.error(...t); } }, He = mr(null); let re = {}; const xr = ({ children: t, hooks: a }) => { re = a; const v = Object.entries(a), l = {}; for (let p = 0; p < v.length; p++) { const [_, g] = v[p]; try { l[_] = g(), k.log( `✅ HookProvider: Executed hook "${_}"`, l[_] ); } catch (m) { k.warn(`Failed to execute hook "${_}":`, m), l[_] = void 0; } } return k.log( "🎯 HookProvider: Providing context with hooks:", Object.keys(l) ), /* @__PURE__ */ Pr.jsx(He.Provider, { value: l, children: t }); }, Fr = ({ children: t, hooks: a }) => xr({ children: t, hooks: a }), W = () => { const t = wr(He); if (t === null) throw new Error("useHookContext must be used within a HookProvider"); return t; }; function Vr() { return W(); } const De = (t) => Object.prototype.hasOwnProperty.call(re, t), Ae = () => Object.keys(re); function Fe(t, a) { const v = W(), l = kr(void 0), [, p] = Sr.useReducer((g) => g + 1, 0); k.log( `🔌 useHookService: Connecting service to hook "${a}"`, v[a] ), Oe(() => { if (!De(a)) { const g = Ae(), m = g.filter( (h) => h.toLowerCase().includes(a.toLowerCase()) || a.toLowerCase().includes(h.toLowerCase()) ).slice(0, 3), y = m.length > 0 ? ` Did you mean one of these? ${m.map((h) => ` • "${h}"`).join(` `)}` : ""; k.error( `🚨 useHookService: Hook "${a}" is not registered in HookProvider. Available hooks: ${g.map((h) => `"${h}"`).join(", ")}${y}` ); } }, [a]); const _ = v[a]; _ !== l.current && (t._setValue(_), l.current = _, k.log( `✅ useHookService: Value set for "${a}" during render. Service ready:`, t.isReady() )), Oe(() => { const g = v[a]; k.log( `📝 useHookService: Effect running for "${a}"`, g ), g !== l.current && (t._setValue(g), l.current = g, k.log( `✅ useHookService: Value updated for "${a}" in effect` ), p()); }, [v, t, a, p]); } function Ir(t, a) { Fe(t, a); } function Lr(t, a) { Fe(t, a); } function Wr(t) { return W()[t]; } function Yr(t) { return jr(t); } function jr(t) { const a = W(); return Object.prototype.hasOwnProperty.call(a, t) ? a[t] : void 0; } function Mr() { return W(); } function Ve() { let t = null, a = !1; return { // Internal method used by useHookService - don't call directly _setValue(v) { (v !== t || !a) && (t = v, a = !0); }, // Get the current hook value get() { return t; }, // Check if the hook value is available isReady() { return a; }, // Use the hook value in a callback - this is the main way to use hooks in non-React files use(v) { if (!a) return k.warn( "Hook service not ready. Make sure you're using useHookService in a React component." ), null; try { return v(t); } catch (l) { return k.error("Error using hook service:", l), null; } }, // Reset the service (for testing) _reset() { t = null, a = !1; } }; } const O = /* @__PURE__ */ new Map(); function $r(t) { const a = Ae(); if (a.length === 0) { k.warn( `🚨 No hooks registered yet. Make sure to wrap your app with HookProvider first. Example: <HookProvider hooks={{ ${t}: your${t.charAt(0).toUpperCase() + t.slice(1)}Hook }}>` ); return; } if (!De(t)) { const v = a.filter( (p) => p.toLowerCase().includes(t.toLowerCase()) || t.toLowerCase().includes(p.toLowerCase()) ).slice(0, 3), l = v.length > 0 ? ` Did you mean one of these? ${v.map((p) => ` • "${p}"`).join(` `)}` : ""; k.error( `🚨 Hook "${t}" is not registered in HookProvider. Available hooks: ${a.map((p) => `"${p}"`).join(", ")}${l} 💡 Make sure your HookProvider includes: <HookProvider hooks={{ ${t}: your${t.charAt(0).toUpperCase() + t.slice(1)}Hook, ...other hooks }}>` ); } } function Ie(t) { return O.has(t) || O.set(t, Ve()), O.get(t); } function Ur(t) { const a = O.get(t); return a || null; } function qr() { O.forEach((t) => { t._reset(); }); } function Jr(t) { return Ie(t); } function Br(t) { return $r(t), O.has(t) || O.set(t, Ve()), O.get(t); } function Kr(t) { return Ie(t); } export { xr as HookProvider, Fr as TypedHookProvider, Dr as configureLogging, Ve as createHookService, Kr as createInferredSingletonService, Ie as createSingletonService, Br as createStrictSingletonService, Jr as createTypedSingletonService, Ar as getLoggerConfig, Ur as getSingletonService, qr as resetAllServices, Mr as useAllHooks, jr as useHook, W as useHookContext, Fe as useHookService, Yr as useStrictHook, Lr as useStrictHookService, Wr as useTypedHook, Vr as useTypedHookContext, Ir as useTypedHookService }; //# sourceMappingURL=index.js.map