https://buffet-crayon-23938188.figma.site/_components/v2/dfec6a6cec67b2de1eeda21cfe393b8c825ff76a.js
1const RR = () => Promise.resolve().then(() => AR), Zm = globalThis.__GLOBALS__.ReactJSXRuntime, { Fragment: rr, jsx: P, jsxs: re } = Zm; 2"use" in globalThis.__GLOBALS__.React || (globalThis.__GLOBALS__.React.use = () => { 3 throw new Error("`use` is not available in this version of React. Make currently only supports React 18, but `use` is only available in React 19+."); 4}); 5function Bf(n) { 6 const e = n?.props?._fgT, t = typeof e == "function" || typeof e == "string" || typeof e == "object" && e !== null && "$$typeof" in e; 7 return globalThis.__GLOBALS__.React.isValidElement(n) && t; 8} 9function Vs(n) { 10 return globalThis.__GLOBALS__.React.isValidElement(n) && n.type === "fg-txt"; 11} 12function zf(n) { 13 const { _fgT: e, _fgS: t, _fgB: i, _fgD: r, ...s } = n.props; 14 return globalThis.__GLOBALS__.React.createElement(e, { 15 ...s, 16 key: n.key 17 }, s.children); 18} 19function Ra(n) { 20 return Bf(n) ? zf(n) : Vs(n) ? n.props.children : n; 21} 22const Cs = globalThis.__GLOBALS__.React.Children, Hf = { 23 map(n, e, t) { 24 return Cs.map(n, (i, r) => { 25 const s = Ra(i); 26 return Vs(i) ? null : e.call(t, s, r); 27 }); 28 }, 29 forEach(n, e, t) { 30 Cs.forEach(n, (i, r) => { 31 if (Vs(i)) 32 return; 33 const s = Ra(i); 34 e.call(t, s, r); 35 }); 36 }, 37 count(n) { 38 let e = 0; 39 return Cs.forEach(n, (t) => { 40 Vs(t) || e++; 41 }), e; 42 }, 43 toArray(n) { 44 const e = []; 45 return Cs.forEach(n, (t) => { 46 Vs(t) || e.push(Ra(t)); 47 }), e; 48 }, 49 only(n) { 50 const e = Cs.only(n); 51 return Ra(e); 52 } 53}, il = [ 54 "_fgT", 55 "_fgS", 56 "_fgB", 57 "_fgD" 58]; 59function Qm(n) { 60 if (n == null || typeof n != "object") return n; 61 const e = Object.keys(n); 62 let t = !1; 63 for (let r = 0; r < il.length; r++) 64 if (il[r] in n) { 65 t = !0; 66 break; 67 } 68 if (!t) return n; 69 const i = {}; 70 for (let r = 0; r < e.length; r++) { 71 const s = e[r]; 72 il.indexOf(s) === -1 && (i[s] = n[s]); 73 } 74 return i; 75} 76const uh = globalThis.__GLOBALS__.React.cloneElement, Gf = (n, ...e) => { 77 if (Bf(n)) { 78 const t = zf(n), i = e[0]; 79 return i != null && typeof i == "object" && (e = [ 80 Qm(i), 81 ...e.slice(1) 82 ]), uh(t, ...e); 83 } 84 return uh(n, ...e); 85}, Jt = { 86 ...globalThis.__GLOBALS__.React, 87 Children: Hf, 88 cloneElement: Gf 89}, { Component: Vf, createContext: Un, createElement: st, createFactory: eg, createRef: tg, forwardRef: ws, Fragment: ps, isValidElement: ng, lazy: ig, memo: Wf, Profiler: rg, PureComponent: sg, startTransition: na, StrictMode: ag, Suspense: og, use: lg, useCallback: Gn, useContext: Mt, useDebugValue: cg, useDeferredValue: ug, useEffect: bt, useId: hg, useImperativeHandle: dg, useInsertionEffect: fg, useLayoutEffect: vu, useMemo: Nn, useReducer: pg, useRef: mt, useState: Xe, useSyncExternalStore: mg, useTransition: gg, version: vg, __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: _g } = globalThis.__GLOBALS__.React, yg = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ 90 __proto__: null, 91 Children: Hf, 92 Component: Vf, 93 Fragment: ps, 94 Profiler: rg, 95 PureComponent: sg, 96 StrictMode: ag, 97 Suspense: og, 98 __SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: _g, 99 cloneElement: Gf, 100 createContext: Un, 101 createElement: st, 102 createFactory: eg, 103 createRef: tg, 104 default: Jt, 105 forwardRef: ws, 106 isValidElement: ng, 107 lazy: ig, 108 memo: Wf, 109 startTransition: na, 110 use: lg, 111 useCallback: Gn, 112 useContext: Mt, 113 useDebugValue: cg, 114 useDeferredValue: ug, 115 useEffect: bt, 116 useId: hg, 117 useImperativeHandle: dg, 118 useInsertionEffect: fg, 119 useLayoutEffect: vu, 120 useMemo: Nn, 121 useReducer: pg, 122 useRef: mt, 123 useState: Xe, 124 useSyncExternalStore: mg, 125 useTransition: gg, 126 version: vg 127}, Symbol.toStringTag, { value: "Module" })); 128/** 129 * react-router v7.13.0 130 * 131 * Copyright (c) Remix Software Inc. 132 * 133 * This source code is licensed under the MIT license found in the 134 * LICENSE.md file in the root directory of this source tree. 135 * 136 * @license MIT 137 */ 138var $f = (n) => { 139 throw TypeError(n); 140}, xg = (n, e, t) => e.has(n) || $f("Cannot " + t), rl = (n, e, t) => (xg(n, e, "read from private field"), t ? t.call(n) : e.get(n)), bg = (n, e, t) => e.has(n) ? $f("Cannot add the same private member more than once") : e instanceof WeakSet ? e.add(n) : e.set(n, t), hh = "popstate"; 141function wg(n = {}) { 142 function e(i, r) { 143 let { pathname: s, search: a, hash: l } = i.location; 144 return ia( 145 "", 146 { pathname: s, search: a, hash: l }, 147 // state defaults to `null` because `window.history.state` does 148 r.state && r.state.usr || null, 149 r.state && r.state.key || "default" 150 ); 151 } 152 function t(i, r) { 153 return typeof r == "string" ? r : mi(r); 154 } 155 return Eg( 156 e, 157 t, 158 null, 159 n 160 ); 161} 162function ht(n, e) { 163 if (n === !1 || n === null || typeof n > "u") 164 throw new Error(e); 165} 166function jt(n, e) { 167 if (!n) { 168 typeof console < "u" && console.warn(e); 169 try { 170 throw new Error(e); 171 } catch { 172 } 173 } 174} 175function Sg() { 176 return Math.random().toString(36).substring(2, 10); 177} 178function dh(n, e) { 179 return { 180 usr: n.state, 181 key: n.key, 182 idx: e 183 }; 184} 185function ia(n, e, t = null, i) { 186 return { 187 pathname: typeof n == "string" ? n : n.pathname, 188 search: "", 189 hash: "", 190 ...typeof e == "string" ? cr(e) : e, 191 state: t, 192 // TODO: This could be cleaned up. push/replace should probably just take 193 // full Locations now and avoid the need to run through this flow at all 194 // But that's a pretty big refactor to the current test suite so going to 195 // keep as is for the time being and just let any incoming keys take precedence 196 key: e && e.key || i || Sg() 197 }; 198} 199function mi({ 200 pathname: n = "/", 201 search: e = "", 202 hash: t = "" 203}) { 204 return e && e !== "?" && (n += e.charAt(0) === "?" ? e : "?" + e), t && t !== "#" && (n += t.charAt(0) === "#" ? t : "#" + t), n; 205} 206function cr(n) { 207 let e = {}; 208 if (n) { 209 let t = n.indexOf("#"); 210 t >= 0 && (e.hash = n.substring(t), n = n.substring(0, t)); 211 let i = n.indexOf("?"); 212 i >= 0 && (e.search = n.substring(i), n = n.substring(0, i)), n && (e.pathname = n); 213 } 214 return e; 215} 216function Eg(n, e, t, i = {}) { 217 let { window: r = document.defaultView, v5Compat: s = !1 } = i, a = r.history, l = "POP", o = null, c = u(); 218 c == null && (c = 0, a.replaceState({ ...a.state, idx: c }, "")); 219 function u() { 220 return (a.state || { idx: null }).idx; 221 } 222 function h() { 223 l = "POP"; 224 let m = u(), g = m == null ? null : m - c; 225 c = m, o && o({ action: l, location: v.location, delta: g }); 226 } 227 function d(m, g) { 228 l = "PUSH"; 229 let _ = ia(v.location, m, g); 230 c = u() + 1; 231 let x = dh(_, c), E = v.createHref(_); 232 try { 233 a.pushState(x, "", E); 234 } catch (R) { 235 if (R instanceof DOMException && R.name === "DataCloneError") 236 throw R; 237 r.location.assign(E); 238 } 239 s && o && o({ action: l, location: v.location, delta: 1 }); 240 } 241 function f(m, g) { 242 l = "REPLACE"; 243 let _ = ia(v.location, m, g); 244 c = u(); 245 let x = dh(_, c), E = v.createHref(_); 246 a.replaceState(x, "", E), s && o && o({ action: l, location: v.location, delta: 0 }); 247 } 248 function p(m) { 249 return jf(m); 250 } 251 let v = { 252 get action() { 253 return l; 254 }, 255 get location() { 256 return n(r, a); 257 }, 258 listen(m) { 259 if (o) 260 throw new Error("A history only accepts one active listener"); 261 return r.addEventListener(hh, h), o = m, () => { 262 r.removeEventListener(hh, h), o = null; 263 }; 264 }, 265 createHref(m) { 266 return e(r, m); 267 }, 268 createURL: p, 269 encodeLocation(m) { 270 let g = p(m); 271 return { 272 pathname: g.pathname, 273 search: g.search, 274 hash: g.hash 275 }; 276 }, 277 push: d, 278 replace: f, 279 go(m) { 280 return a.go(m); 281 } 282 }; 283 return v; 284} 285function jf(n, e = !1) { 286 let t = "http://localhost"; 287 typeof window < "u" && (t = window.location.origin !== "null" ? window.location.origin : window.location.href), ht(t, "No window.location.(origin|href) available to create URL"); 288 let i = typeof n == "string" ? n : mi(n); 289 return i = i.replace(/ $/, "%20"), !e && i.startsWith("//") && (i = t + i), new URL(i, t); 290} 291var Ws, fh = class { 292 /** 293 * Create a new `RouterContextProvider` instance 294 * @param init An optional initial context map to populate the provider with 295 */ 296 constructor(n) {
297 if (bg(this, Ws, /* @__PURE__ */ new Map()), n) 298 for (let [e, t] of n) 299 this.set(e, t); 300 } 301 /** 302 * Access a value from the context. If no value has been set for the context, 303 * it will return the context's `defaultValue` if provided, or throw an error 304 * if no `defaultValue` was set. 305 * @param context The context to get the value for 306 * @returns The value for the context, or the context's `defaultValue` if no 307 * value was set 308 */ 309 get(n) { 310 if (rl(this, Ws).has(n)) 311 return rl(this, Ws).get(n); 312 if (n.defaultValue !== void 0) 313 return n.defaultValue; 314 throw new Error("No value found for context"); 315 } 316 /** 317 * Set a value for the context. If the context already has a value set, this 318 * will overwrite it. 319 * 320 * @param context The context to set the value for 321 * @param value The value to set for the context 322 * @returns {void} 323 */ 324 set(n, e) { 325 rl(this, Ws).set(n, e); 326 } 327}; 328Ws = /* @__PURE__ */ new WeakMap(); 329var Mg = /* @__PURE__ */ new Set([ 330 "lazy", 331 "caseSensitive", 332 "path", 333 "id", 334 "index", 335 "children" 336]); 337function Tg(n) { 338 return Mg.has( 339 n 340 ); 341} 342var Ag = /* @__PURE__ */ new Set([ 343 "lazy", 344 "caseSensitive", 345 "path", 346 "id", 347 "index", 348 "middleware", 349 "children" 350]); 351function Rg(n) { 352 return Ag.has( 353 n 354 ); 355} 356function Cg(n) { 357 return n.index === !0; 358} 359function ra(n, e, t = [], i = {}, r = !1) { 360 return n.map((s, a) => { 361 let l = [...t, String(a)], o = typeof s.id == "string" ? s.id : l.join("-"); 362 if (ht( 363 s.index !== !0 || !s.children, 364 "Cannot specify children on an index route" 365 ), ht( 366 r || !i[o],
vendor: 8,983 bytes, lines 367-674
367 `Found a route id collision on id "${o}". Route id's must be globally unique within Data Router usages` 368 ), Cg(s)) { 369 let c = { 370 ...s, 371 id: o 372 }; 373 return i[o] = ph( 374 c, 375 e(c) 376 ), c; 377 } else { 378 let c = { 379 ...s, 380 id: o, 381 children: void 0 382 }; 383 return i[o] = ph( 384 c, 385 e(c) 386 ), s.children && (c.children = ra( 387 s.children, 388 e, 389 l, 390 i, 391 r 392 )), c; 393 } 394 }); 395} 396function ph(n, e) { 397 return Object.assign(n, { 398 ...e, 399 ...typeof e.lazy == "object" && e.lazy != null ? { 400 lazy: { 401 ...n.lazy, 402 ...e.lazy 403 } 404 } : {} 405 }); 406} 407function Yi(n, e, t = "/") { 408 return $s(n, e, t, !1); 409} 410function $s(n, e, t, i) { 411 let r = typeof e == "string" ? cr(e) : e, s = Vn(r.pathname || "/", t); 412 if (s == null) 413 return null; 414 let a = Xf(n); 415 Lg(a); 416 let l = null; 417 for (let o = 0; l == null && o < a.length; ++o) { 418 let c = Gg(s); 419 l = zg( 420 a[o], 421 c, 422 i 423 ); 424 } 425 return l; 426} 427function Pg(n, e) { 428 let { route: t, pathname: i, params: r } = n; 429 return { 430 id: t.id, 431 pathname: i, 432 params: r, 433 data: e[t.id], 434 loaderData: e[t.id], 435 handle: t.handle 436 }; 437} 438function Xf(n, e = [], t = [], i = "", r = !1) { 439 let s = (a, l, o = r, c) => { 440 let u = { 441 relativePath: c === void 0 ? a.path || "" : c, 442 caseSensitive: a.caseSensitive === !0, 443 childrenIndex: l, 444 route: a 445 }; 446 if (u.relativePath.startsWith("/")) { 447 if (!u.relativePath.startsWith(i) && o) 448 return; 449 ht( 450 u.relativePath.startsWith(i), 451 `Absolute route path "${u.relativePath}" nested under path "${i}" is not valid. An absolute child route path must start with the combined path of all its parent routes.` 452 ), u.relativePath = u.relativePath.slice(i.length); 453 } 454 let h = hi([i, u.relativePath]), d = t.concat(u); 455 a.children && a.children.length > 0 && (ht( 456 // Our types know better, but runtime JS may not! 457 // @ts-expect-error 458 a.index !== !0, 459 `Index routes must not have child routes. Please remove all child routes from route path "${h}".` 460 ), Xf( 461 a.children, 462 e, 463 d, 464 h, 465 o 466 )), !(a.path == null && !a.index) && e.push({ 467 path: h, 468 score: Fg(h, a.index), 469 routesMeta: d 470 }); 471 }; 472 return n.forEach((a, l) => { 473 if (a.path === "" || !a.path?.includes("?")) 474 s(a, l); 475 else 476 for (let o of qf(a.path)) 477 s(a, l, !0, o); 478 }), e; 479} 480function qf(n) { 481 let e = n.split("/"); 482 if (e.length === 0) return []; 483 let [t, ...i] = e, r = t.endsWith("?"), s = t.replace(/\?$/, ""); 484 if (i.length === 0) 485 return r ? [s, ""] : [s]; 486 let a = qf(i.join("/")), l = []; 487 return l.push( 488 ...a.map( 489 (o) => o === "" ? s : [s, o].join("/") 490 ) 491 ), r && l.push(...a), l.map( 492 (o) => n.startsWith("/") && o === "" ? "/" : o 493 ); 494} 495function Lg(n) { 496 n.sort( 497 (e, t) => e.score !== t.score ? t.score - e.score : Bg( 498 e.routesMeta.map((i) => i.childrenIndex), 499 t.routesMeta.map((i) => i.childrenIndex) 500 ) 501 ); 502} 503var Ng = /^:[\w-]+$/, Ig = 3, Dg = 2, Ug = 1, Og = 10, kg = -2, mh = (n) => n === "*"; 504function Fg(n, e) { 505 let t = n.split("/"), i = t.length; 506 return t.some(mh) && (i += kg), e && (i += Dg), t.filter((r) => !mh(r)).reduce( 507 (r, s) => r + (Ng.test(s) ? Ig : s === "" ? Ug : Og), 508 i 509 ); 510} 511function Bg(n, e) { 512 return n.length === e.length && n.slice(0, -1).every((i, r) => i === e[r]) ? ( 513 // If two routes are siblings, we should try to match the earlier sibling 514 // first. This allows people to have fine-grained control over the matching 515 // behavior by simply putting routes with identical paths in the order they 516 // want them tried. 517 n[n.length - 1] - e[e.length - 1] 518 ) : ( 519 // Otherwise, it doesn't really make sense to rank non-siblings by index, 520 // so they sort equally. 521 0 522 ); 523} 524function zg(n, e, t = !1) { 525 let { routesMeta: i } = n, r = {}, s = "/", a = []; 526 for (let l = 0; l < i.length; ++l) { 527 let o = i[l], c = l === i.length - 1, u = s === "/" ? e : e.slice(s.length) || "/", h = Ao( 528 { path: o.relativePath, caseSensitive: o.caseSensitive, end: c }, 529 u 530 ), d = o.route; 531 if (!h && c && t && !i[i.length - 1].route.index && (h = Ao( 532 { 533 path: o.relativePath, 534 caseSensitive: o.caseSensitive, 535 end: !1 536 }, 537 u 538 )), !h) 539 return null; 540 Object.assign(r, h.params), a.push({ 541 // TODO: Can this as be avoided? 542 params: r, 543 pathname: hi([s, h.pathname]), 544 pathnameBase: $g( 545 hi([s, h.pathnameBase]) 546 ), 547 route: d 548 }), h.pathnameBase !== "/" && (s = hi([s, h.pathnameBase])); 549 } 550 return a; 551} 552function Ao(n, e) { 553 typeof n == "string" && (n = { path: n, caseSensitive: !1, end: !0 }); 554 let [t, i] = Hg( 555 n.path, 556 n.caseSensitive, 557 n.end 558 ), r = e.match(t); 559 if (!r) return null; 560 let s = r[0], a = s.replace(/(.)\/+$/, "$1"), l = r.slice(1); 561 return { 562 params: i.reduce( 563 (c, { paramName: u, isOptional: h }, d) => { 564 if (u === "*") { 565 let p = l[d] || ""; 566 a = s.slice(0, s.length - p.length).replace(/(.)\/+$/, "$1"); 567 } 568 const f = l[d]; 569 return h && !f ? c[u] = void 0 : c[u] = (f || "").replace(/%2F/g, "/"), c; 570 }, 571 {} 572 ), 573 pathname: s, 574 pathnameBase: a, 575 pattern: n 576 }; 577} 578function Hg(n, e = !1, t = !0) { 579 jt( 580 n === "*" || !n.endsWith("*") || n.endsWith("/*"), 581 `Route path "${n}" will be treated as if it were "${n.replace(/\*$/, "/*")}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${n.replace(/\*$/, "/*")}".` 582 ); 583 let i = [], r = "^" + n.replace(/\/*\*?$/, "").replace(/^\/*/, "/").replace(/[\\.*+^${}|()[\]]/g, "\\$&").replace( 584 /\/:([\w-]+)(\?)?/g, 585 (a, l, o) => (i.push({ paramName: l, isOptional: o != null }), o ? "/?([^\\/]+)?" : "/([^\\/]+)") 586 ).replace(/\/([\w-]+)\?(\/|$)/g, "(/$1)?$2"); 587 return n.endsWith("*") ? (i.push({ paramName: "*" }), r += n === "*" || n === "/*" ? "(.*)$" : "(?:\\/(.+)|\\/*)$") : t ? r += "\\/*$" : n !== "" && n !== "/" && (r += "(?:(?=\\/|$))"), [new RegExp(r, e ? void 0 : "i"), i]; 588} 589function Gg(n) { 590 try { 591 return n.split("/").map((e) => decodeURIComponent(e).replace(/\//g, "%2F")).join("/"); 592 } catch (e) { 593 return jt( 594 !1, 595 `The URL path "${n}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${e}).` 596 ), n; 597 } 598} 599function Vn(n, e) { 600 if (e === "/") return n; 601 if (!n.toLowerCase().startsWith(e.toLowerCase())) 602 return null; 603 let t = e.endsWith("/") ? e.length - 1 : e.length, i = n.charAt(t); 604 return i && i !== "/" ? null : n.slice(t) || "/"; 605} 606function Vg({ 607 basename: n, 608 pathname: e 609}) { 610 return e === "/" ? n : hi([n, e]); 611} 612var Yf = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i, _u = (n) => Yf.test(n); 613function Wg(n, e = "/") { 614 let { 615 pathname: t, 616 search: i = "", 617 hash: r = "" 618 } = typeof n == "string" ? cr(n) : n, s; 619 return t ? (t = t.replace(/\/\/+/g, "/"), t.startsWith("/") ? s = gh(t.substring(1), "/") : s = gh(t, e)) : s = e, { 620 pathname: s, 621 search: jg(i), 622 hash: Xg(r) 623 }; 624} 625function gh(n, e) { 626 let t = e.replace(/\/+$/, "").split("/"); 627 return n.split("/").forEach((r) => { 628 r === ".." ? t.length > 1 && t.pop() : r !== "." && t.push(r); 629 }), t.length > 1 ? t.join("/") : "/"; 630} 631function sl(n, e, t, i) { 632 return `Cannot include a '${n}' character in a manually specified \`to.${e}\` field [${JSON.stringify( 633 i 634 )}]. Please separate it out to the \`to.${t}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`; 635} 636function Kf(n) { 637 return n.filter( 638 (e, t) => t === 0 || e.route.path && e.route.path.length > 0 639 ); 640} 641function yu(n) { 642 let e = Kf(n); 643 return e.map( 644 (t, i) => i === e.length - 1 ? t.pathname : t.pathnameBase 645 ); 646} 647function xu(n, e, t, i = !1) { 648 let r; 649 typeof n == "string" ? r = cr(n) : (r = { ...n }, ht( 650 !r.pathname || !r.pathname.includes("?"), 651 sl("?", "pathname", "search", r) 652 ), ht( 653 !r.pathname || !r.pathname.includes("#"), 654 sl("#", "pathname", "hash", r) 655 ), ht( 656 !r.search || !r.search.includes("#"), 657 sl("#", "search", "hash", r) 658 )); 659 let s = n === "" || r.pathname === "", a = s ? "/" : r.pathname, l; 660 if (a == null) 661 l = t; 662 else { 663 let h = e.length - 1; 664 if (!i && a.startsWith("..")) { 665 let d = a.split("/"); 666 for (; d[0] === ".."; ) 667 d.shift(), h -= 1; 668 r.pathname = d.join("/"); 669 } 670 l = h >= 0 ? e[h] : "/"; 671 } 672 let o = Wg(r, l), c = a && a !== "/" && a.endsWith("/"), u = (s || a === ".") && t.endsWith("/"); 673 return !o.pathname.endsWith("/") && (c || u) && (o.pathname += "/"), o; 674}
675var hi = (n) => n.join("/").replace(/\/\/+/g, "/"), $g = (n) => n.replace(/\/+$/, "").replace(/^\/*/, "/"), jg = (n) => !n || n === "?" ? "" : n.startsWith("?") ? n : "?" + n, Xg = (n) => !n || n === "#" ? "" : n.startsWith("#") ? n : "#" + n, va = class { 676 constructor(n, e, t, i = !1) { 677 this.status = n, this.statusText = e || "", this.internal = i, t instanceof Error ? (this.data = t.toString(), this.error = t) : this.data = t; 678 } 679}; 680function sa(n) { 681 return n != null && typeof n.status == "number" && typeof n.statusText == "string" && typeof n.internal == "boolean" && "data" in n; 682} 683function _a(n) { 684 return n.map((e) => e.route.path).filter(Boolean).join("/").replace(/\/\/*/g, "/") || "/"; 685} 686var Jf = typeof window < "u" && typeof window.document < "u" && typeof window.document.createElement < "u"; 687function Zf(n, e) { 688 let t = n; 689 if (typeof t != "string" || !Yf.test(t)) 690 return { 691 absoluteURL: void 0, 692 isExternal: !1, 693 to: t 694 }; 695 let i = t, r = !1; 696 if (Jf) 697 try { 698 let s = new URL(window.location.href), a = t.startsWith("//") ? new URL(s.protocol + t) : new URL(t), l = Vn(a.pathname, e); 699 a.origin === s.origin && l != null ? t = l + a.search + a.hash : r = !0; 700 } catch { 701 jt( 702 !1, 703 `<Link to="${t}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.` 704 ); 705 } 706 return { 707 absoluteURL: i, 708 isExternal: r, 709 to: t 710 }; 711} 712var er = Symbol("Uninstrumented"); 713function qg(n, e) { 714 let t = { 715 lazy: [], 716 "lazy.loader": [], 717 "lazy.action": [], 718 "lazy.middleware": [], 719 middleware: [], 720 loader: [], 721 action: [] 722 }; 723 n.forEach( 724 (r) => r({ 725 id: e.id, 726 index: e.index, 727 path: e.path, 728 instrument(s) { 729 let a = Object.keys(t); 730 for (let l of a) 731 s[l] && t[l].push(s[l]); 732 } 733 }) 734 ); 735 let i = {}; 736 if (typeof e.lazy == "function" && t.lazy.length > 0) { 737 let r = os(t.lazy, e.lazy, () => { 738 }); 739 r && (i.lazy = r); 740 } 741 if (typeof e.lazy == "object") { 742 let r = e.lazy; 743 ["middleware", "loader", "action"].forEach((s) => { 744 let a = r[s], l = t[`lazy.${s}`]; 745 if (typeof a == "function" && l.length > 0) { 746 let o = os(l, a, () => { 747 }); 748 o && (i.lazy = Object.assign(i.lazy || {}, { 749 [s]: o 750 })); 751 } 752 }); 753 } 754 return ["loader", "action"].forEach((r) => { 755 let s = e[r]; 756 if (typeof s == "function" && t[r].length > 0) { 757 let a = s[er] ?? s, l = os( 758 t[r], 759 a, 760 (...o) => vh(o[0]) 761 ); 762 l && (r === "loader" && a.hydrate === !0 && (l.hydrate = !0), l[er] = a, i[r] = l); 763 } 764 }), e.middleware && e.middleware.length > 0 && t.middleware.length > 0 && (i.middleware = e.middleware.map((r) => { 765 let s = r[er] ?? r, a = os( 766 t.middleware, 767 s, 768 (...l) => vh(l[0]) 769 ); 770 return a ? (a[er] = s, a) : r; 771 })), i; 772} 773function Yg(n, e) { 774 let t = { 775 navigate: [], 776 fetch: [] 777 }; 778 if (e.forEach( 779 (i) => i({ 780 instrument(r) { 781 let s = Object.keys(r); 782 for (let a of s) 783 r[a] && t[a].push(r[a]); 784 } 785 }) 786 ), t.navigate.length > 0) { 787 let i = n.navigate[er] ?? n.navigate, r = os( 788 t.navigate, 789 i, 790 (...s) => { 791 let [a, l] = s; 792 return { 793 to: typeof a == "number" || typeof a == "string" ? a : a ? mi(a) : ".", 794 ..._h(n, l ?? {}) 795 }; 796 } 797 ); 798 r && (r[er] = i, n.navigate = r); 799 } 800 if (t.fetch.length > 0) { 801 let i = n.fetch[er] ?? n.fetch, r = os(t.fetch, i, (...s) => { 802 let [a, , l, o] = s; 803 return { 804 href: l ?? ".", 805 fetcherKey: a, 806 ..._h(n, o ?? {}) 807 }; 808 }); 809 r && (r[er] = i, n.fetch = r); 810 } 811 return n; 812} 813function os(n, e, t) { 814 return n.length === 0 ? null : async (...i) => { 815 let r = await Qf( 816 n, 817 t(...i), 818 () => e(...i), 819 n.length - 1 820 ); 821 if (r.type === "error") 822 throw r.value; 823 return r.value; 824 }; 825} 826async function Qf(n, e, t, i) { 827 let r = n[i], s; 828 if (r) { 829 let a, l = async () => (a ? console.error("You cannot call instrumented handlers more than once") : a = Qf(n, e, t, i - 1), s = await a, ht(s, "Expected a result"), s.type === "error" && s.value instanceof Error ? { status: "error", error: s.value } : { status: "success", error: void 0 }); 830 try { 831 await r(l, e); 832 } catch (o) { 833 console.error("An instrumentation function threw an error:", o); 834 } 835 a || await l(), await a; 836 } else 837 try { 838 s = { type: "success", value: await t() }; 839 } catch (a) { 840 s = { type: "error", value: a }; 841 } 842 return s || { 843 type: "error", 844 value: new Error("No result assigned in instrumentation chain.") 845 }; 846} 847function vh(n) { 848 let { request: e, context: t, params: i, unstable_pattern: r } = n; 849 return { 850 request: Kg(e), 851 params: { ...i }, 852 unstable_pattern: r, 853 context: Jg(t) 854 }; 855} 856function _h(n, e) { 857 return { 858 currentUrl: mi(n.state.location), 859 ..."formMethod" in e ? { formMethod: e.formMethod } : {}, 860 ..."formEncType" in e ? { formEncType: e.formEncType } : {}, 861 ..."formData" in e ? { formData: e.formData } : {}, 862 ..."body" in e ? { body: e.body } : {} 863 }; 864} 865function Kg(n) { 866 return { 867 method: n.method, 868 url: n.url, 869 headers: { 870 get: (...e) => n.headers.get(...e) 871 } 872 }; 873} 874function Jg(n) { 875 if (Qg(n)) { 876 let e = { ...n }; 877 return Object.freeze(e), e; 878 } else 879 return { 880 get: (e) => n.get(e) 881 }; 882} 883var Zg = Object.getOwnPropertyNames(Object.prototype).sort().join("\0"); 884function Qg(n) { 885 if (n === null || typeof n != "object") 886 return !1; 887 const e = Object.getPrototypeOf(n);
888 return e === Object.prototype || e === null || Object.getOwnPropertyNames(e).sort().join("\0") === Zg; 889} 890var ep = [ 891 "POST", 892 "PUT", 893 "PATCH", 894 "DELETE" 895], e0 = new Set( 896 ep 897), t0 = [ 898 "GET", 899 ...ep 900], n0 = new Set(t0), tp = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]), i0 = /* @__PURE__ */ new Set([307, 308]), al = { 901 state: "idle", 902 location: void 0, 903 formMethod: void 0, 904 formAction: void 0, 905 formEncType: void 0, 906 formData: void 0, 907 json: void 0, 908 text: void 0 909}, r0 = { 910 state: "idle", 911 data: void 0, 912 formMethod: void 0, 913 formAction: void 0, 914 formEncType: void 0, 915 formData: void 0, 916 json: void 0, 917 text: void 0 918}, Ps = { 919 state: "unblocked", 920 proceed: void 0, 921 reset: void 0, 922 location: void 0 923}, s0 = (n) => ({ 924 hasErrorBoundary: !!n.hasErrorBoundary 925}), np = "remix-router-transitions", ip = Symbol("ResetLoaderData"); 926function a0(n) { 927 const e = n.window ? n.window : typeof window < "u" ? window : void 0, t = typeof e < "u" && typeof e.document < "u" && typeof e.document.createElement < "u"; 928 ht( 929 n.routes.length > 0, 930 "You must provide a non-empty routes array to createRouter" 931 ); 932 let i = n.hydrationRouteProperties || [], r = n.mapRouteProperties || s0, s = r; 933 if (n.unstable_instrumentations) { 934 let N = n.unstable_instrumentations; 935 s = (B) => ({ 936 ...r(B), 937 ...qg( 938 N.map((Y) => Y.route).filter(Boolean), 939 B 940 ) 941 }); 942 } 943 let a = {}, l = ra( 944 n.routes, 945 s, 946 void 0, 947 a 948 ), o, c = n.basename || "/"; 949 c.startsWith("/") || (c = `/${c}`); 950 let u = n.dataStrategy || h0, h = { 951 ...n.future 952 }, d = null, f = /* @__PURE__ */ new Set(), p = null, v = null, m = null, g = n.hydrationData != null, _ = Yi(l, n.history.location, c), x = !1, E = null, R; 953 if (_ == null && !n.patchRoutesOnNavigation) { 954 let N = zn(404, { 955 pathname: n.history.location.pathname 956 }), { matches: B, route: Y } = Ca(l); 957 R = !0, _ = B, E = { [Y.id]: N }; 958 } else if (_ && !n.hydrationData && ce( 959 _, 960 l, 961 n.history.location.pathname 962 ).active && (_ = null), _) 963 if (_.some((N) => N.route.lazy)) 964 R = !1; 965 else if (!_.some((N) => bu(N.route))) 966 R = !0; 967 else { 968 let N = n.hydrationData ? n.hydrationData.loaderData : null, B = n.hydrationData ? n.hydrationData.errors : null; 969 if (B) { 970 let Y = _.findIndex( 971 (de) => B[de.route.id] !== void 0 972 ); 973 R = _.slice(0, Y + 1).every( 974 (de) => !ic(de.route, N, B) 975 ); 976 } else 977 R = _.every( 978 (Y) => !ic(Y.route, N, B) 979 ); 980 } 981 else { 982 R = !1, _ = []; 983 let N = ce( 984 null, 985 l, 986 n.history.location.pathname 987 ); 988 N.active && N.matches && (x = !0, _ = N.matches); 989 } 990 let T, w = { 991 historyAction: n.history.action, 992 location: n.history.location, 993 matches: _, 994 initialized: R, 995 navigation: al, 996 // Don't restore on initial updateState() if we were SSR'd 997 restoreScrollPosition: n.hydrationData != null ? !1 : null, 998 preventScrollReset: !1, 999 revalidation: "idle", 1000 loaderData: n.hydrationData && n.hydrationData.loaderData || {}, 1001 actionData: n.hydrationData && n.hydrationData.actionData || null, 1002 errors: n.hydrationData && n.hydrationData.errors || E, 1003 fetchers: /* @__PURE__ */ new Map(), 1004 blockers: /* @__PURE__ */ new Map() 1005 }, y = "POP", M = null, L = !1, C, U = !1, V = /* @__PURE__ */ new Map(), F = null, I = !1, k = !1, H = /* @__PURE__ */ new Set(), X = /* @__PURE__ */ new Map(), K = 0, ae = -1, se = /* @__PURE__ */ new Map(), he = /* @__PURE__ */ new Set(), Ce = /* @__PURE__ */ new Map(), Ie = /* @__PURE__ */ new Map(), Ee = /* @__PURE__ */ new Set(), J = /* @__PURE__ */ new Map(), le, te = null; 1006 function ie() { 1007 if (d = n.history.listen( 1008 ({ action: N, location: B, delta: Y }) => { 1009 if (le) { 1010 le(), le = void 0; 1011 return; 1012 } 1013 jt( 1014 J.size === 0 || Y != null, 1015 "You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL." 1016 ); 1017 let de = gt({ 1018 currentLocation: w.location, 1019 nextLocation: B, 1020 historyAction: N 1021 }); 1022 if (de && Y != null) { 1023 let we = new Promise((We) => { 1024 le = We; 1025 }); 1026 n.history.go(Y * -1), nt(de, { 1027 state: "blocked", 1028 location: B, 1029 proceed() { 1030 nt(de, { 1031 state: "proceeding", 1032 proceed: void 0, 1033 reset: void 0, 1034 location: B 1035 }), we.then(() => n.history.go(Y)); 1036 }, 1037 reset() { 1038 let We = new Map(w.blockers); 1039 We.set(de, Ps), Fe({ blockers: We }); 1040 } 1041 }), M?.resolve(), M = null; 1042 return; 1043 } 1044 return Ue(N, B); 1045 } 1046 ), t) { 1047 C0(e, V); 1048 let N = () => P0(e, V); 1049 e.addEventListener("pagehide", N), F = () => e.removeEventListener("pagehide", N); 1050 } 1051 return w.initialized || Ue("POP", w.location, { 1052 initialHydration: !0 1053 }), T; 1054 } 1055 function fe() { 1056 d && d(), F && F(), f.clear(), C && C.abort(), w.fetchers.forEac
1056h((N, B) => ve(B)), w.blockers.forEach((N, B) => et(B)); 1057 } 1058 function Se(N) { 1059 return f.add(N), () => f.delete(N); 1060 } 1061 function Fe(N, B = {}) { 1062 N.matches && (N.matches = N.matches.map((we) => { 1063 let We = a[we.route.id], Le = we.route; 1064 return Le.element !== We.element || Le.errorElement !== We.errorElement || Le.hydrateFallbackElement !== We.hydrateFallbackElement ? { 1065 ...we, 1066 route: We 1067 } : we; 1068 })), w = { 1069 ...w, 1070 ...N 1071 }; 1072 let Y = [], de = []; 1073 w.fetchers.forEach((we, We) => { 1074 we.state === "idle" && (Ee.has(We) ? Y.push(We) : de.push(We)); 1075 }), Ee.forEach((we) => { 1076 !w.fetchers.has(we) && !X.has(we) && Y.push(we); 1077 }), [...f].forEach( 1078 (we) => we(w, { 1079 deletedFetchers: Y, 1080 newErrors: N.errors ?? null, 1081 viewTransitionOpts: B.viewTransitionOpts, 1082 flushSync: B.flushSync === !0 1083 }) 1084 ), Y.forEach((we) => ve(we)), de.forEach((we) => w.fetchers.delete(we)); 1085 } 1086 function Me(N, B, { flushSync: Y } = {}) { 1087 let de = w.actionData != null && w.navigation.formMethod != null && dn(w.navigation.formMethod) && w.navigation.state === "loading" && N.state?._isRedirect !== !0, we; 1088 B.actionData ? Object.keys(B.actionData).length > 0 ? we = B.actionData : we = null : de ? we = w.actionData : we = null; 1089 let We = B.loaderData ? Rh( 1090 w.loaderData, 1091 B.loaderData, 1092 B.matches || [], 1093 B.errors 1094 ) : w.loaderData, Le = w.blockers; 1095 Le.size > 0 && (Le = new Map(Le), Le.forEach((Je, qe) => Le.set(qe, Ps))); 1096 let Ve = I ? !1 : be(N, B.matches || w.matches), $e = L === !0 || w.navigation.formMethod != null && dn(w.navigation.formMethod) && N.state?._isRedirect !== !0; 1097 o && (l = o, o = void 0), I || y === "POP" || (y === "PUSH" ? n.history.push(N, N.state) : y === "REPLACE" && n.history.replace(N, N.state)); 1098 let Ye; 1099 if (y === "POP") { 1100 let Je = V.get(w.location.pathname); 1101 Je && Je.has(N.pathname) ? Ye = { 1102 currentLocation: w.location, 1103 nextLocation: N 1104 } : V.has(N.pathname) && (Ye = { 1105 currentLocation: N, 1106 nextLocation: w.location 1107 }); 1108 } else if (U) { 1109 let Je = V.get(w.location.pathname); 1110 Je ? Je.add(N.pathname) : (Je = /* @__PURE__ */ new Set([N.pathname]), V.set(w.location.pathname, Je)), Ye = { 1111 currentLocation: w.location, 1112 nextLocation: N 1113 }; 1114 } 1115 Fe( 1116 { 1117 ...B, 1118 // matches, errors, fetchers go through as-is 1119 actionData: we, 1120 loaderData: We, 1121 historyAction: y, 1122 location: N, 1123 initialized: !0, 1124 navigation: al, 1125 revalidation: "idle", 1126 restoreScrollPosition: Ve, 1127 preventScrollReset: $e, 1128 blockers: Le 1129 }, 1130 { 1131 viewTransitionOpts: Ye, 1132 flushSync: Y === !0 1133 } 1134 ), y = "POP", L = !1, U = !1, I = !1, k = !1, M?.resolve(), M = null, te?.resolve(), te = null; 1135 } 1136 async function Ke(N, B) { 1137 if (M?.resolve(), M = null, typeof N == "number") { 1138 M || (M = Nh()); 1139 let vt = M.promise; 1140 return n.history.go(N), vt; 1141 } 1142 let Y = nc( 1143 w.location, 1144 w.matches, 1145 c, 1146 N, 1147 B?.fromRouteId, 1148 B?.relative 1149 ), { path: de, submission: we, error: We } = yh( 1150 !1, 1151 Y, 1152 B 1153 ), Le = w.location, Ve = ia(w.location, de, B && B.state); 1154 Ve = { 1155 ...Ve, 1156 ...n.history.encodeLocation(Ve) 1157 }; 1158 let $e = B && B.replace != null ? B.replace : void 0, Ye = "PUSH"; 1159 $e === !0 ? Ye = "REPLACE" : $e === !1 || we != null && dn(we.formMethod) && we.formAction === w.location.pathname + w.location.search && (Ye = "REPLACE"); 1160 let Je = B && "preventScrollReset" in B ? B.preventScrollReset === !0 : void 0, qe = (B && B.flushSync) === !0, ft = gt({ 1161 currentLocation: Le, 1162 nextLocation: Ve, 1163 historyAction: Ye 1164 }); 1165 if (ft) { 1166 nt(ft, { 1167 state: "blocked", 1168 location: Ve, 1169 proceed() { 1170 nt(ft, { 1171 state: "proceeding", 1172 proceed: void 0, 1173 reset: void 0, 1174 location: Ve 1175 }), Ke(N, B); 1176 }, 1177 reset() { 1178 let vt = new Map(w.blockers); 1179 vt.set(ft, Ps), Fe({ blockers: vt }); 1180 } 1181 }); 1182 return; 1183 } 1184 await Ue(Ye, Ve, { 1185 submission: we, 1186 // Send through the formData serialization error if we have one so we can 1187 // render at the right error boundary after we match routes 1188 pendingError: We, 1189 preventScrollReset: Je, 1190 replace: B && B.replace, 1191 enableViewTransition: B && B.viewTransition, 1192 flushSync: qe, 1193 callSiteDefaultShouldRevalidate: B && B.unstable_defaultShouldRevalidate 1194 }); 1195 } 1196 function at() { 1197 te || (te = Nh()), b(), Fe({ revalidation: "loading" }); 1198 let N = te.promise; 1199 return w.navigation.state === "submitting" ? N : w.navigation.state === "i
1199dle" ? (Ue(w.historyAction, w.location, { 1200 startUninterruptedRevalidation: !0 1201 }), N) : (Ue( 1202 y || w.historyAction, 1203 w.navigation.location, 1204 { 1205 overrideNavigation: w.navigation, 1206 // Proxy through any rending view transition 1207 enableViewTransition: U === !0 1208 } 1209 ), N); 1210 } 1211 async function Ue(N, B, Y) { 1212 C && C.abort(), C = null, y = N, I = (Y && Y.startUninterruptedRevalidation) === !0, Ne(w.location, w.matches), L = (Y && Y.preventScrollReset) === !0, U = (Y && Y.enableViewTransition) === !0; 1213 let de = o || l, we = Y && Y.overrideNavigation, We = Y?.initialHydration && w.matches && w.matches.length > 0 && !x ? ( 1214 // `matchRoutes()` has already been called if we're in here via `router.initialize()` 1215 w.matches 1216 ) : Yi(de, B, c), Le = (Y && Y.flushSync) === !0; 1217 if (We && w.initialized && !k && y0(w.location, B) && !(Y && Y.submission && dn(Y.submission.formMethod))) { 1218 Me(B, { matches: We }, { flushSync: Le }); 1219 return; 1220 } 1221 let Ve = ce(We, de, B.pathname); 1222 if (Ve.active && Ve.matches && (We = Ve.matches), !We) { 1223 let { error: qt, notFoundMatches: rn, route: Pt } = O( 1224 B.pathname 1225 ); 1226 Me( 1227 B, 1228 { 1229 matches: rn, 1230 loaderData: {}, 1231 errors: { 1232 [Pt.id]: qt 1233 } 1234 }, 1235 { flushSync: Le } 1236 ); 1237 return; 1238 } 1239 C = new AbortController(); 1240 let $e = ns( 1241 n.history, 1242 B, 1243 C.signal, 1244 Y && Y.submission 1245 ), Ye = n.getContext ? await n.getContext() : new fh(), Je; 1246 if (Y && Y.pendingError) 1247 Je = [ 1248 Ki(We).route.id, 1249 { type: "error", error: Y.pendingError } 1250 ]; 1251 else if (Y && Y.submission && dn(Y.submission.formMethod)) { 1252 let qt = await lt( 1253 $e, 1254 B, 1255 Y.submission, 1256 We, 1257 Ye, 1258 Ve.active, 1259 Y && Y.initialHydration === !0, 1260 { replace: Y.replace, flushSync: Le } 1261 ); 1262 if (qt.shortCircuited) 1263 return; 1264 if (qt.pendingActionResult) { 1265 let [rn, Pt] = qt.pendingActionResult; 1266 if (Cn(Pt) && sa(Pt.error) && Pt.error.status === 404) { 1267 C = null, Me(B, { 1268 matches: qt.matches, 1269 loaderData: {}, 1270 errors: { 1271 [rn]: Pt.error 1272 } 1273 }); 1274 return; 1275 } 1276 } 1277 We = qt.matches || We, Je = qt.pendingActionResult, we = ol(B, Y.submission), Le = !1, Ve.active = !1, $e = ns( 1278 n.history, 1279 $e.url, 1280 $e.signal 1281 ); 1282 } 1283 let { 1284 shortCircuited: qe, 1285 matches: ft, 1286 loaderData: vt, 1287 errors: Xt 1288 } = await ut( 1289 $e, 1290 B, 1291 We, 1292 Ye, 1293 Ve.active, 1294 we, 1295 Y && Y.submission, 1296 Y && Y.fetcherSubmission, 1297 Y && Y.replace, 1298 Y && Y.initialHydration === !0, 1299 Le, 1300 Je, 1301 Y && Y.callSiteDefaultShouldRevalidate 1302 ); 1303 qe || (C = null, Me(B, { 1304 matches: ft || We, 1305 ...Ch(Je), 1306 loaderData: vt, 1307 errors: Xt 1308 })); 1309 } 1310 async function lt(N, B, Y, de, we, We, Le, Ve = {}) { 1311 b(); 1312 let $e = A0(B, Y); 1313 if (Fe({ navigation: $e }, { flushSync: Ve.flushSync === !0 }), We) { 1314 let qe = await Ge( 1315 de, 1316 B.pathname, 1317 N.signal 1318 ); 1319 if (qe.type === "aborted") 1320 return { shortCircuited: !0 }; 1321 if (qe.type === "error") { 1322 if (qe.partialMatches.length === 0) { 1323 let { matches: vt, route: Xt } = Ca(l); 1324 return { 1325 matches: vt, 1326 pendingActionResult: [ 1327 Xt.id, 1328 { 1329 type: "error", 1330 error: qe.error 1331 } 1332 ] 1333 }; 1334 } 1335 let ft = Ki(qe.partialMatches).route.id; 1336 return { 1337 matches: qe.partialMatches, 1338 pendingActionResult: [ 1339 ft, 1340 { 1341 type: "error", 1342 error: qe.error 1343 } 1344 ] 1345 }; 1346 } else if (qe.matches) 1347 de = qe.matches; 1348 else { 1349 let { notFoundMatches: ft, error: vt, route: Xt } = O( 1350 B.pathname 1351 ); 1352 return { 1353 matches: ft, 1354 pendingActionResult: [ 1355 Xt.id, 1356 { 1357 type: "error", 1358 error: vt 1359 } 1360 ] 1361 }; 1362 } 1363 } 1364 let Ye, Je = mo(de, B); 1365 if (!Je.route.action && !Je.route.lazy) 1366 Ye = { 1367 type: "error", 1368 error: zn(405, { 1369 method: N.method, 1370 pathname: B.pathname, 1371 routeId: Je.route.id 1372 }) 1373 }; 1374 else { 1375 let qe = us( 1376 s, 1377 a, 1378 N, 1379 de, 1380 Je, 1381 Le ? [] : i, 1382 we 1383 ), ft = await At( 1384 N, 1385 qe, 1386 we, 1387 null 1388 ); 1389 if (Ye = ft[Je.route.id], !Ye) { 1390 for (let vt of de) 1391 if (ft[vt.route.id]) { 1392 Ye = ft[vt.route.id]; 1393 break; 1394 } 1395 } 1396 if (N.signal.aborted) 1397 return { shortCircuited: !0 }; 1398 } 1399 if (Er(Ye)) { 1400 let qe; 1401 return Ve && Ve.replace != null ? qe = Ve.replace : qe = Mh( 1402 Ye.response.headers.get("Location"), 1403 new URL(N.url), 1404 c, 1405 n.history 1406 ) === w.location.pathname + w.location.search, await pe(N, Ye, !0, { 1407 submission: Y, 1408 replace: qe 1409 }), { shortCircuited: !0 }; 1410 } 1411 if (Cn(Ye)) { 1412 let qe = Ki(de, Je.route.id); 1413 return (Ve && Ve.replace) !== !0 && (y = "PUSH"), { 1414 matches: de, 1415 pendingActionResult: [ 1416 qe.route.id, 1417 Ye, 1418 Je.route.id 1419 ] 1420 }; 1421 } 1422 return { 1423 matches: de, 1424 pendingActionResult: [Je.route.id, Ye] 1425 }; 1426 } 1427 async function ut(N, B, Y, de, we, We, Le, Ve, $e, Ye, Je, qe, ft) {
1428 let vt = We || ol(B, Le), Xt = Le || Ve || Lh(vt), qt = !I && !Ye; 1429 if (we) { 1430 if (qt) { 1431 let ge = Tt(qe); 1432 Fe( 1433 { 1434 navigation: vt, 1435 ...ge !== void 0 ? { actionData: ge } : {} 1436 }, 1437 { 1438 flushSync: Je 1439 } 1440 ); 1441 } 1442 let ue = await Ge( 1443 Y, 1444 B.pathname, 1445 N.signal 1446 ); 1447 if (ue.type === "aborted") 1448 return { shortCircuited: !0 }; 1449 if (ue.type === "error") { 1450 if (ue.partialMatches.length === 0) { 1451 let { matches: Oe, route: Be } = Ca(l); 1452 return { 1453 matches: Oe, 1454 loaderData: {}, 1455 errors: { 1456 [Be.id]: ue.error 1457 } 1458 }; 1459 } 1460 let ge = Ki(ue.partialMatches).route.id; 1461 return { 1462 matches: ue.partialMatches, 1463 loaderData: {}, 1464 errors: { 1465 [ge]: ue.error 1466 } 1467 }; 1468 } else if (ue.matches) 1469 Y = ue.matches; 1470 else { 1471 let { error: ge, notFoundMatches: Oe, route: Be } = O( 1472 B.pathname 1473 ); 1474 return { 1475 matches: Oe, 1476 loaderData: {}, 1477 errors: { 1478 [Be.id]: ge 1479 } 1480 }; 1481 } 1482 } 1483 let rn = o || l, { dsMatches: Pt, revalidatingFetchers: bn } = xh( 1484 N, 1485 de, 1486 s, 1487 a, 1488 n.history, 1489 w, 1490 Y, 1491 Xt, 1492 B, 1493 Ye ? [] : i, 1494 Ye === !0, 1495 k, 1496 H, 1497 Ee, 1498 Ce, 1499 he, 1500 rn, 1501 c, 1502 n.patchRoutesOnNavigation != null, 1503 qe, 1504 ft 1505 ); 1506 if (ae = ++K, !n.dataStrategy && !Pt.some((ue) => ue.shouldLoad) && !Pt.some( 1507 (ue) => ue.route.middleware && ue.route.middleware.length > 0 1508 ) && bn.length === 0) { 1509 let ue = De(); 1510 return Me( 1511 B, 1512 { 1513 matches: Y, 1514 loaderData: {}, 1515 // Commit pending error if we're short circuiting 1516 errors: qe && Cn(qe[1]) ? { [qe[0]]: qe[1].error } : null, 1517 ...Ch(qe), 1518 ...ue ? { fetchers: new Map(w.fetchers) } : {} 1519 }, 1520 { flushSync: Je } 1521 ), { shortCircuited: !0 }; 1522 } 1523 if (qt) { 1524 let ue = {}; 1525 if (!we) { 1526 ue.navigation = vt; 1527 let ge = Tt(qe); 1528 ge !== void 0 && (ue.actionData = ge); 1529 } 1530 bn.length > 0 && (ue.fetchers = D(bn)), Fe(ue, { flushSync: Je }); 1531 } 1532 bn.forEach((ue) => { 1533 ee(ue.key), ue.controller && X.set(ue.key, ue.controller); 1534 }); 1535 let bi = () => bn.forEach((ue) => ee(ue.key)); 1536 C && C.signal.addEventListener( 1537 "abort", 1538 bi 1539 ); 1540 let { loaderResults: dr, fetcherResults: ii } = await A( 1541 Pt, 1542 bn, 1543 N, 1544 de 1545 ); 1546 if (N.signal.aborted) 1547 return { shortCircuited: !0 }; 1548 C && C.signal.removeEventListener( 1549 "abort", 1550 bi 1551 ), bn.forEach((ue) => X.delete(ue.key)); 1552 let S = Pa(dr); 1553 if (S) 1554 return await pe(N, S.result, !0, { 1555 replace: $e 1556 }), { shortCircuited: !0 }; 1557 if (S = Pa(ii), S) 1558 return he.add(S.key), await pe(N, S.result, !0, { 1559 replace: $e 1560 }), { shortCircuited: !0 }; 1561 let { loaderData: z, errors: q } = Ah( 1562 w, 1563 Y, 1564 dr, 1565 qe, 1566 bn, 1567 ii 1568 ); 1569 Ye && w.errors && (q = { ...w.errors, ...q }); 1570 let $ = De(), j = xe(ae), Te = $ || j || bn.length > 0; 1571 return { 1572 matches: Y, 1573 loaderData: z, 1574 errors: q, 1575 ...Te ? { fetchers: new Map(w.fetchers) } : {} 1576 }; 1577 } 1578 function Tt(N) { 1579 if (N && !Cn(N[1])) 1580 return { 1581 [N[0]]: N[1].data 1582 }; 1583 if (w.actionData) 1584 return Object.keys(w.actionData).length === 0 ? null : w.actionData; 1585 } 1586 function D(N) { 1587 return N.forEach((B) => { 1588 let Y = w.fetchers.get(B.key), de = Ls( 1589 void 0, 1590 Y ? Y.data : void 0 1591 ); 1592 w.fetchers.set(B.key, de); 1593 }), new Map(w.fetchers); 1594 } 1595 async function Rt(N, B, Y, de) { 1596 ee(N); 1597 let we = (de && de.flushSync) === !0, We = o || l, Le = nc( 1598 w.location, 1599 w.matches, 1600 c, 1601 Y, 1602 B, 1603 de?.relative 1604 ), Ve = Yi(We, Le, c), $e = ce(Ve, We, Le); 1605 if ($e.active && $e.matches && (Ve = $e.matches), !Ve) { 1606 Q( 1607 N, 1608 B, 1609 zn(404, { pathname: Le }), 1610 { flushSync: we } 1611 ); 1612 return; 1613 } 1614 let { path: Ye, submission: Je, error: qe } = yh( 1615 !0, 1616 Le, 1617 de 1618 ); 1619 if (qe) { 1620 Q(N, B, qe, { flushSync: we }); 1621 return; 1622 } 1623 let ft = n.getContext ? await n.getContext() : new fh(), vt = (de && de.preventScrollReset) === !0; 1624 if (Je && dn(Je.formMethod)) { 1625 await Qe( 1626 N, 1627 B, 1628 Ye, 1629 Ve, 1630 ft, 1631 $e.active, 1632 we, 1633 vt, 1634 Je, 1635 de && de.unstable_defaultShouldRevalidate 1636 ); 1637 return; 1638 } 1639 Ce.set(N, { routeId: B, path: Ye }), await dt( 1640 N, 1641 B, 1642 Ye, 1643 Ve, 1644 ft, 1645 $e.active, 1646 we, 1647 vt, 1648 Je 1649 ); 1650 } 1651 async function Qe(N, B, Y, de, we, We, Le, Ve, $e, Ye) { 1652 b(), Ce.delete(N); 1653 let Je = w.fetchers.get(N); 1654 G(N, R0($e, Je), { 1655 flushSync: Le 1656 }); 1657 let qe = new AbortController(), ft = ns( 1658 n.history, 1659 Y, 1660 qe.signal, 1661 $e 1662 ); 1663 if (We) { 1664 let ze = await Ge( 1665 de, 1666 new URL(ft.url).pathname, 1667 ft.signal, 1668 N 1669 ); 1670 if (ze.type === "aborted") 1671 return; 1672 if (ze.type === "error") { 1673 Q(N, B, ze.error, { flushSync: Le }); 1674 return; 1675 } else if (ze.matches) 1676 de = ze.matches; 1677 else { 1678 Q( 1679 N, 1680 B, 1681 zn(404, { pathname: Y }), 1682 { flushSync: Le } 1683 ); 1684 return; 1685 } 1686 } 1687 let vt = mo(de, Y); 1688 if (!vt.route.action && !vt.route.lazy) { 1689 let ze = zn(405, { 1690 method: $e.formMethod, 1691 pathname: Y, 1692 routeId: B 1693 }); 1694 Q(N, B, ze, { flushSync: Le }); 1695 return; 1696 } 1697 X.set(N, qe); 1698 let Xt = K, qt = us( 1699 s, 1700 a, 1701 ft, 1702 de, 1703 vt, 1704 i, 1705 we 1706 ), rn = await At( 1707 ft, 1708 qt, 1709 we, 1710 N 1711 ), Pt = rn[vt.route.id]; 1712 if (!Pt) { 1713 for (let ze of qt) 1714 if (rn[ze.route.id]) { 1715 Pt = rn[ze.route.id]; 1716 break; 1717 } 1718 } 1719 if (ft.signal.aborted) { 1720 X.get(N) === qe && X.delete(N); 1721 return; 1722 } 1723 if (Ee.has(N)) { 1724 if (Er(Pt) || Cn(Pt)) { 1725 G(N, Ci(void 0)); 1726 return; 1727 } 1728 } else { 1729 if (Er(Pt)) 1730 if (X.delete(N), ae > Xt) { 1731 G(N, Ci(void 0)); 1732 return; 1733 } else 1734 return he.add(N), G(N, Ls($e)), pe(ft, Pt, !1, { 1735 fetcherSubmission: $e, 1736 preventScrollReset: Ve 1737 }); 1738 if (Cn(Pt)) { 1739 Q(N, B, Pt.error); 1740 return; 1741 } 1742 } 1743 let bn = w.navigation.location || w.location, bi = ns( 1744 n.history, 1745 bn, 1746 qe.signal 1747 ), dr = o || l, ii = w.navigation.state !== "idle" ? Yi(dr, w.navigation.location, c) : w.matches; 1748 ht(ii, "Didn't find any matches after fetcher action"); 1749 let S = ++K; 1750 se.set(N, S); 1751 let z = Ls($e, Pt.data); 1752 w.fetchers.set(N, z); 1753 let { dsMatches: q, revalidatingFetchers: $ } = xh( 1754 bi, 1755 we, 1756 s, 1757 a, 1758 n.history, 1759 w, 1760 ii, 1761 $e, 1762 bn, 1763 i, 1764 !1, 1765 k, 1766 H, 1767 Ee, 1768 Ce, 1769 he, 1770 dr, 1771 c, 1772 n.patchRoutesOnNavigation != null, 1773 [vt.route.id, Pt], 1774 Ye 1775 ); 1776 $.filter((ze) =>
1776 ze.key !== N).forEach((ze) => { 1777 let rt = ze.key, je = w.fetchers.get(rt), Lt = Ls( 1778 void 0, 1779 je ? je.data : void 0 1780 ); 1781 w.fetchers.set(rt, Lt), ee(rt), ze.controller && X.set(rt, ze.controller); 1782 }), Fe({ fetchers: new Map(w.fetchers) }); 1783 let j = () => $.forEach((ze) => ee(ze.key)); 1784 qe.signal.addEventListener( 1785 "abort", 1786 j 1787 ); 1788 let { loaderResults: Te, fetcherResults: ue } = await A( 1789 q, 1790 $, 1791 bi, 1792 we 1793 ); 1794 if (qe.signal.aborted) 1795 return; 1796 if (qe.signal.removeEventListener( 1797 "abort", 1798 j 1799 ), se.delete(N), X.delete(N), $.forEach((ze) => X.delete(ze.key)), w.fetchers.has(N)) { 1800 let ze = Ci(Pt.data); 1801 w.fetchers.set(N, ze); 1802 } 1803 let ge = Pa(Te); 1804 if (ge) 1805 return pe( 1806 bi, 1807 ge.result, 1808 !1, 1809 { preventScrollReset: Ve } 1810 ); 1811 if (ge = Pa(ue), ge) 1812 return he.add(ge.key), pe( 1813 bi, 1814 ge.result, 1815 !1, 1816 { preventScrollReset: Ve } 1817 ); 1818 let { loaderData: Oe, errors: Be } = Ah( 1819 w, 1820 ii, 1821 Te, 1822 void 0, 1823 $, 1824 ue 1825 ); 1826 xe(S), w.navigation.state === "loading" && S > ae ? (ht(y, "Expected pending action"), C && C.abort(), Me(w.navigation.location, { 1827 matches: ii, 1828 loaderData: Oe, 1829 errors: Be, 1830 fetchers: new Map(w.fetchers) 1831 })) : (Fe({ 1832 errors: Be, 1833 loaderData: Rh( 1834 w.loaderData, 1835 Oe, 1836 ii, 1837 Be 1838 ), 1839 fetchers: new Map(w.fetchers) 1840 }), k = !1); 1841 } 1842 async function dt(N, B, Y, de, we, We, Le, Ve, $e) { 1843 let Ye = w.fetchers.get(N); 1844 G( 1845 N, 1846 Ls( 1847 $e, 1848 Ye ? Ye.data : void 0 1849 ), 1850 { flushSync: Le } 1851 ); 1852 let Je = new AbortController(), qe = ns( 1853 n.history, 1854 Y, 1855 Je.signal 1856 ); 1857 if (We) { 1858 let Pt = await Ge( 1859 de, 1860 new URL(qe.url).pathname, 1861 qe.signal, 1862 N 1863 ); 1864 if (Pt.type === "aborted") 1865 return; 1866 if (Pt.type === "error") { 1867 Q(N, B, Pt.error, { flushSync: Le }); 1868 return; 1869 } else if (Pt.matches) 1870 de = Pt.matches; 1871 else { 1872 Q( 1873 N, 1874 B, 1875 zn(404, { pathname: Y }), 1876 { flushSync: Le } 1877 ); 1878 return; 1879 } 1880 } 1881 let ft = mo(de, Y); 1882 X.set(N, Je); 1883 let vt = K, Xt = us( 1884 s, 1885 a, 1886 qe, 1887 de, 1888 ft, 1889 i, 1890 we 1891 ), rn = (await At( 1892 qe, 1893 Xt, 1894 we, 1895 N 1896 ))[ft.route.id]; 1897 if (X.get(N) === Je && X.delete(N), !qe.signal.aborted) { 1898 if (Ee.has(N)) { 1899 G(N, Ci(void 0)); 1900 return; 1901 } 1902 if (Er(rn)) 1903 if (ae > vt) { 1904 G(N, Ci(void 0)); 1905 return; 1906 } else { 1907 he.add(N), await pe(qe, rn, !1, { 1908 preventScrollReset: Ve 1909 }); 1910 return; 1911 } 1912 if (Cn(rn)) { 1913 Q(N, B, rn.error); 1914 return; 1915 } 1916 G(N, Ci(rn.data)); 1917 } 1918 } 1919 async function pe(N, B, Y, { 1920 submission: de, 1921 fetcherSubmission: we, 1922 preventScrollReset: We, 1923 replace: Le 1924 } = {}) { 1925 Y || (M?.resolve(), M = null), B.response.headers.has("X-Remix-Revalidate") && (k = !0); 1926 let Ve = B.response.headers.get("Location"); 1927 ht(Ve, "Expected a Location header on the redirect Response"), Ve = Mh( 1928 Ve, 1929 new URL(N.url), 1930 c, 1931 n.history 1932 ); 1933 let $e = ia(w.location, Ve, { 1934 _isRedirect: !0 1935 }); 1936 if (t) { 1937 let Xt = !1; 1938 if (B.response.headers.has("X-Remix-Reload-Document")) 1939 Xt = !0; 1940 else if (_u(Ve)) { 1941 const qt = jf(Ve, !0); 1942 Xt = // Hard reload if it's an absolute URL to a new origin 1943 qt.origin !== e.location.origin || // Hard reload if it's an absolute URL that does not match our basename 1944 Vn(qt.pathname, c) == null; 1945 } 1946 if (Xt) { 1947 Le ? e.location.replace(Ve) : e.location.assign(Ve); 1948 return; 1949 } 1950 } 1951 C = null; 1952 let Ye = Le === !0 || B.response.headers.has("X-Remix-Replace") ? "REPLACE" : "PUSH", { formMethod: Je, formAction: qe, formEncType: ft } = w.navigation; 1953 !de && !we && Je && qe && ft && (de = Lh(w.navigation)); 1954 let vt = de || we; 1955 if (i0.has(B.response.status) && vt && dn(vt.formMethod)) 1956 await Ue(Ye, $e, { 1957 submission: { 1958 ...vt, 1959 formAction: Ve 1960 }, 1961 // Preserve these flags across redirects 1962 preventScrollReset: We || L, 1963 enableViewTransition: Y ? U : void 0 1964 }); 1965 else { 1966 let Xt = ol( 1967 $e, 1968 de 1969 ); 1970 await Ue(Ye, $e, { 1971 overrideNavigation: Xt, 1972 // Send fetcher submissions through for shouldRevalidate 1973 fetcherSubmission: we, 1974 // Preserve these flags across redirects 1975 preventScrollReset: We || L, 1976 enableViewTransition: Y ? U : void 0 1977 }); 1978 } 1979 } 1980 async function At(N, B, Y, de) { 1981 let we, We = {}; 1982 try { 1983 we = await f0( 1984 u, 1985 N, 1986 B, 1987 de, 1988 Y, 1989 !1 1990 ); 1991 } catch (Le) { 1992 return B.filter((Ve) =>
1992 Ve.shouldLoad).forEach((Ve) => { 1993 We[Ve.route.id] = { 1994 type: "error", 1995 error: Le 1996 }; 1997 }), We; 1998 } 1999 if (N.signal.aborted) 2000 return We; 2001 if (!dn(N.method)) 2002 for (let Le of B) { 2003 if (we[Le.route.id]?.type === "error") 2004 break; 2005 !we.hasOwnProperty(Le.route.id) && !w.loaderData.hasOwnProperty(Le.route.id) && (!w.errors || !w.errors.hasOwnProperty(Le.route.id)) && Le.shouldCallHandler() && (we[Le.route.id] = { 2006 type: "error", 2007 result: new Error( 2008 `No result returned from dataStrategy for route ${Le.route.id}` 2009 ) 2010 }); 2011 } 2012 for (let [Le, Ve] of Object.entries(we)) 2013 if (S0(Ve)) { 2014 let $e = Ve.result; 2015 We[Le] = { 2016 type: "redirect", 2017 response: v0( 2018 $e, 2019 N, 2020 Le, 2021 B, 2022 c 2023 ) 2024 }; 2025 } else 2026 We[Le] = await g0(Ve); 2027 return We; 2028 } 2029 async function A(N, B, Y, de) { 2030 let we = At( 2031 Y, 2032 N, 2033 de, 2034 null 2035 ), We = Promise.all( 2036 B.map(async ($e) => { 2037 if ($e.matches && $e.match && $e.request && $e.controller) { 2038 let Je = (await At( 2039 $e.request, 2040 $e.matches, 2041 de, 2042 $e.key 2043 ))[$e.match.route.id]; 2044 return { [$e.key]: Je }; 2045 } else 2046 return Promise.resolve({ 2047 [$e.key]: { 2048 type: "error", 2049 error: zn(404, { 2050 pathname: $e.path 2051 }) 2052 } 2053 }); 2054 }) 2055 ), Le = await we, Ve = (await We).reduce( 2056 ($e, Ye) => Object.assign($e, Ye), 2057 {} 2058 ); 2059 return { 2060 loaderResults: Le, 2061 fetcherResults: Ve 2062 }; 2063 } 2064 function b() { 2065 k = !0, Ce.forEach((N, B) => { 2066 X.has(B) && H.add(B), ee(B); 2067 }); 2068 } 2069 function G(N, B, Y = {}) { 2070 w.fetchers.set(N, B), Fe( 2071 { fetchers: new Map(w.fetchers) }, 2072 { flushSync: (Y && Y.flushSync) === !0 } 2073 ); 2074 } 2075 function Q(N, B, Y, de = {}) { 2076 let we = Ki(w.matches, B); 2077 ve(N), Fe( 2078 { 2079 errors: { 2080 [we.route.id]: Y 2081 }, 2082 fetchers: new Map(w.fetchers) 2083 }, 2084 { flushSync: (de && de.flushSync) === !0 } 2085 ); 2086 } 2087 function oe(N) { 2088 return Ie.set(N, (Ie.get(N) || 0) + 1), Ee.has(N) && Ee.delete(N), w.fetchers.get(N) || r0; 2089 } 2090 function me(N, B) { 2091 ee(N, B?.reason), G(N, Ci(null)); 2092 } 2093 function ve(N) { 2094 let B = w.fetchers.get(N); 2095 X.has(N) && !(B && B.state === "loading" && se.has(N)) && ee(N), Ce.delete(N), se.delete(N), he.delete(N), Ee.delete(N), H.delete(N), w.fetchers.delete(N); 2096 } 2097 function Z(N) { 2098 let B = (Ie.get(N) || 0) - 1; 2099 B <= 0 ? (Ie.delete(N), Ee.add(N)) : Ie.set(N, B), Fe({ fetchers: new Map(w.fetchers) }); 2100 } 2101 function ee(N, B) { 2102 let Y = X.get(N); 2103 Y && (Y.abort(B), X.delete(N)); 2104 } 2105 function Ae(N) { 2106 for (let B of N) { 2107 let Y = oe(B), de = Ci(Y.data); 2108 w.fetchers.set(B, de); 2109 } 2110 } 2111 function De() { 2112 let N = [], B = !1; 2113 for (let Y of he) { 2114 let de = w.fetchers.get(Y); 2115 ht(de, `Expected fetcher: ${Y}`), de.state === "loading" && (he.delete(Y), N.push(Y), B = !0); 2116 } 2117 return Ae(N), B; 2118 } 2119 function xe(N) { 2120 let B = []; 2121 for (let [Y, de] of se) 2122 if (de < N) { 2123 let we = w.fetchers.get(Y); 2124 ht(we, `Expected fetcher: ${Y}`), we.state === "loading" && (ee(Y), se.delete(Y), B.push(Y)); 2125 } 2126 return Ae(B), B.length > 0; 2127 } 2128 function _e(N, B) { 2129 let Y = w.blockers.get(N) || Ps; 2130 return J.get(N) !== B && J.set(N, B), Y; 2131 } 2132 function et(N) { 2133 w.blockers.delete(N), J.delete(N); 2134 } 2135 function nt(N, B) { 2136 let Y = w.blockers.get(N) || Ps; 2137 ht( 2138 Y.state === "unblocked" && B.state === "blocked" || Y.state === "blocked" && B.state === "blocked" || Y.state === "blocked" && B.state === "proceeding" || Y.state === "blocked" && B.state === "unblocked" || Y.state === "proceeding" && B.state === "unblocked", 2139 `Invalid blocker state transition: ${Y.state} -> ${B.state}` 2140 ); 2141 let de = new Map(w.blockers); 2142 de.set(N, B), Fe({ blockers: de }); 2143 } 2144 function gt({ 2145 currentLocation: N, 2146 nextLocation: B, 2147 historyAction: Y 2148 }) { 2149 if (J.size === 0) 2150 return; 2151 J.size > 1 && jt(!1, "A router only supports one blocker at a time"); 2152 let de = Array.from(J.entries()), [we, We] = de[de.length - 1], Le = w.blockers.get(we); 2153 if (!(Le && Le.state === "proceeding") && We({ currentLocation: N, nextLocation: B, historyAction: Y })) 2154 return we; 2155 } 2156 function O(N) { 2157 let B = zn(404, { pathname: N }), Y = o || l, { matches: de, route: we } = Ca(Y); 2158 return { notFoundMatches: de, route: we, error: B }; 2159 } 2160 function ye(N, B, Y) { 2161 if (p = N, m = B, v = Y || null, !g && w.navigation === al) { 2162 g = !0; 2163 let de = be(w.location, w.matches); 2164 de != null && Fe({ restoreScrollPosition: de }); 2165 } 2166 return () => { 2167 p = null, m = null, v = null; 2168 }; 2169 } 2170 function ne(N, B) { 2171 return v && v( 2172 N, 2173 B.map((de) => Pg(de, w.loaderData)) 2174 ) || N.key; 2175 } 2176 function Ne(N, B) { 2177 if (p && m) { 2178 let Y = ne(N, B); 2179 p[Y] = m(); 2180 } 2181 } 2182 function be(N, B) { 2183 if (p) { 2184 let Y = ne(N, B), de = p[Y]; 2185 if (typeof de == "number") 2186 return de; 2187 } 2188 return null; 2189 } 2190 function ce(N, B, Y) { 2191 if (n.patchRoutesOnNavigation) 2192 if (N) { 2193 if (Object.keys(N[0].params).length > 0) 2194 return { active: !0, matches: $s( 2195 B, 2196 Y, 2197 c, 2198 !0 2199 ) }; 2200 } else 2201 return { active: !0, matches: $s( 2202 B, 2203 Y, 2204 c, 2205 !0 2206 ) || [] }; 2207 return { active: !1, matches: null }; 2208 } 2209 async function Ge(N, B, Y, de) { 2210 if (!n.patchRoutesOnNavigation) 2211 return { type: "success", matches: N }; 2212 let we = N; 2213 for (; ; ) { 2214 let We = o == null, Le = o || l, Ve = a;
2215 try { 2216 await n.patchRoutesOnNavigation({ 2217 signal: Y, 2218 path: B, 2219 matches: we, 2220 fetcherKey: de, 2221 patch: (Je, qe) => { 2222 Y.aborted || bh( 2223 Je, 2224 qe, 2225 Le, 2226 Ve, 2227 s, 2228 !1 2229 ); 2230 } 2231 }); 2232 } catch (Je) { 2233 return { type: "error", error: Je, partialMatches: we }; 2234 } finally { 2235 We && !Y.aborted && (l = [...l]); 2236 } 2237 if (Y.aborted) 2238 return { type: "aborted" }; 2239 let $e = Yi(Le, B, c), Ye = null; 2240 if ($e) { 2241 if (Object.keys($e[0].params).length === 0) 2242 return { type: "success", matches: $e }; 2243 if (Ye = $s( 2244 Le, 2245 B, 2246 c, 2247 !0 2248 ), !(Ye && we.length < Ye.length && it( 2249 we, 2250 Ye.slice(0, we.length) 2251 ))) 2252 return { type: "success", matches: $e }; 2253 } 2254 if (Ye || (Ye = $s( 2255 Le, 2256 B, 2257 c, 2258 !0 2259 )), !Ye || it(we, Ye)) 2260 return { type: "success", matches: null }; 2261 we = Ye; 2262 } 2263 } 2264 function it(N, B) { 2265 return N.length === B.length && N.every((Y, de) => Y.route.id === B[de].route.id); 2266 } 2267 function Ft(N) { 2268 a = {}, o = ra( 2269 N, 2270 s, 2271 void 0, 2272 a 2273 ); 2274 } 2275 function Ct(N, B, Y = !1) { 2276 let de = o == null; 2277 bh( 2278 N, 2279 B, 2280 o || l, 2281 a, 2282 s, 2283 Y 2284 ), de && (l = [...l], Fe({})); 2285 } 2286 return T = { 2287 get basename() { 2288 return c; 2289 }, 2290 get future() { 2291 return h; 2292 }, 2293 get state() { 2294 return w; 2295 }, 2296 get routes() { 2297 return l; 2298 }, 2299 get window() { 2300 return e; 2301 }, 2302 initialize: ie, 2303 subscribe: Se, 2304 enableScrollRestoration: ye, 2305 navigate: Ke, 2306 fetch: Rt, 2307 revalidate: at, 2308 // Passthrough to history-aware createHref used by useHref so we get proper 2309 // hash-aware URLs in DOM paths 2310 createHref: (N) => n.history.createHref(N), 2311 encodeLocation: (N) => n.history.encodeLocation(N), 2312 getFetcher: oe, 2313 resetFetcher: me, 2314 deleteFetcher: Z, 2315 dispose: fe, 2316 getBlocker: _e, 2317 deleteBlocker: et, 2318 patchRoutes: Ct, 2319 _internalFetchControllers: X, 2320 // TODO: Remove setRoutes, it's temporary to avoid dealing with 2321 // updating the tree while validating the update algorithm. 2322 _internalSetRoutes: Ft, 2323 _internalSetStateDoNotUseOrYouWillBreakYourApp(N) { 2324 Fe(N); 2325 } 2326 }, n.unstable_instrumentations && (T = Yg( 2327 T, 2328 n.unstable_instrumentations.map((N) => N.router).filter(Boolean) 2329 )), T; 2330} 2331function o0(n) { 2332 return n != null && ("formData" in n && n.formData != null || "body" in n && n.body !== void 0); 2333} 2334function nc(n, e, t, i, r, s) { 2335 let a, l; 2336 if (r) { 2337 a = []; 2338 for (let c of e) 2339 if (a.push(c), c.route.id === r) { 2340 l = c; 2341 break; 2342 } 2343 } else 2344 a = e, l = e[e.length - 1]; 2345 let o = xu( 2346 i || ".", 2347 yu(a), 2348 Vn(n.pathname, t) || n.pathname, 2349 s === "path" 2350 ); 2351 if (i == null && (o.search = n.search, o.hash = n.hash), (i == null || i === "" || i === ".") && l) { 2352 let c = Su(o.search); 2353 if (l.route.index && !c) 2354 o.search = o.search ? o.search.replace(/^\?/, "?index&") : "?index"; 2355 else if (!l.route.index && c) { 2356 let u = new URLSearchParams(o.search), h = u.getAll("index"); 2357 u.delete("index"), h.filter((f) => f).forEach((f) => u.append("index", f)); 2358 let d = u.toString(); 2359 o.search = d ? `?${d}` : ""; 2360 } 2361 } 2362 return t !== "/" && (o.pathname = Vg({ basename: t, pathname: o.pathname })), mi(o); 2363} 2364function yh(n, e, t) { 2365 if (!t || !o0(t)) 2366 return { path: e }; 2367 if (t.formMethod && !T0(t.formMethod)) 2368 return { 2369 path: e, 2370 error: zn(405, { method: t.formMethod }) 2371 }; 2372 let i = () => ({ 2373 path: e, 2374 error: zn(400, { type: "invalid-body" }) 2375 }), s = (t.formMethod || "get").toUpperCase(), a = cp(e); 2376 if (t.body !== void 0) { 2377 if (t.formEncType === "text/plain") { 2378 if (!dn(s)) 2379 return i(); 2380 let h = typeof t.body == "string" ? t.body : t.body instanceof FormData || t.body instanceof URLSearchParams ? ( 2381 // https://html.spec.whatwg.org/multipage/form-control-infrastru
2381cture.html#plain-text-form-data 2382 Array.from(t.body.entries()).reduce( 2383 (d, [f, p]) => `${d}${f}=${p} 2384`, 2385 "" 2386 ) 2387 ) : String(t.body); 2388 return { 2389 path: e, 2390 submission: { 2391 formMethod: s, 2392 formAction: a, 2393 formEncType: t.formEncType, 2394 formData: void 0, 2395 json: void 0, 2396 text: h 2397 } 2398 }; 2399 } else if (t.formEncType === "application/json") { 2400 if (!dn(s)) 2401 return i(); 2402 try { 2403 let h = typeof t.body == "string" ? JSON.parse(t.body) : t.body; 2404 return { 2405 path: e, 2406 submission: { 2407 formMethod: s, 2408 formAction: a, 2409 formEncType: t.formEncType, 2410 formData: void 0, 2411 json: h, 2412 text: void 0 2413 } 2414 }; 2415 } catch { 2416 return i(); 2417 } 2418 } 2419 } 2420 ht( 2421 typeof FormData == "function", 2422 "FormData is not available in this environment" 2423 ); 2424 let l, o; 2425 if (t.formData) 2426 l = sc(t.formData), o = t.formData; 2427 else if (t.body instanceof FormData) 2428 l = sc(t.body), o = t.body; 2429 else if (t.body instanceof URLSearchParams) 2430 l = t.body, o = Th(l); 2431 else if (t.body == null) 2432 l = new URLSearchParams(), o = new FormData(); 2433 else 2434 try { 2435 l = new URLSearchParams(t.body), o = Th(l); 2436 } catch { 2437 return i(); 2438 } 2439 let c = { 2440 formMethod: s, 2441 formAction: a, 2442 formEncType: t && t.formEncType || "application/x-www-form-urlencoded", 2443 formData: o, 2444 json: void 0, 2445 text: void 0 2446 }; 2447 if (dn(c.formMethod)) 2448 return { path: e, submission: c }; 2449 let u = cr(e); 2450 return n && u.search && Su(u.search) && l.append("index", ""), u.search = `?${l}`, { path: mi(u), submission: c }; 2451} 2452function xh(n, e, t, i, r, s, a, l, o, c, u, h, d, f, p, v, m, g, _, x, E) { 2453 let R = x ? Cn(x[1]) ? x[1].error : x[1].data : void 0, T = r.createURL(s.location), w = r.createURL(o), y; 2454 if (u && s.errors) { 2455 let I = Object.keys(s.errors)[0]; 2456 y = a.findIndex((k) => k.route.id === I); 2457 } else if (x && Cn(x[1])) { 2458 let I = x[0]; 2459 y = a.findIndex((k) => k.route.id === I) - 1; 2460 } 2461 let M = x ? x[1].statusCode : void 0, L = M && M >= 400, C = { 2462 currentUrl: T, 2463 currentParams: s.matches[0]?.params || {}, 2464 nextUrl: w, 2465 nextParams: a[0].params, 2466 ...l, 2467 actionResult: R, 2468 actionStatus: M 2469 }, U = _a(a), V = a.map((I, k) => { 2470 let { route: H } = I, X = null; 2471 if (y != null && k > y ? X = !1 : H.lazy ? X = !0 : bu(H) ? u ? X = ic( 2472 H, 2473 s.loaderData, 2474 s.errors 2475 ) : l0(s.loaderData, s.matches[k], I) && (X = !0) : X = !1, X !== null) 2476 return rc( 2477 t, 2478 i, 2479 n, 2480 U, 2481 I, 2482 c, 2483 e, 2484 X 2485 ); 2486 let K = !1; 2487 typeof E == "boolean" ? K = E : L ? K = !1 : (h || T.pathname + T.search === w.pathname + w.search || T.search !== w.search || c0(s.matches[k], I)) && (K = !0); 2488 let ae = { 2489 ...C, 2490 defaultShouldRevalidate: K 2491 }, se = Js(I, ae); 2492 return rc( 2493 t, 2494 i, 2495 n, 2496 U, 2497 I, 2498 c, 2499 e, 2500 se, 2501 ae, 2502 E 2503 ); 2504 }), F = []; 2505 return p.forEach((I, k) => { 2506 if (u || !a.some((Ie) => Ie.route.id === I.routeId) || f.has(k)) 2507 return; 2508 let H = s.fetchers.get(k), X = H && H.state !== "idle" && H.data === void 0, K = Yi(m, I.path, g); 2509 if (!K) { 2510 if (_ && X) 2511 return; 2512 F.push({ 2513 key: k, 2514 routeId: I.routeId, 2515 path: I.path, 2516 matches: null, 2517 match: null, 2518 request: null, 2519 controller: null 2520 }); 2521 return; 2522 } 2523 if (v.has(k)) 2524 return; 2525 let ae = mo(K, I.path), se = new AbortController(), he = ns( 2526 r, 2527 I.path, 2528 se.signal 2529 ), Ce = null; 2530 if (d.has(k)) 2531 d.delete(k), Ce = us( 2532 t, 2533 i, 2534 he, 2535 K, 2536 ae, 2537 c, 2538 e 2539 ); 2540 else if (X) 2541 h && (Ce = us( 2542 t, 2543 i, 2544 he, 2545 K, 2546 ae, 2547 c, 2548 e 2549 )); 2550 else { 2551 let Ie; 2552 typeof E == "boolean" ? Ie = E : L ? Ie = !1 : Ie = h; 2553 let Ee = { 2554 ...C, 2555 defaultShouldRevalidate: Ie 2556 }; 2557 Js(ae, Ee) && (Ce = us( 2558 t, 2559 i, 2560 he, 2561 K, 2562 ae, 2563 c, 2564 e, 2565 Ee 2566 )); 2567 } 2568 Ce && F.push({ 2569 key: k, 2570 routeId: I.routeId, 2571 path: I.path, 2572 matches: Ce, 2573 match: ae, 2574 request: he, 2575 controller: se 2576 }); 2577 }), { dsMatches: V, revalidatingFetchers: F }; 2578} 2579function bu(n) { 2580 return n.loader != null || n.middleware != null && n.middleware.length > 0; 2581} 2582function ic(n, e, t) { 2583 if (n.lazy) 2584 return !0; 2585 if (!bu(n)) 2586 return !1; 2587 let i = e != null && n.id in e, r = t != null && t[n.id] !== void 0; 2588 return !i && r ? !1 : typeof n.loader == "function" && n.loader.hydrate === !0 ? !0 : !i && !r; 2589} 2590function l0(n, e, t) { 2591 let i = ( 2592 // [a] -> [a, b] 2593 !e || // [a, b] -> [a, c] 2594 t.route.id !== e.route.id 2595 ), r = !n.hasOwnProperty(t.route.id); 2596 return i || r; 2597} 2598function c0(n, e) { 2599 let t = n.route.path; 2600 return ( 2601 // param change for this match, /users/123 -> /users/456 2602 n.pathname !== e.pathname || // splat param changed, which is not present in match.path 2603 // e.g. /files/images/avatar.jpg -> files/finances.xls 2604 t != null && t.endsWith("*") && n.params["*"] !== e.params["*"] 2605 ); 2606} 2607function Js(n, e) {
2608 if (n.route.shouldRevalidate) { 2609 let t = n.route.shouldRevalidate(e); 2610 if (typeof t == "boolean") 2611 return t; 2612 } 2613 return e.defaultShouldRevalidate; 2614} 2615function bh(n, e, t, i, r, s) { 2616 let a; 2617 if (n) { 2618 let c = i[n]; 2619 ht( 2620 c, 2621 `No route found to patch children into: routeId = ${n}` 2622 ), c.children || (c.children = []), a = c.children; 2623 } else 2624 a = t; 2625 let l = [], o = []; 2626 if (e.forEach((c) => { 2627 let u = a.find( 2628 (h) => rp(c, h) 2629 ); 2630 u ? o.push({ existingRoute: u, newRoute: c }) : l.push(c); 2631 }), l.length > 0) { 2632 let c = ra( 2633 l, 2634 r, 2635 [n || "_", "patch", String(a?.length || "0")], 2636 i 2637 ); 2638 a.push(...c); 2639 } 2640 if (s && o.length > 0) 2641 for (let c = 0; c < o.length; c++) { 2642 let { existingRoute: u, newRoute: h } = o[c], d = u, [f] = ra( 2643 [h], 2644 r, 2645 [], 2646 // Doesn't matter for mutated routes since they already have an id 2647 {}, 2648 // Don't touch the manifest here since we're updating in place 2649 !0 2650 ); 2651 Object.assign(d, { 2652 element: f.element ? f.element : d.element, 2653 errorElement: f.errorElement ? f.errorElement : d.errorElement, 2654 hydrateFallbackElement: f.hydrateFallbackElement ? f.hydrateFallbackElement : d.hydrateFallbackElement 2655 }); 2656 } 2657} 2658function rp(n, e) { 2659 return "id" in n && "id" in e && n.id === e.id ? !0 : n.index === e.index && n.path === e.path && n.caseSensitive === e.caseSensitive ? (!n.children || n.children.length === 0) && (!e.children || e.children.length === 0) ? !0 : n.children.every( 2660 (t, i) => e.children?.some((r) => rp(t, r)) 2661 ) : !1; 2662} 2663var wh = /* @__PURE__ */ new WeakMap(), sp = ({ 2664 key: n, 2665 route: e, 2666 manifest: t, 2667 mapRouteProperties: i 2668}) => { 2669 let r = t[e.id]; 2670 if (ht(r, "No route found in manifest"), !r.lazy || typeof r.lazy != "object") 2671 return; 2672 let s = r.lazy[n]; 2673 if (!s) 2674 return; 2675 let a = wh.get(r); 2676 a || (a = {}, wh.set(r, a)); 2677 let l = a[n]; 2678 if (l) 2679 return l; 2680 let o = (async () => {
2681 let c = Tg(n), h = r[n] !== void 0 && n !== "hasErrorBoundary"; 2682 if (c) 2683 jt( 2684 !c, 2685 "Route property " + n + " is not a supported lazy route property. This property will be ignored." 2686 ), a[n] = Promise.resolve(); 2687 else if (h) 2688 jt( 2689 !1, 2690 `Route "${r.id}" has a static property "${n}" defined. The lazy property will be ignored.` 2691 ); 2692 else { 2693 let d = await s(); 2694 d != null && (Object.assign(r, { [n]: d }), Object.assign(r, i(r))); 2695 } 2696 typeof r.lazy == "object" && (r.lazy[n] = void 0, Object.values(r.lazy).every((d) => d === void 0) && (r.lazy = void 0)); 2697 })(); 2698 return a[n] = o, o; 2699}, Sh = /* @__PURE__ */ new WeakMap(); 2700function u0(n, e, t, i, r) { 2701 let s = t[n.id]; 2702 if (ht(s, "No route found in manifest"), !n.lazy) 2703 return { 2704 lazyRoutePromise: void 0, 2705 lazyHandlerPromise: void 0 2706 }; 2707 if (typeof n.lazy == "function") { 2708 let u = Sh.get(s); 2709 if (u) 2710 return { 2711 lazyRoutePromise: u, 2712 lazyHandlerPromise: u 2713 }; 2714 let h = (async () => { 2715 ht( 2716 typeof n.lazy == "function", 2717 "No lazy route function found" 2718 ); 2719 let d = await n.lazy(), f = {}; 2720 for (let p in d) { 2721 let v = d[p]; 2722 if (v === void 0) 2723 continue; 2724 let m = Rg(p), _ = s[p] !== void 0 && // This property isn't static since it should always be updated based 2725 // on the route updates 2726 p !== "hasErrorBoundary"; 2727 m ? jt( 2728 !m, 2729 "Route property " + p + " is not a supported property to be returned from a lazy route function. This property will be ignored." 2730 ) : _ ? jt( 2731 !_, 2732 `Route "${s.id}" has a static property "${p}" defined but its lazy function is also returning a value for this property. The lazy route property "${p}" will be ignored.` 2733 ) : f[p] = v; 2734 } 2735 Object.assign(s, f), Object.assign(s, { 2736 // To keep things framework agnostic, we use the provided `mapRouteProperties` 2737 // function to set the framework-aware properties (`element`/`hasErrorBoundary`) 2738 // since the logic will differ between frameworks. 2739 ...i(s), 2740 lazy: void 0 2741 }); 2742 })(); 2743 return Sh.set(s, h), h.catch(() => { 2744 }), { 2745 lazyRoutePromise: h, 2746 lazyHandlerPromise: h 2747 }; 2748 } 2749 let a = Object.keys(n.lazy), l = [], o; 2750 for (let u of a) { 2751 if (r && r.includes(u)) 2752 continue; 2753 let h = sp({ 2754 key: u, 2755 route: n, 2756 manifest: t, 2757 mapRouteProperties: i 2758 }); 2759 h && (l.push(h), u === e && (o = h)); 2760 } 2761 let c = l.length > 0 ? Promise.all(l).then(() => { 2762 }) : void 0; 2763 return c?.catch(() => { 2764 }), o?.catch(() => { 2765 }), { 2766 lazyRoutePromise: c, 2767 lazyHandlerPromise: o 2768 }; 2769} 2770async function Eh(n) { 2771 let e = n.matches.filter((r) => r.shouldLoad), t = {}; 2772 return (await Promise.all(e.map((r) => r.resolve()))).forEach((r, s) => { 2773 t[e[s].route.id] = r; 2774 }), t; 2775} 2776async function h0(n) { 2777 return n.matches.some((e) => e.route.middleware) ? ap(n, () => Eh(n)) : Eh(n); 2778} 2779function ap(n, e) { 2780 return d0( 2781 n, 2782 e, 2783 (i) => { 2784 if (M0(i)) 2785 throw i; 2786 return i; 2787 }, 2788 b0, 2789 t 2790 ); 2791 function t(i, r, s) { 2792 if (s) 2793 return Promise.resolve( 2794 Object.assign(s.value, { 2795 [r]: { type: "error", result: i } 2796 }) 2797 ); 2798 { 2799 let { matches: a } = n, l = Math.min( 2800 // Throwing route 2801 Math.max( 2802 a.findIndex((c) => c.route.id === r), 2803 0 2804 ), 2805 // or the shallowest route that needs to load data 2806 Math.max( 2807 a.findIndex((c) => c.shouldCallHandler()), 2808 0 2809 ) 2810 ), o = Ki( 2811 a, 2812 a[l].route.id 2813 ).route.id; 2814 return Promise.resolve({ 2815 [o]: { type: "error", result: i } 2816 }); 2817 } 2818 } 2819} 2820async function d0(n, e, t, i, r) { 2821 let { matches: s, request: a, params: l, context: o, unstable_pattern: c } = n, u = s.flatMap( 2822 (d) => d.route.middleware ? d.route.middleware.map((f) => [d.route.id, f]) : [] 2823 ); 2824 return await op( 2825 { 2826 request: a, 2827 params: l, 2828 context: o, 2829 unstable_pattern: c 2830 }, 2831 u, 2832 e, 2833 t, 2834 i, 2835 r 2836 ); 2837} 2838async function op(n, e, t, i, r, s, a = 0) { 2839 let { request: l } = n; 2840 if (l.signal.aborted) 2841 throw l.signal.reason ?? new Error(`Request aborted: ${l.method} ${l.url}`); 2842 let o = e[a]; 2843 if (!o) 2844 return await t(); 2845 let [c, u] = o, h, d = async () => { 2846 if (h) 2847 throw new Error("You may only call `next()` once per middleware"); 2848 try { 2849 return h = { value: await op( 2850 n, 2851 e, 2852 t, 2853 i, 2854 r, 2855 s, 2856 a + 1 2857 ) }, h.value; 2858 } catch (f) { 2859 return h = { value: await s(f, c, h) }, h.value; 2860 } 2861 }; 2862 try { 2863 let f = await u(n, d), p = f != null ? i(f) : void 0; 2864 return r(p) ? p : h ? p ?? h.value : (h = { value: await d() }, h.value); 2865 } catch (f) { 2866 return await s(f, c, h); 2867 } 2868} 2869function lp(n, e, t, i, r) { 2870 let s = sp({ 2871 key: "middleware", 2872 route: i.route, 2873 manifest: e, 2874 mapRouteProperties: n 2875 }), a = u0( 2876 i.route, 2877 dn(t.method) ? "action" : "loader", 2878 e, 2879 n, 2880 r 2881 ); 2882 return { 2883 middleware: s, 2884 route: a.lazyRoutePromise, 2885 handler: a.lazyHandlerPromise 2886 }; 2887} 2888function rc(n, e, t, i, r, s, a, l, o = null, c) { 2889 let u = !1, h = lp( 2890 n, 2891 e, 2892 t, 2893 r, 2894 s 2895 ); 2896 return { 2897 ...r, 2898 _lazyPromises: h, 2899 shouldLoad: l, 2900 shouldRevalidateArgs: o, 2901 shouldCallHandler(d) { 2902 return u = !0, o ? typeof c == "boolean" ? Js(r, { 2903 ...o, 2904 defaultShouldRevalidate: c 2905 }) : typeof d == "boolean" ? Js(r, { 2906 ...o, 2907 defaultShouldRevalidate: d 2908 }) : Js(r, o) : l; 2909 }, 2910 resolve(d) { 2911 let { lazy: f, loader: p, middleware: v } = r.route, m = u || l || d && !dn(t.method) && (f || p), g = v && v.length > 0 && !p && !f; 2912 return m && (dn(t.method) || !g) ? p0({ 2913 request: t, 2914 unstable_pattern: i, 2915 match: r, 2916 lazyHandlerPromise: h?.handler, 2917 lazyRoutePromise: h?.route, 2918 handlerOverride: d, 2919 scopedContext: a 2920 }) : Promise.resolve({ type: "data", result: void 0 }); 2921 } 2922 }; 2923} 2924function us(n, e, t, i, r, s, a, l = null) { 2925 return i.map((o) => o.route.id !== r.route.id ? { 2926 ...o, 2927 shouldLoad: !1, 2928 shouldRevalidateArgs: l, 2929 shouldCallHandler: () => !1, 2930 _lazyPromises: lp( 2931 n, 2932 e, 2933 t, 2934 o, 2935 s 2936 ), 2937 resolve: () => Promise.resolve({ type: "data", result: void 0 }) 2938 } : rc( 2939 n, 2940 e, 2941 t, 2942 _a(i), 2943 o, 2944 s, 2945 a, 2946 !0, 2947 l 2948 )); 2949} 2950async function f0(n, e, t, i, r, s) { 2951 t.some((c) => c._lazyPromises?.middleware) && await Promise.all(t.map((c) => c._lazyPromises?.middleware)); 2952 let a = { 2953 request: e, 2954 unstable_pattern: _a(t), 2955 params: t[0].params, 2956 context: r, 2957 matches: t 2958 }, o = await n({ 2959 ...a, 2960 fetcherKey: i, 2961 runClientMiddleware: (c) => { 2962 let u = a; 2963 return ap(u, () => c({ 2964 ...u, 2965 fetcherKey: i, 2966 runClientMiddleware: () => { 2967 throw new Error( 2968 "Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler" 2969 ); 2970 } 2971 })); 2972 } 2973 }); 2974 try { 2975 await Promise.all( 2976 t.flatMap((c) => [ 2977 c._lazyPromises?.handler, 2978 c._lazyPromises?.route 2979 ]) 2980 ); 2981 } catch { 2982 } 2983 return o; 2984} 2985async function p0({ 2986 request: n, 2987 unstable_pattern: e, 2988 match: t, 2989 lazyHandlerPromise: i, 2990 lazyRoutePromise: r, 2991 handlerOverride: s, 2992 scopedContext: a 2993}) { 2994 let l, o, c = dn(n.method), u = c ? "action" : "loader", h = (d) => { 2995 let f, p = new Promise((g, _) => f = _); 2996 o = () => f(), n.signal.addEventListener("abort", o); 2997 let v = (g) => typeof d != "function" ? Promise.reject( 2998 new Error( 2999 `You cannot call the handler for a route which defines a boolean "${u}" [routeId: ${t.route.id}]` 3000 ) 3001 ) : d( 3002 { 3003 request: n, 3004 unstable_pattern: e, 3005 params: t.params, 3006 context: a 3007 }, 3008 ...g !== void 0 ? [g] : [] 3009 ), m = (async () => {
3010 try { 3011 return { type: "data", result: await (s ? s((_) => v(_)) : v()) }; 3012 } catch (g) { 3013 return { type: "error", result: g }; 3014 } 3015 })(); 3016 return Promise.race([m, p]); 3017 }; 3018 try { 3019 let d = c ? t.route.action : t.route.loader; 3020 if (i || r) 3021 if (d) { 3022 let f, [p] = await Promise.all([ 3023 // If the handler throws, don't let it immediately bubble out, 3024 // since we need to let the lazy() execution finish so we know if this 3025 // route has a boundary that can handle the error 3026 h(d).catch((v) => { 3027 f = v; 3028 }), 3029 // Ensure all lazy route promises are resolved before continuing 3030 i, 3031 r 3032 ]); 3033 if (f !== void 0) 3034 throw f; 3035 l = p; 3036 } else { 3037 await i; 3038 let f = c ? t.route.action : t.route.loader; 3039 if (f) 3040 [l] = await Promise.all([h(f), r]); 3041 else if (u === "action") { 3042 let p = new URL(n.url), v = p.pathname + p.search; 3043 throw zn(405, { 3044 method: n.method, 3045 pathname: v, 3046 routeId: t.route.id 3047 }); 3048 } else 3049 return { type: "data", result: void 0 }; 3050 } 3051 else if (d) 3052 l = await h(d); 3053 else { 3054 let f = new URL(n.url), p = f.pathname + f.search; 3055 throw zn(404, { 3056 pathname: p 3057 }); 3058 } 3059 } catch (d) { 3060 return { type: "error", result: d }; 3061 } finally { 3062 o && n.signal.removeEventListener("abort", o); 3063 } 3064 return l; 3065} 3066async function m0(n) { 3067 let e = n.headers.get("Content-Type"); 3068 return e && /\bapplication\/json\b/.test(e) ? n.body == null ? null : n.json() : n.text(); 3069} 3070async function g0(n) { 3071 let { result: e, type: t } = n; 3072 if (wu(e)) { 3073 let i; 3074 try { 3075 i = await m0(e); 3076 } catch (r) { 3077 return { type: "error", error: r }; 3078 } 3079 return t === "error" ? { 3080 type: "error", 3081 error: new va(e.status, e.statusText, i), 3082 statusCode: e.status, 3083 headers: e.headers 3084 } : { 3085 type: "data", 3086 data: i, 3087 statusCode: e.status, 3088 headers: e.headers 3089 }; 3090 } 3091 return t === "error" ? Ph(e) ? e.data instanceof Error ? { 3092 type: "error", 3093 error: e.data, 3094 statusCode: e.init?.status, 3095 headers: e.init?.headers ? new Headers(e.init.headers) : void 0 3096 } : { 3097 type: "error", 3098 error: x0(e), 3099 statusCode: sa(e) ? e.status : void 0, 3100 headers: e.init?.headers ? new Headers(e.init.headers) : void 0 3101 } : { 3102 type: "error", 3103 error: e, 3104 statusCode: sa(e) ? e.status : void 0 3105 } : Ph(e) ? { 3106 type: "data", 3107 data: e.data, 3108 statusCode: e.init?.status, 3109 headers: e.init?.headers ? new Headers(e.init.headers) : void 0 3110 } : { type: "data", data: e }; 3111} 3112function v0(n, e, t, i, r) { 3113 let s = n.headers.get("Location"); 3114 if (ht( 3115 s, 3116 "Redirects returned/thrown from loaders/actions must have a Location header" 3117 ), !_u(s)) { 3118 let a = i.slice( 3119 0, 3120 i.findIndex((l) => l.route.id === t) + 1 3121 ); 3122 s = nc( 3123 new URL(e.url), 3124 a, 3125 r, 3126 s 3127 ), n.headers.set("Location", s); 3128 } 3129 return n; 3130} 3131function Mh(n, e, t, i) { 3132 let r = [ 3133 "about:", 3134 "blob:", 3135 "chrome:", 3136 "chrome-untrusted:", 3137 "content:", 3138 "data:", 3139 "devtools:", 3140 "file:", 3141 "filesystem:", 3142 // eslint-disable-next-line no-script-url 3143 "javascript:" 3144 ]; 3145 if (_u(n)) { 3146 let s = n, a = s.startsWith("//") ? new URL(e.protocol + s) : new URL(s); 3147 if (r.includes(a.protocol)) 3148 throw new Error("Invalid redirect location"); 3149 let l = Vn(a.pathname, t) != null; 3150 if (a.origin === e.origin && l) 3151 return a.pathname + a.search + a.hash; 3152 } 3153 try { 3154 let s = i.createURL(n); 3155 if (r.includes(s.protocol)) 3156 throw new Error("Invalid redirect location"); 3157 } catch { 3158 } 3159 return n; 3160} 3161function ns(n, e, t, i) { 3162 let r = n.createURL(cp(e)).toString(), s = { signal: t }; 3163 if (i && dn(i.formMethod)) { 3164 let { formMethod: a, formEncType: l } = i; 3165 s.method = a.toUpperCase(), l === "application/json" ? (s.headers = new Headers({ "Content-Type": l }), s.body = JSON.stringify(i.json)) : l === "text/plain" ? s.body = i.text : l === "application/x-www-form-urlencoded" && i.formData ? s.body = sc(i.formData) : s.body = i.formData; 3166 }
3167 return new Request(r, s); 3168} 3169function sc(n) { 3170 let e = new URLSearchParams(); 3171 for (let [t, i] of n.entries()) 3172 e.append(t, typeof i == "string" ? i : i.name); 3173 return e; 3174} 3175function Th(n) { 3176 let e = new FormData(); 3177 for (let [t, i] of n.entries()) 3178 e.append(t, i); 3179 return e; 3180} 3181function _0(n, e, t, i = !1, r = !1) { 3182 let s = {}, a = null, l, o = !1, c = {}, u = t && Cn(t[1]) ? t[1].error : void 0; 3183 return n.forEach((h) => { 3184 if (!(h.route.id in e)) 3185 return; 3186 let d = h.route.id, f = e[d]; 3187 if (ht( 3188 !Er(f), 3189 "Cannot handle redirect results in processLoaderData" 3190 ), Cn(f)) { 3191 let p = f.error; 3192 if (u !== void 0 && (p = u, u = void 0), a = a || {}, r) 3193 a[d] = p; 3194 else { 3195 let v = Ki(n, d); 3196 a[v.route.id] == null && (a[v.route.id] = p); 3197 } 3198 i || (s[d] = ip), o || (o = !0, l = sa(f.error) ? f.error.status : 500), f.headers && (c[d] = f.headers); 3199 } else 3200 s[d] = f.data, f.statusCode && f.statusCode !== 200 && !o && (l = f.statusCode), f.headers && (c[d] = f.headers); 3201 }), u !== void 0 && t && (a = { [t[0]]: u }, t[2] && (s[t[2]] = void 0)), { 3202 loaderData: s, 3203 errors: a, 3204 statusCode: l || 200, 3205 loaderHeaders: c 3206 }; 3207} 3208function Ah(n, e, t, i, r, s) { 3209 let { loaderData: a, errors: l } = _0( 3210 e, 3211 t, 3212 i 3213 ); 3214 return r.filter((o) => !o.matches || o.matches.some((c) => c.shouldLoad)).forEach((o) => { 3215 let { key: c, match: u, controller: h } = o; 3216 if (h && h.signal.aborted) 3217 return; 3218 let d = s[c]; 3219 if (ht(d, "Did not find corresponding fetcher result"), Cn(d)) { 3220 let f = Ki(n.matches, u?.route.id); 3221 l && l[f.route.id] || (l = { 3222 ...l, 3223 [f.route.id]: d.error 3224 }), n.fetchers.delete(c); 3225 } else if (Er(d)) 3226 ht(!1, "Unhandled fetcher revalidation redirect"); 3227 else { 3228 let f = Ci(d.data); 3229 n.fetchers.set(c, f); 3230 } 3231 }), { loaderData: a, errors: l }; 3232} 3233function Rh(n, e, t, i) { 3234 let r = Object.entries(e).filter(([, s]) => s !== ip).reduce((s, [a, l]) => (s[a] = l, s), {}); 3235 for (let s of t) { 3236 let a = s.route.id; 3237 if (!e.hasOwnProperty(a) && n.hasOwnProperty(a) && s.route.loader && (r[a] = n[a]), i && i.hasOwnProperty(a)) 3238 break; 3239 } 3240 return r; 3241} 3242function Ch(n) { 3243 return n ? Cn(n[1]) ? { 3244 // Clear out prior actionData on errors 3245 actionData: {} 3246 } : { 3247 actionData: { 3248 [n[0]]: n[1].data 3249 } 3250 } : {}; 3251} 3252function Ki(n, e) { 3253 return (e ? n.slice(0, n.findIndex((i) => i.route.id === e) + 1) : [...n]).reverse().find((i) => i.route.hasErrorBoundary === !0) || n[0]; 3254} 3255function Ca(n) { 3256 let e = n.length === 1 ? n[0] : n.find((t) => t.index || !t.path || t.path === "/") || { 3257 id: "__shim-error-route__" 3258 }; 3259 return { 3260 matches: [ 3261 { 3262 params: {}, 3263 pathname: "", 3264 pathnameBase: "", 3265 route: e 3266 } 3267 ], 3268 route: e 3269 }; 3270} 3271function zn(n, { 3272 pathname: e, 3273 routeId: t, 3274 method: i, 3275 type: r, 3276 message: s 3277} = {}) { 3278 let a = "Unknown Server Error", l = "Unknown @remix-run/router error"; 3279 return n === 400 ? (a = "Bad Request", i && e && t ? l = `You made a ${i} request to "${e}" but did not provide a \`loader\` for route "${t}", so there is no way to handle the request.` : r === "invalid-body" && (l = "Unable to encode submission body")) : n === 403 ? (a = "Forbidden", l = `Route "${t}" does not match URL "${e}"`) : n === 404 ? (a = "Not Found", l = `No route matches URL "${e}"`) : n === 405 && (a = "Method Not Allowed", i && e && t ? l = `You made a ${i.toUpperCase()} request to "${e}" but did not provide an \`action\` for route "${t}", so there is no way to handle the request.` : i && (l = `Invalid request method "${i.toUpperCase()}"`)), new va( 3280 n || 500, 3281 a, 3282 new Error(l), 3283 !0 3284 ); 3285} 3286function Pa(n) { 3287 let e = Object.entries(n); 3288 for (let t = e.length - 1; t >= 0; t--) { 3289 let [i, r] = e[t]; 3290 if (Er(r)) 3291 return { key: i, result: r }; 3292 } 3293} 3294function cp(n) { 3295 let e = typeof n == "string" ? cr(n) : n; 3296 return mi({ ...e, hash: "" }); 3297} 3298function y0(n, e) { 3299 return n.pathname !== e.pathname || n.search !== e.search ? !1 : n.hash === "" ? e.hash !== "" : n.hash === e.hash ? !0 : e.hash !== ""; 3300} 3301function x0(n) { 3302 return new va( 3303 n.init?.status ?? 500, 3304 n.init?.statusText ?? "Internal Server Error", 3305 n.data 3306 ); 3307} 3308function b0(n) { 3309 return n != null && typeof n == "object" && Object.entries(n).every( 3310 ([e, t]) => typeof e == "string" && w0(t) 3311 ); 3312} 3313function w0(n) { 3314 return n != null && typeof n == "object" && "type" in n && "result" in n && (n.type === "data" || n.type === "error"); 3315} 3316function S0(n) { 3317 return wu(n.result) && tp.has(n.result.status); 3318} 3319function Cn(n) { 3320 return n.type === "error"; 3321} 3322function Er(n) { 3323 return (n && n.type) === "redirect"; 3324} 3325function Ph(n) { 3326 return typeof n == "object" && n != null && "type" in n && "data" in n && "init" in n && n.type === "DataWithResponseInit"; 3327} 3328function wu(n) { 3329 return n != null && typeof n.status == "number" && typeof n.statusText == "string" && typeof n.headers == "object" && typeof n.body < "u"; 3330} 3331function E0(n) { 3332 return tp.has(n); 3333} 3334function M0(n) { 3335 return wu(n) && E0(n.status) && n.headers.has("Location"); 3336} 3337function T0(n) { 3338 return n0.has(n.toUpperCase()); 3339} 3340function dn(n) { 3341 return e0.has(n.toUpperCase()); 3342} 3343function Su(n) { 3344 return new URLSearchParams(n).getAll("index").some((e) => e === ""); 3345} 3346function mo(n, e) { 3347 let t = typeof e == "string" ? cr(e).search : e.search; 3348 if (n[n.length - 1].route.index && Su(t || "")) 3349 return n[n.length - 1]; 3350 let i = Kf(n); 3351 return i[i.length - 1]; 3352} 3353function Lh(n) { 3354 let { formMethod: e, formAction: t, formEncType: i, text: r, formData: s, json: a } = n; 3355 if (!(!e || !t || !i)) { 3356 if (r != null) 3357 return { 3358 formMethod: e, 3359 formAction: t, 3360 formEncType: i, 3361 formData: void 0, 3362 json: void 0, 3363 text: r 3364 }; 3365 if (s != null) 3366 return { 3367 formMethod: e, 3368 formAction: t, 3369 formEncType: i, 3370 formData: s, 3371 json: void 0, 3372 text: void 0 3373 }; 3374 if (a !== void 0) 3375 return { 3376 formMethod: e, 3377 formAction: t, 3378 formEncType: i, 3379 formData: void 0, 3380 json: a, 3381 text: void 0 3382 }; 3383 } 3384} 3385function ol(n, e) { 3386 return e ? { 3387 state: "loading", 3388 location: n, 3389 formMethod: e.formMethod, 3390 formAction: e.formAction, 3391 formEncType: e.formEncType, 3392 formData: e.formData, 3393 json: e.json, 3394 text: e.text 3395 }
3395 : { 3396 state: "loading", 3397 location: n, 3398 formMethod: void 0, 3399 formAction: void 0, 3400 formEncType: void 0, 3401 formData: void 0, 3402 json: void 0, 3403 text: void 0 3404 }; 3405} 3406function A0(n, e) { 3407 return { 3408 state: "submitting", 3409 location: n, 3410 formMethod: e.formMethod, 3411 formAction: e.formAction, 3412 formEncType: e.formEncType, 3413 formData: e.formData, 3414 json: e.json, 3415 text: e.text 3416 }; 3417} 3418function Ls(n, e) { 3419 return n ? { 3420 state: "loading", 3421 formMethod: n.formMethod, 3422 formAction: n.formAction, 3423 formEncType: n.formEncType, 3424 formData: n.formData, 3425 json: n.json, 3426 text: n.text, 3427 data: e 3428 } : { 3429 state: "loading", 3430 formMethod: void 0, 3431 formAction: void 0, 3432 formEncType: void 0, 3433 formData: void 0, 3434 json: void 0, 3435 text: void 0, 3436 data: e 3437 }; 3438} 3439function R0(n, e) { 3440 return { 3441 state: "submitting", 3442 formMethod: n.formMethod, 3443 formAction: n.formAction, 3444 formEncType: n.formEncType, 3445 formData: n.formData, 3446 json: n.json, 3447 text: n.text, 3448 data: e ? e.data : void 0 3449 }; 3450} 3451function Ci(n) { 3452 return { 3453 state: "idle", 3454 formMethod: void 0, 3455 formAction: void 0, 3456 formEncType: void 0, 3457 formData: void 0, 3458 json: void 0, 3459 text: void 0, 3460 data: n 3461 }; 3462} 3463function C0(n, e) { 3464 try { 3465 let t = n.sessionStorage.getItem( 3466 np 3467 ); 3468 if (t) { 3469 let i = JSON.parse(t); 3470 for (let [r, s] of Object.entries(i || {})) 3471 s && Array.isArray(s) && e.set(r, new Set(s || [])); 3472 } 3473 } catch { 3474 } 3475} 3476function P0(n, e) { 3477 if (e.size > 0) { 3478 let t = {}; 3479 for (let [i, r] of e) 3480 t[i] = [...r]; 3481 try { 3482 n.sessionStorage.setItem( 3483 np, 3484 JSON.stringify(t) 3485 ); 3486 } catch (i) { 3487 jt( 3488 !1, 3489 `Failed to save applied view transitions in sessionStorage (${i}).` 3490 ); 3491 } 3492 } 3493} 3494function Nh() { 3495 let n, e, t = new Promise((i, r) => { 3496 n = async (s) => { 3497 i(s); 3498 try { 3499 await t; 3500 } catch { 3501 } 3502 }, e = async (s) => { 3503 r(s); 3504 try { 3505 await t; 3506 } catch { 3507 } 3508 }; 3509 }); 3510 return { 3511 promise: t, 3512 //@ts-ignore 3513 resolve: n, 3514 //@ts-ignore 3515 reject: e 3516 }; 3517} 3518var Nr = Un(null); 3519Nr.displayName = "DataRouter"; 3520var ya = Un(null); 3521ya.displayName = "DataRouterState"; 3522var up = Un(!1); 3523function L0() { 3524 return Mt(up); 3525} 3526var Eu = Un({ 3527 isTransitioning: !1 3528}); 3529Eu.displayName = "ViewTransition"; 3530var hp = Un( 3531 /* @__PURE__ */ new Map() 3532); 3533hp.displayName = "Fetchers"; 3534var N0 = Un(null); 3535N0.displayName = "Await"; 3536var jn = Un( 3537 null 3538); 3539jn.displayName = "Navigation"; 3540var Vo = Un( 3541 null 3542); 3543Vo.displayName = "Location"; 3544var vi = Un({ 3545 outlet: null, 3546 matches: [], 3547 isDataRoute: !1 3548}); 3549vi.displayName = "Route"; 3550var Mu = Un(null); 3551Mu.displayName = "RouteError"; 3552var dp = "REACT_ROUTER_ERROR", I0 = "REDIRECT", D0 = "ROUTE_ERROR_RESPONSE"; 3553function U0(n) { 3554 if (n.startsWith(`${dp}:${I0}:{`)) 3555 try { 3556 let e = JSON.parse(n.slice(28)); 3557 if (typeof e == "object" && e && typeof e.status == "number" && typeof e.statusText == "string" && typeof e.location == "string" && typeof e.reloadDocument == "boolean" && typeof e.replace == "boolean") 3558 return e; 3559 } catch { 3560 } 3561} 3562function O0(n) { 3563 if (n.startsWith( 3564 `${dp}:${D0}:{` 3565 )) 3566 try { 3567 let e = JSON.parse(n.slice(40)); 3568 if (typeof e == "object" && e && typeof e.status == "number" && typeof e.statusText == "string") 3569 return new va( 3570 e.status, 3571 e.statusText, 3572 e.data 3573 ); 3574 } catch { 3575 } 3576} 3577function k0(n, { relative: e } = {}) { 3578 ht( 3579 xa(), 3580 // TODO: This error is probably because they somehow have 2 versions of the 3581 // router loaded. We can help them understand how to avoid that. 3582 "useHref() may be used only in the context of a <Router> component." 3583 ); 3584 let { basename: t, navigator: i } = Mt(jn), { hash: r, pathname: s, search: a } = ba(n, { relative: e }), l = s; 3585 return t !== "/" && (l = s === "/" ? t : hi([t, s])), i.createHref({ pathname: l, search: a, hash: r }); 3586} 3587function xa() { 3588 return Mt(Vo) != null; 3589} 3590function ur() { 3591 return ht( 3592 xa(), 3593 // TODO: This error is probably because they somehow have 2 versions of the 3594 // router loaded. We can help them understand how to avoid that. 3595 "useLocation() may be used only in the context of a <Router> component." 3596 ), Mt(Vo).location; 3597} 3598var fp = "You should call navigate() in a React.useEffect(), not when your component is first rendered.";
3599function pp(n) { 3600 Mt(jn).static || vu(n); 3601} 3602function hr() { 3603 let { isDataRoute: n } = Mt(vi); 3604 return n ? J0() : F0(); 3605} 3606function F0() { 3607 ht( 3608 xa(), 3609 // TODO: This error is probably because they somehow have 2 versions of the 3610 // router loaded. We can help them understand how to avoid that. 3611 "useNavigate() may be used only in the context of a <Router> component." 3612 ); 3613 let n = Mt(Nr), { basename: e, navigator: t } = Mt(jn), { matches: i } = Mt(vi), { pathname: r } = ur(), s = JSON.stringify(yu(i)), a = mt(!1); 3614 return pp(() => { 3615 a.current = !0; 3616 }), Gn( 3617 (o, c = {}) => { 3618 if (jt(a.current, fp), !a.current) return; 3619 if (typeof o == "number") { 3620 t.go(o); 3621 return; 3622 } 3623 let u = xu( 3624 o, 3625 JSON.parse(s), 3626 r, 3627 c.relative === "path" 3628 ); 3629 n == null && e !== "/" && (u.pathname = u.pathname === "/" ? e : hi([e, u.pathname])), (c.replace ? t.replace : t.push)( 3630 u, 3631 c.state, 3632 c 3633 ); 3634 }, 3635 [ 3636 e, 3637 t, 3638 s, 3639 r, 3640 n 3641 ] 3642 ); 3643} 3644Un(null); 3645function B0() { 3646 let { matches: n } = Mt(vi), e = n[n.length - 1]; 3647 return e ? e.params : {}; 3648} 3649function ba(n, { relative: e } = {}) { 3650 let { matches: t } = Mt(vi), { pathname: i } = ur(), r = JSON.stringify(yu(t)); 3651 return Nn( 3652 () => xu( 3653 n, 3654 JSON.parse(r), 3655 i, 3656 e === "path" 3657 ), 3658 [n, r, i, e] 3659 ); 3660} 3661function z0(n, e, t, i, r) { 3662 ht( 3663 xa(), 3664 // TODO: This error is probably because they somehow have 2 versions of the 3665 // router loaded. We can help them understand how to avoid that. 3666 "useRoutes() may be used only in the context of a <Router> component." 3667 ); 3668 let { navigator: s } = Mt(jn), { matches: a } = Mt(vi), l = a[a.length - 1], o = l ? l.params : {}, c = l ? l.pathname : "/", u = l ? l.pathnameBase : "/", h = l && l.route; 3669 { 3670 let _ = h && h.path || ""; 3671 gp( 3672 c, 3673 !h || _.endsWith("*") || _.endsWith("*?"), 3674 `You rendered descendant <Routes> (or called \`useRoutes()\`) at "${c}" (under <Route path="${_}">) but the parent route path has no trailing "*". This means if you navigate deeper, the parent won't match anymore and therefore the child routes will never render. 3675 3676Please change the parent <Route path="${_}"> to <Route path="${_ === "/" ? "*" : `${_}/*`}">.` 3677 ); 3678 } 3679 let d = ur(), f; 3680 f = d; 3681 let p = f.pathname || "/", v = p; 3682 if (u !== "/") { 3683 let _ = u.replace(/^\//, "").split("/"); 3684 v = "/" + p.replace(/^\//, "").split("/").slice(_.length).join("/"); 3685 } 3686 let m = Yi(n, { pathname: v }); 3687 return jt( 3688 h || m != null, 3689 `No routes matched location "${f.pathname}${f.search}${f.hash}" ` 3690 ), jt( 3691 m == null || m[m.length - 1].route.element !== void 0 || m[m.length - 1].route.Component !== void 0 || m[m.length - 1].route.lazy !== void 0, 3692 `Matched leaf route at location "${f.pathname}${f.search}${f.hash}" does not have an element or Component. This means it will render an <Outlet /> with a null value by default resulting in an "empty" page.` 3693 ), $0( 3694 m && m.map( 3695 (_) => Object.assign({}, _, { 3696 params: Object.assign({}, o, _.params), 3697 pathname: hi([ 3698 u, 3699 // Re-encode pathnames that were decoded inside matchRoutes. 3700 // Pre-encode `?` and `#` ahead of `encodeLocation` because it uses 3701 // `new URL()` internally and we need to prevent it from treating 3702 // them as separators 3703 s.encodeLocation ? s.encodeLocation( 3704 _.pathname.replace(/\?/g, "%3F").replace(/#/g, "%23") 3705 ).pathname : _.pathname 3706 ]), 3707 pathnameBase: _.pathnameBase === "/" ? u : hi([ 3708 u, 3709 // Re-encode pathnames that were decoded inside matchRoutes 3710 // Pre-encode `?` and `#` ahead of `encodeLocation` because it uses 3711 // `new URL()` internally and we need to prevent it from treating 3712 // them as separators 3713 s.encodeLocation ? s.encodeLocation( 3714 _.pathnameBase.replace(/\?/g, "%3F").replace(/#/g, "%23") 3715 ).pathname : _.pathnameBase 3716 ]) 3717 }) 3718 ), 3719 a, 3720 t, 3721 i, 3722 r 3723 ); 3724} 3725function H0() { 3726 let n = K0(), e = sa(n) ? `${n.status} ${n.statusText}` : n instanceof Error ? n.message : JSON.stringify(n), t = n instanceof Error ? n.stack : null, i = "rgba(200,200,200, 0.5)", r = { padding: "0.5rem", backgroundColor: i }, s = { padding: "2px 4px", backgroundColor: i }, a = null; 3727 return console.error( 3728 "Error handled by React Router default ErrorBoundary:", 3729 n
3730 ), a = /* @__PURE__ */ st(ps, null, /* @__PURE__ */ st("p", null, "ð¿ Hey developer ð"), /* @__PURE__ */ st("p", null, "You can provide a way better UX than this when your app throws errors by providing your own ", /* @__PURE__ */ st("code", { style: s }, "ErrorBoundary"), " or", " ", /* @__PURE__ */ st("code", { style: s }, "errorElement"), " prop on your route.")), /* @__PURE__ */ st(ps, null, /* @__PURE__ */ st("h2", null, "Unexpected Application Error!"), /* @__PURE__ */ st("h3", { style: { fontStyle: "italic" } }, e), t ? /* @__PURE__ */ st("pre", { style: r }, t) : null, a); 3731} 3732var G0 = /* @__PURE__ */ st(H0, null), mp = class extends Vf { 3733 constructor(n) { 3734 super(n), this.state = { 3735 location: n.location, 3736 revalidation: n.revalidation, 3737 error: n.error 3738 }; 3739 } 3740 static getDerivedStateFromError(n) { 3741 return { error: n }; 3742 } 3743 static getDerivedStateFromProps(n, e) { 3744 return e.location !== n.location || e.revalidation !== "idle" && n.revalidation === "idle" ? { 3745 error: n.error, 3746 location: n.location, 3747 revalidation: n.revalidation 3748 } : { 3749 error: n.error !== void 0 ? n.error : e.error, 3750 location: e.location, 3751 revalidation: n.revalidation || e.revalidation 3752 }; 3753 } 3754 componentDidCatch(n, e) { 3755 this.props.onError ? this.props.onError(n, e) : console.error( 3756 "React Router caught the following error during render", 3757 n 3758 ); 3759 } 3760 render() { 3761 let n = this.state.error; 3762 if (this.context && typeof n == "object" && n && "digest" in n && typeof n.digest == "string") { 3763 const t = O0(n.digest); 3764 t && (n = t); 3765 } 3766 let e = n !== void 0 ? /* @__PURE__ */ st(vi.Provider, { value: this.props.routeContext }, /* @__PURE__ */ st( 3767 Mu.Provider, 3768 { 3769 value: n, 3770 children: this.props.component 3771 } 3772 )) : this.props.children;
3773 return this.context ? /* @__PURE__ */ st(V0, { error: n }, e) : e; 3774 } 3775}; 3776mp.contextType = up; 3777var ll = /* @__PURE__ */ new WeakMap(); 3778function V0({ 3779 children: n, 3780 error: e 3781}) { 3782 let { basename: t } = Mt(jn); 3783 if (typeof e == "object" && e && "digest" in e && typeof e.digest == "string") { 3784 let i = U0(e.digest); 3785 if (i) { 3786 let r = ll.get(e); 3787 if (r) throw r; 3788 let s = Zf(i.location, t); 3789 if (Jf && !ll.get(e)) 3790 if (s.isExternal || i.reloadDocument) 3791 window.location.href = s.absoluteURL || s.to; 3792 else { 3793 const a = Promise.resolve().then( 3794 () => window.__reactRouterDataRouter.navigate(s.to, { 3795 replace: i.replace 3796 }) 3797 ); 3798 throw ll.set(e, a), a; 3799 } 3800 return /* @__PURE__ */ st( 3801 "meta", 3802 { 3803 httpEquiv: "refresh", 3804 content: `0;url=${s.absoluteURL || s.to}` 3805 } 3806 ); 3807 } 3808 } 3809 return n; 3810} 3811function W0({ routeContext: n, match: e, children: t }) { 3812 let i = Mt(Nr); 3813 return i && i.static && i.staticContext && (e.route.errorElement || e.route.ErrorBoundary) && (i.staticContext._deepestRenderedBoundaryId = e.route.id), /* @__PURE__ */ st(vi.Provider, { value: n }, t); 3814} 3815function $0(n, e = [], t = null, i = null, r = null) { 3816 if (n == null) { 3817 if (!t) 3818 return null; 3819 if (t.errors) 3820 n = t.matches; 3821 else if (e.length === 0 && !t.initialized && t.matches.length > 0) 3822 n = t.matches; 3823 else 3824 return null; 3825 } 3826 let s = n, a = t?.errors; 3827 if (a != null) { 3828 let u = s.findIndex( 3829 (h) => h.route.id && a?.[h.route.id] !== void 0 3830 ); 3831 ht( 3832 u >= 0, 3833 `Could not find a matching route for errors on route IDs: ${Object.keys( 3834 a 3835 ).join(",")}` 3836 ), s = s.slice( 3837 0, 3838 Math.min(s.length, u + 1) 3839 ); 3840 } 3841 let l = !1, o = -1; 3842 if (t) 3843 for (let u = 0; u < s.length; u++) { 3844 let h = s[u]; 3845 if ((h.route.HydrateFallback || h.route.hydrateFallbackElement) && (o = u), h.route.id) { 3846 let { loaderData: d, errors: f } = t, p = h.route.loader && !d.hasOwnProperty(h.route.id) && (!f || f[h.route.id] === void 0); 3847 if (h.route.lazy || p) { 3848 l = !0, o >= 0 ? s = s.slice(0, o + 1) : s = [s[0]]; 3849 break; 3850 } 3851 } 3852 } 3853 let c = t && i ? (u, h) => { 3854 i(u, { 3855 location: t.location, 3856 params: t.matches?.[0]?.params ?? {}, 3857 unstable_pattern: _a(t.matches), 3858 errorInfo: h 3859 }); 3860 } : void 0; 3861 return s.reduceRight( 3862 (u, h, d) => { 3863 let f, p = !1, v = null, m = null; 3864 t && (f = a && h.route.id ? a[h.route.id] : void 0, v = h.route.errorElement || G0, l && (o < 0 && d === 0 ? (gp( 3865 "route-fallback", 3866 !1, 3867 "No `HydrateFallback` element provided to render during initial hydration" 3868 ), p = !0, m = null) : o === d && (p = !0, m = h.route.hydrateFallbackElement || null))); 3869 let g = e.concat(s.slice(0, d + 1)), _ = () => { 3870 let x; 3871 return f ? x = v : p ? x = m : h.route.Component ? x = /* @__PURE__ */ st(h.route.Component, null) : h.route.element ? x = h.route.element : x = u, /* @__PURE__ */ st( 3872 W0, 3873 { 3874 match: h, 3875 routeContext: { 3876 outlet: u, 3877 matches: g, 3878 isDataRoute: t != null 3879 }, 3880 children: x 3881 } 3882 ); 3883 }; 3884 return t && (h.route.ErrorBoundary || h.route.errorElement || d === 0) ? /* @__PURE__ */ st( 3885 mp, 3886 { 3887 location: t.location, 3888 revalidation: t.revalidation, 3889 component: v, 3890 error: f, 3891 children: _(), 3892 routeContext: { outlet: null, matches: g, isDataRoute: !0 }, 3893 onError: c 3894 } 3895 ) : _(); 3896 }, 3897 null 3898 ); 3899} 3900function Tu(n) { 3901 return `${n} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`; 3902} 3903function j0(n) { 3904 let e = Mt(Nr); 3905 return ht(e, Tu(n)), e; 3906} 3907function X0(n) { 3908 let e = Mt(ya); 3909 return ht(e, Tu(n)), e; 3910} 3911function q0(n) { 3912 let e = Mt(vi); 3913 return ht(e, Tu(n)), e; 3914} 3915function Au(n) { 3916 let e = q0(n), t = e.matches[e.matches.length - 1]; 3917 return ht( 3918 t.route.id, 3919 `${n} can only be used on routes that contain a unique "id"` 3920 ), t.route.id; 3921} 3922function Y0() { 3923 return Au( 3924 "useRouteId" 3925 /* UseRouteId */ 3926 ); 3927} 3928function K0() { 3929 let n = Mt(Mu), e = X0( 3930 "useRouteError" 3931 /* UseRouteError */ 3932 ), t = Au( 3933 "useRouteError" 3934 /* UseRouteError */ 3935 ); 3936 return n !== void 0 ? n : e.errors?.[t]; 3937} 3938function J0() { 3939 let { router: n } = j0( 3940 "useNavigate" 3941 /* UseNavigateStable */ 3942 ), e = Au( 3943 "useNavigate" 3944 /* UseNavigateStable */ 3945 ), t = mt(!1); 3946 return pp(() => { 3947 t.current = !0; 3948 }), Gn( 3949 async (r, s = {}) => { 3950 jt(t.current, fp), t.current && (typeof r == "number" ? await n.navigate(r) : await n.navigate(r, { fromRouteId: e, ...s })); 3951 }, 3952 [n, e] 3953 ); 3954} 3955var Ih = {}; 3956function gp(n, e, t) { 3957 !e && !Ih[n] && (Ih[n] = !0, jt(!1, t)); 3958} 3959var Dh = {}; 3960function Uh(n, e) { 3961 !n && !Dh[e] && (Dh[e] = !0, console.warn(e)); 3962} 3963var Z0 = "useOptimistic", Oh = yg[Z0], Q0 = () => { 3964}; 3965function ev(n) { 3966 return Oh ? Oh(n) : [n, Q0]; 3967} 3968function tv(n) { 3969 let e = { 3970 // Note: this check also occurs in createRoutesFromChildren so update 3971 // there if you change this -- please and thank you! 3972 hasErrorBoundary: n.hasErrorBoundary || n.ErrorBoundary != null || n.errorElement != null 3973 }; 3974 return n.Component && (n.element && jt( 3975 !1, 3976 "You should not include both `Component` and `element` on your route - `Component` will be used." 3977 ), Object.assign(e, { 3978 element: st(n.Component), 3979 Component: void 0 3980 })), n.HydrateFallback && (n.hydrateFallbackElement && jt( 3981 !1, 3982 "You should not include both `HydrateFallback` and `hydrateFallbackElement` on your route - `HydrateFallback` will be used." 3983 ), Object.assign(e, { 3984 hydrateFallbackElement: st(n.HydrateFallback), 3985 HydrateFallback: void 0 3986 })), n.ErrorBoundary && (n.errorElement && jt( 3987 !1, 3988 "You should not include both `ErrorBoundary` and `errorElement` on your route - `ErrorBoundary` will be used." 3989 ), Object.assign(e, { 3990 errorElement: st(n.ErrorBoundary), 3991 ErrorBoundary: void 0 3992 })), e; 3993} 3994var nv = [ 3995 "HydrateFallback", 3996 "hydrateFallbackElement" 3997], iv = class { 3998 constructor() { 3999 this.status = "pending", this.promise = new Promise((e, t) => { 4000 this.resolve = (i) => { 4001 this.status === "pending" && (this.status = "resolved", e(i)); 4002 }, this.reject = (i) => { 4003 this.status === "pending" && (this.status = "rejected", t(i)); 4004 }; 4005 }); 4006 } 4007}; 4008function kh({ 4009 router: n, 4010 flushSync: e, 4011 onError: t, 4012 unstable_useTransitions: i 4013}) { 4014 i = L0() || i; 4015 let [s, a] = Xe(n.state), [l, o] = ev(s), [c, u] = Xe(), [h, d] = Xe({ 4016 isTransitioning: !1 4017 }), [f, p] = Xe(), [v, m] = Xe(), [g, _] = Xe(), x = mt(/* @__PURE__ */ new Map()), E = Gn( 4018 (y, { deletedFetchers: M, newErrors: L, flushSync: C, viewTransitionOpts: U }) => {
4019 L && t && Object.values(L).forEach( 4020 (F) => t(F, { 4021 location: y.location, 4022 params: y.matches[0]?.params ?? {}, 4023 unstable_pattern: _a(y.matches) 4024 }) 4025 ), y.fetchers.forEach((F, I) => { 4026 F.data !== void 0 && x.current.set(I, F.data); 4027 }), M.forEach((F) => x.current.delete(F)), Uh( 4028 C === !1 || e != null, 4029 'You provided the `flushSync` option to a router update, but you are not using the `<RouterProvider>` from `react-router/dom` so `ReactDOM.flushSync()` is unavailable. Please update your app to `import { RouterProvider } from "react-router/dom"` and ensure you have `react-dom` installed as a dependency to use the `flushSync` option.' 4030 ); 4031 let V = n.window != null && n.window.document != null && typeof n.window.document.startViewTransition == "function"; 4032 if (Uh( 4033 U == null || V, 4034 "You provided the `viewTransition` option to a router update, but you do not appear to be running in a DOM environment as `window.startViewTransition` is not available." 4035 ), !U || !V) { 4036 e && C ? e(() => a(y)) : i === !1 ? a(y) : na(() => { 4037 i === !0 && o((F) => Fh(F, y)), a(y); 4038 }); 4039 return; 4040 } 4041 if (e && C) { 4042 e(() => { 4043 v && (f?.resolve(), v.skipTransition()), d({ 4044 isTransitioning: !0, 4045 flushSync: !0, 4046 currentLocation: U.currentLocation, 4047 nextLocation: U.nextLocation 4048 }); 4049 }); 4050 let F = n.window.document.startViewTransition(() => { 4051 e(() => a(y)); 4052 }); 4053 F.finished.finally(() => { 4054 e(() => { 4055 p(void 0), m(void 0), u(void 0), d({ isTransitioning: !1 }); 4056 }); 4057 }), e(() => m(F)); 4058 return; 4059 } 4060 v ? (f?.resolve(), v.skipTransition(), _({ 4061 state: y, 4062 currentLocation: U.currentLocation, 4063 nextLocation: U.nextLocation 4064 })) : (u(y), d({ 4065 isTransitioning: !0, 4066 flushSync: !1, 4067 currentLocation: U.currentLocation, 4068 nextLocation: U.nextLocation 4069 })); 4070 }, 4071 [ 4072 n.window, 4073 e, 4074 v, 4075 f, 4076 i, 4077 o, 4078 t 4079 ] 4080 ); 4081 vu(() => n.subscribe(E), [n, E]), bt(() => { 4082 h.isTransitioning && !h.flushSync && p(new iv()); 4083 }, [h]), bt(() => { 4084 if (f && c && n.window) { 4085 let y = c, M = f.promise, L = n.window.document.startViewTransition(async () => { 4086 i === !1 ? a(y) : na(() => { 4087 i === !0 && o((C) => Fh(C, y)), a(y); 4088 }), await M; 4089 }); 4090 L.finished.finally(() => { 4091 p(void 0), m(void 0), u(void 0), d({ isTransitioning: !1 }); 4092 }), m(L); 4093 } 4094 }, [ 4095 c, 4096 f, 4097 n.window, 4098 i, 4099 o 4100 ]), bt(() => { 4101 f && c && l.location.key === c.location.key && f.resolve(); 4102 }, [f, v, l.location, c]), bt(() => { 4103 !h.isTransitioning && g && (u(g.state), d({ 4104 isTransitioning: !0, 4105 flushSync: !1, 4106 currentLocation: g.currentLocation, 4107 nextLocation: g.nextLocation 4108 }), _(void 0)); 4109 }, [h.isTransitioning, g]); 4110 let R = Nn(() => ({ 4111 createHref: n.createHref, 4112 encodeLocation: n.encodeLocation, 4113 go: (y) => n.navigate(y), 4114 push: (y, M, L) => n.navigate(y, { 4115 state: M, 4116 preventScrollReset: L?.preventScrollReset 4117 }), 4118 replace: (y, M, L) => n.navigate(y, { 4119 replace: !0, 4120 state: M, 4121 preventScrollReset: L?.preventScrollReset 4122 }) 4123 }), [n]), T = n.basename || "/", w = Nn( 4124 () => ({ 4125 router: n, 4126 navigator: R, 4127 static: !1, 4128 basename: T, 4129 onError: t 4130 }), 4131 [n, R, T, t] 4132 ); 4133 return /* @__PURE__ */ st(ps, null, /* @__PURE__ */ st(Nr.Provider, { value: w }, /* @__PURE__ */ st(ya.Provider, { value: l }, /* @__PURE__ */ st(hp.Provider, { value: x.current }, /* @__PURE__ */ st(Eu.Provider, { value: h }, /* @__PURE__ */ st( 4134 av, 4135 { 4136 basename: T, 4137 location: l.location, 4138 navigationType: l.historyAction, 4139 navigator: R, 4140 unstable_useTransitions: i 4141 }, 4142 /* @__PURE__ */ st( 4143 rv, 4144 { 4145 routes: n.routes, 4146 future: n.future, 4147 state: l, 4148 onError: t 4149 } 4150 ) 4151 ))))), null); 4152} 4153function Fh(n, e) { 4154 return { 4155 // Don't surface "current location specific" stuff mid-navigation 4156 // (historyAction, location, matches, loaderData, errors, initialized, 4157 // restoreScroll, preventScrollReset, blockers, etc.) 4158 ...n, 4159 // Only surface "pending/in-flight stuff" 4160 // (navigation, revalidation, actionData, fetchers, ) 4161 navigation: e.navigation.state !== "idle" ? e.navigation : n.navigation,
4162 revalidation: e.revalidation !== "idle" ? e.revalidation : n.revalidation, 4163 actionData: e.navigation.state !== "submitting" ? e.actionData : n.actionData, 4164 fetchers: e.fetchers 4165 }; 4166} 4167var rv = Wf(sv); 4168function sv({ 4169 routes: n, 4170 future: e, 4171 state: t, 4172 onError: i 4173}) { 4174 return z0(n, void 0, t, i, e); 4175} 4176function av({ 4177 basename: n = "/", 4178 children: e = null, 4179 location: t, 4180 navigationType: i = "POP", 4181 navigator: r, 4182 static: s = !1, 4183 unstable_useTransitions: a 4184}) { 4185 ht( 4186 !xa(), 4187 "You cannot render a <Router> inside another <Router>. You should never have more than one in your app." 4188 ); 4189 let l = n.replace(/^\/*/, "/"), o = Nn( 4190 () => ({ 4191 basename: l, 4192 navigator: r, 4193 static: s, 4194 unstable_useTransitions: a, 4195 future: {} 4196 }), 4197 [l, r, s, a] 4198 ); 4199 typeof t == "string" && (t = cr(t)); 4200 let { 4201 pathname: c = "/", 4202 search: u = "", 4203 hash: h = "", 4204 state: d = null, 4205 key: f = "default" 4206 } = t, p = Nn(() => { 4207 let v = Vn(c, l); 4208 return v == null ? null : { 4209 location: { 4210 pathname: v, 4211 search: u, 4212 hash: h, 4213 state: d, 4214 key: f 4215 }, 4216 navigationType: i 4217 }; 4218 }, [l, c, u, h, d, f, i]); 4219 return jt( 4220 p != null, 4221 `<Router basename="${l}"> is not able to match the URL "${c}${u}${h}" because it does not start with the basename, so the <Router> won't render anything.` 4222 ), p == null ? null : /* @__PURE__ */ st(jn.Provider, { value: o }, /* @__PURE__ */ st(Vo.Provider, { children: e, value: p })); 4223} 4224var go = "get", vo = "application/x-www-form-urlencoded"; 4225function Wo(n) { 4226 return typeof HTMLElement < "u" && n instanceof HTMLElement; 4227} 4228function ov(n) { 4229 return Wo(n) && n.tagName.toLowerCase() === "button"; 4230} 4231function lv(n) { 4232 return Wo(n) && n.tagName.toLowerCase() === "form"; 4233} 4234function cv(n) { 4235 return Wo(n) && n.tagName.toLowerCase() === "input"; 4236} 4237function uv(n) { 4238 return !!(n.metaKey || n.altKey || n.ctrlKey || n.shiftKey); 4239} 4240function hv(n, e) { 4241 return n.button === 0 && // Ignore everything but left clicks 4242 (!e || e === "_self") && // Let browser handle "target=_blank" etc. 4243 !uv(n); 4244} 4245function ac(n = "") { 4246 return new URLSearchParams( 4247 typeof n == "string" || Array.isArray(n) || n instanceof URLSearchParams ? n : Object.keys(n).reduce((e, t) => { 4248 let i = n[t]; 4249 return e.concat( 4250 Array.isArray(i) ? i.map((r) => [t, r]) : [[t, i]] 4251 ); 4252 }, []) 4253 ); 4254} 4255function dv(n, e) { 4256 let t = ac(n); 4257 return e && e.forEach((i, r) => { 4258 t.has(r) || e.getAll(r).forEach((s) => { 4259 t.append(r, s); 4260 }); 4261 }), t; 4262} 4263var La = null; 4264function fv() { 4265 if (La === null) 4266 try { 4267 new FormData( 4268 document.createElement("form"), 4269 // @ts-expect-error if FormData supports the submitter parameter, this will throw 4270 0 4271 ), La = !1; 4272 } catch { 4273 La = !0; 4274 } 4275 return La; 4276} 4277var pv = /* @__PURE__ */ new Set([ 4278 "application/x-www-form-urlencoded", 4279 "multipart/form-data", 4280 "text/plain" 4281]); 4282function cl(n) { 4283 return n != null && !pv.has(n) ? (jt( 4284 !1, 4285 `"${n}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${vo}"` 4286 ), null) : n; 4287} 4288function mv(n, e) { 4289 let t, i, r, s, a; 4290 if (lv(n)) { 4291 let l = n.getAttribute("action"); 4292 i = l ? Vn(l, e) : null, t = n.getAttribute("method") || go, r = cl(n.getAttribute("enctype")) || vo, s = new FormData(n); 4293 } else if (ov(n) || cv(n) && (n.type === "submit" || n.type === "image")) { 4294 let l = n.form; 4295 if (l == null) 4296 throw new Error( 4297 'Cannot submit a <button> or <input type="submit"> without a <form>' 4298 ); 4299 let o = n.getAttribute("formaction") || l.getAttribute("action"); 4300 if (i = o ? Vn(o, e) : null, t = n.getAttribute("formmethod") || l.getAttribute("method") || go, r = cl(n.getAttribute("formenctype")) || cl(l.getAttribute("enctype")) || vo, s = new FormData(l, n), !fv()) { 4301 let { name: c, type: u, value: h } = n; 4302 if (u === "image") { 4303 let d = c ? `${c}.` : ""; 4304 s.append(`${d}x`, "0"), s.append(`${d}y`, "0"); 4305 } else c && s.append(c, h); 4306 } 4307 } else { 4308 if (Wo(n)) 4309 throw new Error( 4310 'Cannot submit element that is not <form>, <button>, or <input type="submit|image">' 4311 ); 4312 t = go, i = null, r = vo, a = n; 4313 } 4314 return s && r === "text/plain" && (a = s, s = void 0), { action: i, method: t.toLowerCase(), encType: r, formData: s, body: a }; 4315} 4316Object.getOwnPropertyNames(Object.prototype).sort().join("\0"); 4317function Ru(n, e) { 4318 if (n === !1 || n === null || typeof n > "u") 4319 throw new Error(e); 4320}
4321function gv(n, e, t, i) { 4322 let r = typeof n == "string" ? new URL( 4323 n, 4324 // This can be called during the SSR flow via PrefetchPageLinksImpl so 4325 // don't assume window is available 4326 typeof window > "u" ? "server://singlefetch/" : window.location.origin 4327 ) : n; 4328 return t ? r.pathname.endsWith("/") ? r.pathname = `${r.pathname}_.${i}` : r.pathname = `${r.pathname}.${i}` : r.pathname === "/" ? r.pathname = `_root.${i}` : e && Vn(r.pathname, e) === "/" ? r.pathname = `${e.replace(/\/$/, "")}/_root.${i}` : r.pathname = `${r.pathname.replace(/\/$/, "")}.${i}`, r; 4329} 4330async function vv(n, e) { 4331 if (n.id in e) 4332 return e[n.id]; 4333 try { 4334 let t = await import( 4335 /* @vite-ignore */ 4336 /* webpackIgnore: true */ 4337 n.module 4338 ); 4339 return e[n.id] = t, t; 4340 } catch (t) { 4341 return console.error( 4342 `Error loading route module \`${n.module}\`, reloading page...` 4343 ), console.error(t), window.__reactRouterContext && window.__reactRouterContext.isSpaMode, window.location.reload(), new Promise(() => { 4344 }); 4345 } 4346} 4347function _v(n) { 4348 return n == null ? !1 : n.href == null ? n.rel === "preload" && typeof n.imageSrcSet == "string" && typeof n.imageSizes == "string" : typeof n.rel == "string" && typeof n.href == "string"; 4349} 4350async function yv(n, e, t) { 4351 let i = await Promise.all( 4352 n.map(async (r) => { 4353 let s = e.routes[r.route.id]; 4354 if (s) { 4355 let a = await vv(s, t); 4356 return a.links ? a.links() : []; 4357 } 4358 return []; 4359 }) 4360 ); 4361 return Sv( 4362 i.flat(1).filter(_v).filter((r) => r.rel === "stylesheet" || r.rel === "preload").map( 4363 (r) => r.rel === "stylesheet" ? { ...r, rel: "prefetch", as: "style" }
vendor: 4,635 bytes, lines 4363-4544
4363 : { ...r, rel: "prefetch" } 4364 ) 4365 ); 4366} 4367function Bh(n, e, t, i, r, s) { 4368 let a = (o, c) => t[c] ? o.route.id !== t[c].route.id : !0, l = (o, c) => ( 4369 // param change, /users/123 -> /users/456 4370 t[c].pathname !== o.pathname || // splat param changed, which is not present in match.path 4371 // e.g. /files/images/avatar.jpg -> files/finances.xls 4372 t[c].route.path?.endsWith("*") && t[c].params["*"] !== o.params["*"] 4373 ); 4374 return s === "assets" ? e.filter( 4375 (o, c) => a(o, c) || l(o, c) 4376 ) : s === "data" ? e.filter((o, c) => { 4377 let u = i.routes[o.route.id]; 4378 if (!u || !u.hasLoader) 4379 return !1; 4380 if (a(o, c) || l(o, c)) 4381 return !0; 4382 if (o.route.shouldRevalidate) { 4383 let h = o.route.shouldRevalidate({ 4384 currentUrl: new URL( 4385 r.pathname + r.search + r.hash, 4386 window.origin 4387 ), 4388 currentParams: t[0]?.params || {}, 4389 nextUrl: new URL(n, window.origin), 4390 nextParams: o.params, 4391 defaultShouldRevalidate: !0 4392 }); 4393 if (typeof h == "boolean") 4394 return h; 4395 } 4396 return !0; 4397 }) : []; 4398} 4399function xv(n, e, { includeHydrateFallback: t } = {}) { 4400 return bv( 4401 n.map((i) => { 4402 let r = e.routes[i.route.id]; 4403 if (!r) return []; 4404 let s = [r.module]; 4405 return r.clientActionModule && (s = s.concat(r.clientActionModule)), r.clientLoaderModule && (s = s.concat(r.clientLoaderModule)), t && r.hydrateFallbackModule && (s = s.concat(r.hydrateFallbackModule)), r.imports && (s = s.concat(r.imports)), s; 4406 }).flat(1) 4407 ); 4408} 4409function bv(n) { 4410 return [...new Set(n)]; 4411} 4412function wv(n) { 4413 let e = {}, t = Object.keys(n).sort(); 4414 for (let i of t) 4415 e[i] = n[i]; 4416 return e; 4417} 4418function Sv(n, e) { 4419 let t = /* @__PURE__ */ new Set(); 4420 return new Set(e), n.reduce((i, r) => { 4421 let s = JSON.stringify(wv(r)); 4422 return t.has(s) || (t.add(s), i.push({ key: s, link: r })), i; 4423 }, []); 4424} 4425function vp() { 4426 let n = Mt(Nr); 4427 return Ru( 4428 n, 4429 "You must render this element inside a <DataRouterContext.Provider> element" 4430 ), n; 4431} 4432function Ev() { 4433 let n = Mt(ya); 4434 return Ru( 4435 n, 4436 "You must render this element inside a <DataRouterStateContext.Provider> element" 4437 ), n; 4438} 4439var Cu = Un(void 0); 4440Cu.displayName = "FrameworkContext"; 4441function _p() { 4442 let n = Mt(Cu); 4443 return Ru( 4444 n, 4445 "You must render this element inside a <HydratedRouter> element" 4446 ), n; 4447} 4448function Mv(n, e) { 4449 let t = Mt(Cu), [i, r] = Xe(!1), [s, a] = Xe(!1), { onFocus: l, onBlur: o, onMouseEnter: c, onMouseLeave: u, onTouchStart: h } = e, d = mt(null); 4450 bt(() => { 4451 if (n === "render" && a(!0), n === "viewport") { 4452 let v = (g) => { 4453 g.forEach((_) => { 4454 a(_.isIntersecting); 4455 }); 4456 }, m = new IntersectionObserver(v, { threshold: 0.5 }); 4457 return d.current && m.observe(d.current), () => { 4458 m.disconnect(); 4459 }; 4460 } 4461 }, [n]), bt(() => { 4462 if (i) { 4463 let v = setTimeout(() => { 4464 a(!0); 4465 }, 100); 4466 return () => { 4467 clearTimeout(v); 4468 }; 4469 } 4470 }, [i]); 4471 let f = () => { 4472 r(!0); 4473 }, p = () => { 4474 r(!1), a(!1); 4475 }; 4476 return t ? n !== "intent" ? [s, d, {}] : [ 4477 s, 4478 d, 4479 { 4480 onFocus: Ns(l, f), 4481 onBlur: Ns(o, p), 4482 onMouseEnter: Ns(c, f), 4483 onMouseLeave: Ns(u, p), 4484 onTouchStart: Ns(h, f) 4485 } 4486 ] : [!1, d, {}]; 4487} 4488function Ns(n, e) { 4489 return (t) => { 4490 n && n(t), t.defaultPrevented || e(t); 4491 }; 4492} 4493function Tv({ page: n, ...e }) { 4494 let { router: t } = vp(), i = Nn( 4495 () => Yi(t.routes, n, t.basename), 4496 [t.routes, n, t.basename] 4497 ); 4498 return i ? /* @__PURE__ */ st(Rv, { page: n, matches: i, ...e }) : null; 4499} 4500function Av(n) { 4501 let { manifest: e, routeModules: t } = _p(), [i, r] = Xe([]); 4502 return bt(() => { 4503 let s = !1; 4504 return yv(n, e, t).then( 4505 (a) => { 4506 s || r(a); 4507 } 4508 ), () => { 4509 s = !0; 4510 }; 4511 }, [n, e, t]), i; 4512} 4513function Rv({ 4514 page: n, 4515 matches: e, 4516 ...t 4517}) { 4518 let i = ur(), { future: r, manifest: s, routeModules: a } = _p(), { basename: l } = vp(), { loaderData: o, matches: c } = Ev(), u = Nn( 4519 () => Bh( 4520 n, 4521 e, 4522 c, 4523 s, 4524 i, 4525 "data" 4526 ), 4527 [n, e, c, s, i] 4528 ), h = Nn( 4529 () => Bh( 4530 n, 4531 e, 4532 c, 4533 s, 4534 i, 4535 "assets" 4536 ), 4537 [n, e, c, s, i] 4538 ), d = Nn(() => { 4539 if (n === i.pathname + i.search + i.hash) 4540 return []; 4541 let v = /* @__PURE__ */ new Set(), m = !1; 4542 if (e.forEach((_) => { 4543 let x = s.routes[_.route.id]; 4544 !x || !x.hasLoader || (!u.some((E) => E.route.id === _.route.id) && _.route.id in o && a[_.route.id]?.shouldRevalidate || x.hasCl
4544ientLoader ? m = !0 : v.add(_.route.id)); 4545 }), v.size === 0) 4546 return []; 4547 let g = gv( 4548 n, 4549 l, 4550 r.unstable_trailingSlashAwareDataRequests, 4551 "data" 4552 ); 4553 return m && v.size > 0 && g.searchParams.set( 4554 "_routes", 4555 e.filter((_) => v.has(_.route.id)).map((_) => _.route.id).join(",") 4556 ), [g.pathname + g.search]; 4557 }, [ 4558 l, 4559 r.unstable_trailingSlashAwareDataRequests, 4560 o, 4561 i, 4562 s, 4563 u, 4564 e, 4565 n, 4566 a 4567 ]), f = Nn( 4568 () => xv(h, s), 4569 [h, s] 4570 ), p = Av(h); 4571 return /* @__PURE__ */ st(ps, null, d.map((v) => /* @__PURE__ */ st("link", { key: v, rel: "prefetch", as: "fetch", href: v, ...t })), f.map((v) => /* @__PURE__ */ st("link", { key: v, rel: "modulepreload", href: v, ...t })), p.map(({ key: v, link: m }) => ( 4572 // these don't spread `linkProps` because they are full link descriptors 4573 // already with their own props 4574 /* @__PURE__ */ st( 4575 "link", 4576 { 4577 key: v, 4578 nonce: t.nonce, 4579 ...m, 4580 crossOrigin: m.crossOrigin ?? t.crossOrigin 4581 } 4582 ) 4583 ))); 4584} 4585function Cv(...n) { 4586 return (e) => {
4587 n.forEach((t) => { 4588 typeof t == "function" ? t(e) : t != null && (t.current = e); 4589 }); 4590 }; 4591} 4592var Pv = typeof window < "u" && typeof window.document < "u" && typeof window.document.createElement < "u"; 4593try { 4594 Pv && (window.__reactRouterVersion = // @ts-expect-error 4595 "7.13.0"); 4596} catch { 4597} 4598function Lv(n, e) { 4599 return a0({ 4600 basename: e?.basename, 4601 getContext: e?.getContext, 4602 future: e?.future, 4603 history: wg({ window: e?.window }), 4604 hydrationData: Nv(), 4605 routes: n, 4606 mapRouteProperties: tv, 4607 hydrationRouteProperties: nv, 4608 dataStrategy: e?.dataStrategy, 4609 patchRoutesOnNavigation: e?.patchRoutesOnNavigation, 4610 window: e?.window, 4611 unstable_instrumentations: e?.unstable_instrumentations 4612 }).initialize(); 4613} 4614function Nv() { 4615 let n = window?.__staticRouterHydrationData; 4616 return n && n.errors && (n = { 4617 ...n, 4618 errors: Iv(n.errors) 4619 }), n; 4620} 4621function Iv(n) { 4622 if (!n) return null; 4623 let e = Object.entries(n), t = {}; 4624 for (let [i, r] of e) 4625 if (r && r.__type === "RouteErrorResponse") 4626 t[i] = new va( 4627 r.status, 4628 r.statusText, 4629 r.data, 4630 r.internal === !0 4631 ); 4632 else if (r && r.__type === "Error") { 4633 if (r.__subType) { 4634 let s = window[r.__subType]; 4635 if (typeof s == "function") 4636 try { 4637 let a = new s(r.message); 4638 a.stack = "", t[i] = a; 4639 } catch { 4640 } 4641 } 4642 if (t[i] == null) { 4643 let s = new Error(r.message); 4644 s.stack = "", t[i] = s; 4645 } 4646 } else 4647 t[i] = r; 4648 return t; 4649} 4650var yp = /^(?:[a-z][a-z0-9+.-]*:|\/\/)/i, Pu = ws( 4651 function({ 4652 onClick: e, 4653 discover: t = "render", 4654 prefetch: i = "none", 4655 relative: r, 4656 reloadDocument: s, 4657 replace: a, 4658 state: l, 4659 target: o, 4660 to: c, 4661 preventScrollReset: u, 4662 viewTransition: h, 4663 unstable_defaultShouldRevalidate: d, 4664 ...f 4665 }, p) { 4666 let { basename: v, unstable_useTransitions: m } = Mt(jn), g = typeof c == "string" && yp.test(c), _ = Zf(c, v); 4667 c = _.to; 4668 let x = k0(c, { relative: r }), [E, R, T] = Mv( 4669 i, 4670 f 4671 ), w = kv(c, { 4672 replace: a, 4673 state: l, 4674 target: o, 4675 preventScrollReset: u, 4676 relative: r, 4677 viewTransition: h, 4678 unstable_defaultShouldRevalidate: d, 4679 unstable_useTransitions: m 4680 }); 4681 function y(L) { 4682 e && e(L), L.defaultPrevented || w(L); 4683 } 4684 let M = ( 4685 // eslint-disable-next-line jsx-a11y/anchor-has-content
4686 /* @__PURE__ */ st( 4687 "a", 4688 { 4689 ...f, 4690 ...T, 4691 href: _.absoluteURL || x, 4692 onClick: _.isExternal || s ? e : y, 4693 ref: Cv(p, R), 4694 target: o, 4695 "data-discover": !g && t === "render" ? "true" : void 0 4696 } 4697 ) 4698 ); 4699 return E && !g ? /* @__PURE__ */ st(ps, null, M, /* @__PURE__ */ st(Tv, { page: x })) : M; 4700 } 4701); 4702Pu.displayName = "Link"; 4703var Dv = ws( 4704 function({ 4705 "aria-current": e = "page", 4706 caseSensitive: t = !1, 4707 className: i = "", 4708 end: r = !1, 4709 style: s, 4710 to: a, 4711 viewTransition: l, 4712 children: o, 4713 ...c 4714 }, u) { 4715 let h = ba(a, { relative: c.relative }), d = ur(), f = Mt(ya), { navigator: p, basename: v } = Mt(jn), m = f != null && // Conditional usage is OK here because the usage of a data router is static 4716 // eslint-disable-next-line react-hooks/rules-of-hooks 4717 Vv(h) && l === !0, g = p.encodeLocation ? p.encodeLocation(h).pathname : h.pathname, _ = d.pathname, x = f && f.navigation && f.navigation.location ? f.navigation.location.pathname : null; 4718 t || (_ = _.toLowerCase(), x = x ? x.toLowerCase() : null, g = g.toLowerCase()), x && v && (x = Vn(x, v) || x); 4719 const E = g !== "/" && g.endsWith("/") ? g.length - 1 : g.length; 4720 let R = _ === g || !r && _.startsWith(g) && _.charAt(E) === "/", T = x != null && (x === g || !r && x.startsWith(g) && x.charAt(g.length) === "/"), w = { 4721 isActive: R, 4722 isPending: T, 4723 isTransitioning: m 4724 }, y = R ? e : void 0, M; 4725 typeof i == "function" ? M = i(w) : M = [ 4726 i, 4727 R ? "active" : null, 4728 T ? "pending" : null, 4729 m ? "transitioning" : null 4730 ].filter(Boolean).join(" "); 4731 let L = typeof s == "function" ? s(w) : s; 4732 return /* @__PURE__ */ st( 4733 Pu, 4734 { 4735 ...c, 4736 "aria-current": y, 4737 className: M, 4738 ref: u, 4739 style: L, 4740 to: a, 4741 viewTransition: l 4742 }, 4743 typeof o == "function" ? o(w) : o 4744 ); 4745 } 4746); 4747Dv.displayName = "NavLink"; 4748var Uv = ws( 4749 ({ 4750 discover: n = "render", 4751 fetcherKey: e, 4752 navigate: t, 4753 reloadDocument: i, 4754 replace: r, 4755 state: s, 4756 method: a = go, 4757 action: l, 4758 onSubmit: o, 4759 relative: c, 4760 preventScrollReset: u, 4761 viewTransition: h, 4762 unstable_defaultShouldRevalidate: d, 4763 ...f 4764 }, p) => { 4765 let { unstable_useTransitions: v } = Mt(jn), m = Hv(), g = Gv(l, { relative: c }), _ = a.toLowerCase() === "get" ? "get" : "post", x = typeof l == "string" && yp.test(l); 4766 return /* @__PURE__ */ st( 4767 "form", 4768 { 4769 ref: p, 4770 method: _, 4771 action: g, 4772 onSubmit: i ? o : (R) => { 4773 if (o && o(R), R.defaultPrevented) return; 4774 R.preventDefault(); 4775 let T = R.nativeEvent.submitter, w = T?.getAttribute("formmethod") || a, y = () => m(T || R.currentTarget, { 4776 fetcherKey: e, 4777 method: w, 4778 navigate: t, 4779 replace: r, 4780 state: s, 4781 relative: c, 4782 preventScrollReset: u, 4783 viewTransition: h, 4784 unstable_defaultShouldRevalidate: d 4785 }); 4786 v && t !== !1 ? na(() => y()) : y(); 4787 }, 4788 ...f, 4789 "data-discover": !x && n === "render" ? "true" : void 0 4790 } 4791 ); 4792 } 4793); 4794Uv.displayName = "Form"; 4795function Ov(n) { 4796 return `${n} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`; 4797} 4798function xp(n) { 4799 let e = Mt(Nr); 4800 return ht(e, Ov(n)), e; 4801} 4802function kv(n, { 4803 target: e, 4804 replace: t, 4805 state: i, 4806 preventScrollReset: r, 4807 relative: s, 4808 viewTransition: a, 4809 unstable_defaultShouldRevalidate: l, 4810 unstable_useTransitions: o 4811} = {}) { 4812 let c = hr(), u = ur(), h = ba(n, { relative: s }); 4813 return Gn( 4814 (d) => { 4815 if (hv(d, e)) { 4816 d.preventDefault(); 4817 let f = t !== void 0 ? t : mi(u) === mi(h), p = () => c(n, { 4818 replace: f, 4819 state: i, 4820 preventScrollReset: r, 4821 relative: s, 4822 viewTransition: a, 4823 unstable_defaultShouldRevalidate: l 4824 }); 4825 o ? na(() => p()) : p(); 4826 } 4827 }, 4828 [ 4829 u, 4830 c, 4831 h, 4832 t, 4833 i, 4834 e, 4835 n, 4836 r, 4837 s, 4838 a, 4839 l, 4840 o 4841 ] 4842 ); 4843} 4844function Fv(n) { 4845 jt( 4846 typeof URLSearchParams < "u", 4847 "You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params." 4848 ); 4849 let e = mt(ac(n)), t = mt(!1), i = ur(), r = Nn( 4850 () => ( 4851 // Only merge in the defaults if we haven't yet called setSearchParams. 4852 // Once we call that we want those to take precedence, otherwise you can't 4853 // remove a param with setSearchParams({}) if it has an initial value 4854 dv( 4855 i.search, 4856 t.current ? null : e.current 4857 ) 4858 ), 4859 [i.search] 4860 ), s = hr(), a = Gn( 4861 (l, o) => { 4862 const c = ac( 4863 typeof l == "function" ? l(new URLSearchParams(r)) : l 4864 ); 4865 t.current = !0, s("?" + c, o); 4866 }, 4867 [s, r] 4868 ); 4869 return [r, a]; 4870} 4871var Bv = 0, zv = () => `__${String(++Bv)}__`; 4872function Hv() { 4873 let { router: n } = xp( 4874 "useSubmit" 4875 /* UseSubmit */ 4876 ), { basename: e } = Mt(jn), t = Y0(), i = n.fetch, r = n.navigate; 4877 return Gn( 4878 async (s, a = {}) => { 4879 let { action: l, method: o, encType: c, formData: u, body: h } = mv( 4880 s, 4881 e 4882 ); 4883 if (a.navigate === !1) { 4884 let d = a.fetcherKey || zv(); 4885 await i(d, t, a.action || l, { 4886 unstable_defaultShouldRevalidate: a.unstable_defaultShouldRevalidate, 4887 preventScrollReset: a.preventScrollReset, 4888 formData: u, 4889 body: h, 4890 formMethod: a.method || o, 4891 formEncType: a.encType || c, 4892 flushSync: a.flushSync 4893 }); 4894 } else 4895 await r(a.action || l, { 4896 unstable_defaultShouldRevalidate: a.unstable_defaultShouldRevalidate, 4897 preventScrollReset: a.preventScrollReset, 4898 formData: u, 4899 body: h, 4900 formMethod: a.method || o, 4901 formEncType: a.encType || c, 4902 replace: a.replace, 4903 state: a.state, 4904 fromRouteId: t, 4905 flushSync: a.flushSync, 4906 viewTransition: a.viewTransition 4907 }); 4908 }, 4909 [i, r, e, t] 4910 ); 4911} 4912function Gv(n, { relative: e } = {}) { 4913 let { basename: t } = Mt(jn), i = Mt(vi); 4914 ht(i, "useFormAction must be used inside a RouteContext"); 4915 let [r] = i.matches.slice(-1), s = { ...ba(n || ".", { relative: e }) }, a = ur(); 4916 if (n == null) { 4917 s.search = a.search; 4918 let l = new URLSearchParams(s.search), o = l.getAll("index"); 4919 if (o.some((u) => u === "")) { 4920 l.delete("index"), o.filter((h) =>
vendor: 1,553 bytes, lines 4920-4947
4920 h).forEach((h) => l.append("index", h)); 4921 let u = l.toString(); 4922 s.search = u ? `?${u}` : ""; 4923 } 4924 } 4925 return (!n || n === ".") && r.route.index && (s.search = s.search ? s.search.replace(/^\?/, "?index&") : "?index"), t !== "/" && (s.pathname = s.pathname === "/" ? t : hi([t, s.pathname])), mi(s); 4926} 4927function Vv(n, { relative: e } = {}) { 4928 let t = Mt(Eu); 4929 ht( 4930 t != null, 4931 "`useViewTransitionState` must be used within `react-router-dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?" 4932 ); 4933 let { basename: i } = xp( 4934 "useViewTransitionState" 4935 /* useViewTransitionState */ 4936 ), r = ba(n, { relative: e }); 4937 if (!t.isTransitioning) 4938 return !1; 4939 let s = Vn(t.currentLocation.pathname, i) || t.currentLocation.pathname, a = Vn(t.nextLocation.pathname, i) || t.nextLocation.pathname; 4940 return Ao(r.pathname, a) != null || Ao(r.pathname, s) != null; 4941} 4942/** 4943 * @license 4944 * Copyright 2010-2026 Three.js Authors 4945 * SPDX-License-Identifier: MIT 4946 */ 4947const Lu = "184", Wv = 0, zh = 1, $v = 2, _o = 1, jv = 2, js = 3, sr = 0, Mn = 1, Ni = 2, Ui = 0, hs = 1, oc = 2, Hh = 3, Gh = 4, Xv = 5, wr = 100, qv = 101, Yv = 102, Kv = 103, Jv = 104, Zv = 200, Qv = 201, e_ = 202, t_ = 203, lc = 204, cc = 205, n_ = 206, i_ = 207, r_ = 208, s_ = 209, a_ = 210, o_ = 211, l_ = 212, c_ = 213, u_ = 214, uc = 0, hc = 1, dc = 2, ms = 3, fc = 4, pc = 5, mc = 6, gc = 7, Nu = 0, h_ = 1, d_ = 2, di = 0, bp = 1, wp = 2, Sp = 3, Ep = 4, Mp = 5, Tp = 6, Ap = 7, Rp = 300, Cr = 301, gs = 302, ul = 303, hl = 3
494704, $o = 306, vc = 1e3, Di = 1001, _c = 1002, sn = 1003, f_ = 1004, Na = 1005, fn = 1006, dl = 1007, Mr = 1008, Pn = 1009, Cp = 1010, Pp = 1011, aa = 1012, Iu = 1013, gi = 1014, ti = 1015, ki = 1016, Du = 1017, Uu = 1018, oa = 1020, Lp = 35902, Np = 35899, Ip = 1021, Dp = 1022, ni = 1023, Fi = 1026, Tr = 1027, Ou = 1028, ku = 1029, Pr = 1030, Fu = 1031, Bu = 1033, yo = 33776, xo = 33777, bo = 33778, wo = 33779, yc = 35840, xc = 35841, bc = 35842, wc = 35843, Sc = 36196, Ec = 37492, Mc = 37496, Tc = 37488, Ac = 37489, Ro = 37490, Rc = 37491, Cc = 37808, Pc = 37809, Lc = 37810, Nc = 37811, Ic = 37812, Dc = 37813, Uc = 37814, Oc = 37815, kc = 37816, Fc = 37817, Bc = 37818, zc = 37819, Hc = 37820, Gc = 37821, Vc = 36492, Wc = 36494, $c = 36495, jc = 36283, Xc = 36284, Co = 36285, qc = 36286, p_ = 3200, Yc = 0, m_ = 1, Ji = "", Hn = "srgb", Po = "srgb-linear", Lo = "linear", Nt = "srgb", kr = 7680, Vh = 519, g_ = 512, v_ = 513, __ = 514, zu = 515, y_ = 516, x_ = 517, Hu = 518, b_ = 519, Wh = 35044, $h = "300 es", ui = 2e3, la = 2001; 4948function w_(n) { 4949 for (let e = n.length - 1; e >= 0; --e) 4950 if (n[e] >= 65535) return !0; 4951 return !1; 4952} 4953function No(n) { 4954 return document.createElementNS("http://www.w3.org/1999/xhtml", n); 4955} 4956function S_() { 4957 const n = No("canvas"); 4958 return n.style.display = "block", n; 4959} 4960const jh = {}; 4961function Xh(...n) { 4962 const e = "THREE." + n.shift(); 4963 console.log(e, ...n); 4964} 4965function Up(n) { 4966 const e = n[0]; 4967 if (typeof e == "string" && e.startsWith("TSL:")) { 4968 const t = n[1]; 4969 t && t.isStackTrace ? n[0] += " " + t.getLocation() : n[1] = 'Stack trace not available. Enable "THREE.Node.captureStackTrace" to capture stack traces.'; 4970 } 4971 return n; 4972} 4973function tt(...n) { 4974 n = Up(n); 4975 const e = "THREE." + n.shift(); 4976 { 4977 const t = n[0]; 4978 t && t.isStackTrace ? console.warn(t.getError(e)) : console.warn(e, ...n); 4979 } 4980} 4981function xt(...n) { 4982 n = Up(n); 4983 const e = "THREE." + n.shift(); 4984 { 4985 const t = n[0]; 4986 t && t.isStackTrace ? console.error(t.getError(e)) : console.error(e, ...n); 4987 } 4988} 4989function Kc(...n) { 4990 const e = n.join(" "); 4991 e in jh || (jh[e] = !0, tt(...n)); 4992} 4993function E_(n, e, t) { 4994 return new Promise(function(i, r) { 4995 function s() { 4996 switch (n.clientWaitSync(e, n.SYNC_FLUSH_COMMANDS_BIT, 0)) { 4997 case n.WAIT_FAILED: 4998 r(); 4999 break; 5000 case n.TIMEOUT_EXPIRED: 5001 setTimeout(s, t); 5002 break; 5003 default: 5004 i(); 5005 } 5006 } 5007 setTimeout(s, t); 5008 }); 5009} 5010const M_ = { 5011 [uc]: hc, 5012 [dc]: mc, 5013 [fc]: gc, 5014 [ms]: pc, 5015 [hc]: uc, 5016 [mc]: dc, 5017 [gc]: fc, 5018 [pc]: ms 5019}; 5020class Ir { 5021 /** 5022 * Adds the given event listener to the given event type. 5023 * 5024 * @param {string} type - The type of event to listen to. 5025 * @param {Function} listener - The function that gets called when the event is fired. 5026 */ 5027 addEventListener(e, t) { 5028 this._listeners === void 0 && (this._listeners = {}); 5029 const i = this._listeners; 5030 i[e] === void 0 && (i[e] = []), i[e].indexOf(t) === -1 && i[e].push(t); 5031 } 5032 /** 5033 * Returns `true` if the given event listener has been added to the given event type. 5034 * 5035 * @param {string} type - The type of event. 5036 * @param {Function} listener - The listener to check. 5037 * @return {boolean} Whether the given event listener has been added to the given event type. 5038 */ 5039 hasEventListener(e, t) { 5040 const i = this._listeners; 5041 return i === void 0 ? !1 : i[e] !== void 0 && i[e].indexOf(t) !== -1; 5042 } 5043 /** 5044 * Removes the given event listener from the given event type. 5045 * 5046 * @param {string} type - The type of event. 5047 * @param {Function} listener - The listener to remove. 5048 */ 5049 removeEventListener(e, t) { 5050 const i = this._listeners; 5051 if (i === void 0) return; 5052 const r = i[e]; 5053 if (r !== void 0) { 5054 const s = r.indexOf(t); 5055 s !== -1 && r.splice(s, 1); 5056 } 5057 } 5058 /** 5059 * Dispatches an event object. 5060 * 5061 * @param {Object} event - The event that gets fired. 5062 */ 5063 dispatchEvent(e) { 5064 const t = this._listeners; 5065 if (t === void 0) return; 5066 const i = t[e.type]; 5067 if (i !== void 0) { 5068 e.target = this; 5069 const r = i.slice(0); 5070 for (let s = 0, a = r.length; s < a; s++) 5071 r[s].call(this, e); 5072 e.target = null; 5073 } 5074 } 5075} 5076const cn = ["00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "0a", "0b", "0c", "0d", "0e", "0f", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "1a", "1b", "1c", "1d", "1e", "1f", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "2a", "2b", "2c", "2d", "2e", "2f", "30", "31", "32", "33", "34", "35", "36", "37", "38", "39", "3a", "3b", "3c", "3d", "3e", "3f", "40", "41", "42", "43", "44", "45", "46", "47", "48", "49", "4a", "4b", "4c", "4d", "4e", "4f", "50", "51", "52", "53", "54", "55", "56", "57", "58", "59", "5a", "5b", "5c", "5d", "5e", "5f", "60", "61", "62", "63", "64", "65", "66", "67", "68", "69", "6a", "6b", "6c", "6d", "6e", "6f", "70", "71", "72", "73", "74", "75", "76", "77", "78", "79", "7a", "7b", "7c", "7d", "7e", "7f", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89", "8a", "8b", "8c", "8d", "8e", "8f", "90", "91", "92", "93", "94", "95", "96", "97", "98", "99", "9a", "9b", "9c", "9d", "9e", "9f", "a0", "a1", "a2", "a3", "a4", "a5", "a6", "a7", "a8", "a9", "aa", "ab", "ac", "ad", "ae", "af", "b0", "b1", "b2", "b3", "b4", "b5", "b6", "b7", "b8", "b9", "ba", "bb", "bc", "bd", "be", "bf", "c0", "c1", "c2", "c3", "c4", "c5", "c6", "c7", "c8", "c9", "ca", "cb", "cc", "cd", "ce", "cf", "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7", "d8", "d9", "da", "db", "dc", "dd", "de", "df", "e0", "e1", "e2", "e3", "e4", "e5", "e6", "e7", "e8", "e9", "ea", "eb", "e
vendor: 16,082 bytes, lines 5076-5602
5076c", "ed", "ee", "ef", "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7", "f8", "f9", "fa", "fb", "fc", "fd", "fe", "ff"], fl = Math.PI / 180, Jc = 180 / Math.PI; 5077function wa() { 5078 const n = Math.random() * 4294967295 | 0, e = Math.random() * 4294967295 | 0, t = Math.random() * 4294967295 | 0, i = Math.random() * 4294967295 | 0; 5079 return (cn[n & 255] + cn[n >> 8 & 255] + cn[n >> 16 & 255] + cn[n >> 24 & 255] + "-" + cn[e & 255] + cn[e >> 8 & 255] + "-" + cn[e >> 16 & 15 | 64] + cn[e >> 24 & 255] + "-" + cn[t & 63 | 128] + cn[t >> 8 & 255] + "-" + cn[t >> 16 & 255] + cn[t >> 24 & 255] + cn[i & 255] + cn[i >> 8 & 255] + cn[i >> 16 & 255] + cn[i >> 24 & 255]).toLowerCase(); 5080} 5081function yt(n, e, t) { 5082 return Math.max(e, Math.min(t, n)); 5083} 5084function T_(n, e) { 5085 return (n % e + e) % e; 5086} 5087function pl(n, e, t) { 5088 return (1 - t) * n + t * e; 5089} 5090function Is(n, e) { 5091 switch (e.constructor) { 5092 case Float32Array: 5093 return n; 5094 case Uint32Array: 5095 return n / 4294967295; 5096 case Uint16Array: 5097 return n / 65535; 5098 case Uint8Array: 5099 return n / 255; 5100 case Int32Array: 5101 return Math.max(n / 2147483647, -1); 5102 case Int16Array: 5103 return Math.max(n / 32767, -1); 5104 case Int8Array: 5105 return Math.max(n / 127, -1); 5106 default: 5107 throw new Error("Invalid component type."); 5108 } 5109} 5110function wn(n, e) { 5111 switch (e.constructor) { 5112 case Float32Array: 5113 return n; 5114 case Uint32Array: 5115 return Math.round(n * 4294967295); 5116 case Uint16Array: 5117 return Math.round(n * 65535); 5118 case Uint8Array: 5119 return Math.round(n * 255); 5120 case Int32Array: 5121 return Math.round(n * 2147483647); 5122 case Int16Array: 5123 return Math.round(n * 32767); 5124 case Int8Array: 5125 return Math.round(n * 127); 5126 default: 5127 throw new Error("Invalid component type."); 5128 } 5129} 5130const rh = class rh { 5131 /** 5132 * Constructs a new 2D vector. 5133 * 5134 * @param {number} [x=0] - The x value of this vector. 5135 * @param {number} [y=0] - The y value of this vector. 5136 */ 5137 constructor(e = 0, t = 0) { 5138 this.x = e, this.y = t; 5139 } 5140 /** 5141 * Alias for {@link Vector2#x}. 5142 * 5143 * @type {number} 5144 */ 5145 get width() { 5146 return this.x; 5147 } 5148 set width(e) { 5149 this.x = e; 5150 } 5151 /** 5152 * Alias for {@link Vector2#y}. 5153 * 5154 * @type {number} 5155 */ 5156 get height() { 5157 return this.y; 5158 } 5159 set height(e) { 5160 this.y = e; 5161 } 5162 /** 5163 * Sets the vector components. 5164 * 5165 * @param {number} x - The value of the x component. 5166 * @param {number} y - The value of the y component. 5167 * @return {Vector2} A reference to this vector. 5168 */ 5169 set(e, t) { 5170 return this.x = e, this.y = t, this; 5171 } 5172 /** 5173 * Sets the vector components to the same value. 5174 * 5175 * @param {number} scalar - The value to set for all vector components. 5176 * @return {Vector2} A reference to this vector. 5177 */ 5178 setScalar(e) { 5179 return this.x = e, this.y = e, this; 5180 } 5181 /** 5182 * Sets the vector's x component to the given value 5183 * 5184 * @param {number} x - The value to set. 5185 * @return {Vector2} A reference to this vector. 5186 */ 5187 setX(e) { 5188 return this.x = e, this; 5189 } 5190 /** 5191 * Sets the vector's y component to the given value 5192 * 5193 * @param {number} y - The value to set. 5194 * @return {Vector2} A reference to this vector. 5195 */ 5196 setY(e) { 5197 return this.y = e, this; 5198 } 5199 /** 5200 * Allows to set a vector component with an index. 5201 * 5202 * @param {number} index - The component index. `0` equals to x, `1` equals to y. 5203 * @param {number} value - The value to set. 5204 * @return {Vector2} A reference to this vector. 5205 */ 5206 setComponent(e, t) { 5207 switch (e) { 5208 case 0: 5209 this.x = t; 5210 break; 5211 case 1: 5212 this.y = t; 5213 break; 5214 default: 5215 throw new Error("index is out of range: " + e); 5216 } 5217 return this; 5218 } 5219 /** 5220 * Returns the value of the vector component which matches the given index. 5221 * 5222 * @param {number} index - The component index. `0` equals to x, `1` equals to y. 5223 * @return {number} A vector component value. 5224 */ 5225 getComponent(e) { 5226 switch (e) { 5227 case 0: 5228 return this.x; 5229 case 1: 5230 return this.y; 5231 default: 5232 throw new Error("index is out of range: " + e); 5233 } 5234 } 5235 /** 5236 * Returns a new vector with copied values from this instance. 5237 * 5238 * @return {Vector2} A clone of this instance. 5239 */ 5240 clone() { 5241 return new this.constructor(this.x, this.y); 5242 } 5243 /** 5244 * Copies the values of the given vector to this instance. 5245 * 5246 * @param {Vector2} v - The vector to copy. 5247 * @return {Vector2} A reference to this vector. 5248 */ 5249 copy(e) { 5250 return this.x = e.x, this.y = e.y, this; 5251 } 5252 /** 5253 * Adds the given vector to this instance. 5254 * 5255 * @param {Vector2} v - The vector to add. 5256 * @return {Vector2} A reference to this vector. 5257 */ 5258 add(e) { 5259 return this.x += e.x, this.y += e.y, this; 5260 } 5261 /** 5262 * Adds the given scalar value to all components of this instance. 5263 * 5264 * @param {number} s - The scalar to add. 5265 * @return {Vector2} A reference to this vector. 5266 */ 5267 addScalar(e) { 5268 return this.x += e, this.y += e, this; 5269 } 5270 /** 5271 * Adds the given vectors and stores the result in this instance. 5272 * 5273 * @param {Vector2} a - The first vector. 5274 * @param {Vector2} b - The second vector. 5275 * @return {Vector2} A reference to this vector. 5276 */ 5277 addVectors(e, t) { 5278 return this.x = e.x + t.x, this.y = e.y + t.y, this; 5279 } 5280 /** 5281 * Adds the given vector scaled by the given factor to this instance. 5282 * 5283 * @param {Vector2} v - The vector. 5284 * @param {number} s - The factor that scales `v`. 5285 * @return {Vector2} A reference to this vector. 5286 */ 5287 addScaledVector(e, t) { 5288 return this.x += e.x * t, this.y += e.y * t, this; 5289 } 5290 /** 5291 * Subtracts the given vector from this instance. 5292 * 5293 * @param {Vector2} v - The vector to subtract. 5294 * @return {Vector2} A reference to this vector. 5295 */ 5296 sub(e) { 5297 return this.x -= e.x, this.y -= e.y, this; 5298 } 5299 /** 5300 * Subtracts the given scalar value from all components of this instance. 5301 * 5302 * @param {number} s - The scalar to subtract. 5303 * @return {Vector2} A reference to this vector. 5304 */ 5305 subScalar(e) { 5306 return this.x -= e, this.y -= e, this; 5307 } 5308 /** 5309 * Subtracts the given vectors and stores the result in this instance. 5310 * 5311 * @param {Vector2} a - The first vector. 5312 * @param {Vector2} b - The second vector. 5313 * @return {Vector2} A reference to this vector. 5314 */ 5315 subVectors(e, t) { 5316 return this.x = e.x - t.x, this.y = e.y - t.y, this; 5317 } 5318 /** 5319 * Multiplies the given vector with this instance. 5320 * 5321 * @param {Vector2} v - The vector to multiply. 5322 * @return {Vector2} A reference to this vector. 5323 */ 5324 multiply(e) { 5325 return this.x *= e.x, this.y *= e.y, this; 5326 } 5327 /** 5328 * Multiplies the given scalar value with all components of this instance. 5329 * 5330 * @param {number} scalar - The scalar to multiply. 5331 * @return {Vector2} A reference to this vector. 5332 */ 5333 multiplyScalar(e) { 5334 return this.x *= e, this.y *= e, this; 5335 } 5336 /** 5337 * Divides this instance by the given vector. 5338 * 5339 * @param {Vector2} v - The vector to divide. 5340 * @return {Vector2} A reference to this vector. 5341 */ 5342 divide(e) { 5343 return this.x /= e.x, this.y /= e.y, this; 5344 } 5345 /** 5346 * Divides this vector by the given scalar. 5347 * 5348 * @param {number} scalar - The scalar to divide. 5349 * @return {Vector2} A reference to this vector. 5350 */ 5351 divideScalar(e) { 5352 return this.multiplyScalar(1 / e); 5353 } 5354 /** 5355 * Multiplies this vector (with an implicit 1 as the 3rd component) by 5356 * the given 3x3 matrix. 5357 * 5358 * @param {Matrix3} m - The matrix to apply. 5359 * @return {Vector2} A reference to this vector. 5360 */ 5361 applyMatrix3(e) { 5362 const t = this.x, i = this.y, r = e.elements; 5363 return this.x = r[0] * t + r[3] * i + r[6], this.y = r[1] * t + r[4] * i + r[7], this; 5364 } 5365 /** 5366 * If this vector's x or y value is greater than the given vector's x or y 5367 * value, replace that value with the corresponding min value. 5368 * 5369 * @param {Vector2} v - The vector. 5370 * @return {Vector2} A reference to this vector. 5371 */ 5372 min(e) { 5373 return this.x = Math.min(this.x, e.x), this.y = Math.min(this.y, e.y), this; 5374 } 5375 /** 5376 * If this vector's x or y value is less than the given vector's x or y 5377 * value, replace that value with the corresponding max value. 5378 * 5379 * @param {Vector2} v - The vector. 5380 * @return {Vector2} A reference to this vector. 5381 */ 5382 max(e) { 5383 return this.x = Math.max(this.x, e.x), this.y = Math.max(this.y, e.y), this; 5384 } 5385 /** 5386 * If this vector's x or y value is greater than the max vector's x or y 5387 * value, it is replaced by the corresponding value. 5388 * If this vector's x or y value is less than the min vector's x or y value, 5389 * it is replaced by the corresponding value. 5390 * 5391 * @param {Vector2} min - The minimum x and y values. 5392 * @param {Vector2} max - The maximum x and y values in the desired range. 5393 * @return {Vector2} A reference to this vector. 5394 */ 5395 clamp(e, t) { 5396 return this.x = yt(this.x, e.x, t.x), this.y = yt(this.y, e.y, t.y), this; 5397 } 5398 /** 5399 * If this vector's x or y values are greater than the max value, they are 5400 * replaced by the max value. 5401 * If this vector's x or y values are less than the min value, they are 5402 * replaced by the min value. 5403 * 5404 * @param {number} minVal - The minimum value the components will be clamped to. 5405 * @param {number} maxVal - The maximum value the components will be clamped to. 5406 * @return {Vector2} A reference to this vector. 5407 */ 5408 clampScalar(e, t) { 5409 return this.x = yt(this.x, e, t), this.y = yt(this.y, e, t), this; 5410 } 5411 /** 5412 * If this vector's length is greater than the max value, it is replaced by 5413 * the max value. 5414 * If this vector's length is less than the min value, it is replaced by the 5415 * min value. 5416 * 5417 * @param {number} min - The minimum value the vector length will be clamped to. 5418 * @param {number} max - The maximum value the vector length will be clamped to. 5419 * @return {Vector2} A reference to this vector. 5420 */ 5421 clampLength(e, t) { 5422 const i = this.length(); 5423 return this.divideScalar(i || 1).multiplyScalar(yt(i, e, t)); 5424 } 5425 /** 5426 * The components of this vector are rounded down to the nearest integer value. 5427 * 5428 * @return {Vector2} A reference to this vector. 5429 */ 5430 floor() { 5431 return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this; 5432 } 5433 /** 5434 * The components of this vector are rounded up to the nearest integer value. 5435 * 5436 * @return {Vector2} A reference to this vector. 5437 */ 5438 ceil() { 5439 return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this; 5440 } 5441 /** 5442 * The components of this vector are rounded to the nearest integer value 5443 * 5444 * @return {Vector2} A reference to this vector. 5445 */ 5446 round() { 5447 return this.x = Math.round(this.x), this.y = Math.round(this.y), this; 5448 } 5449 /** 5450 * The components of this vector are rounded towards zero (up if negative, 5451 * down if positive) to an integer value. 5452 * 5453 * @return {Vector2} A reference to this vector. 5454 */ 5455 roundToZero() { 5456 return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this; 5457 } 5458 /** 5459 * Inverts this vector - i.e. sets x = -x and y = -y. 5460 * 5461 * @return {Vector2} A reference to this vector. 5462 */ 5463 negate() { 5464 return this.x = -this.x, this.y = -this.y, this; 5465 } 5466 /** 5467 * Calculates the dot product of the given vector with this instance. 5468 * 5469 * @param {Vector2} v - The vector to compute the dot product with. 5470 * @return {number} The result of the dot product. 5471 */ 5472 dot(e) { 5473 return this.x * e.x + this.y * e.y; 5474 } 5475 /** 5476 * Calculates the cross product of the given vector with this instance. 5477 * 5478 * @param {Vector2} v - The vector to compute the cross product with. 5479 * @return {number} The result of the cross product. 5480 */ 5481 cross(e) { 5482 return this.x * e.y - this.y * e.x; 5483 } 5484 /** 5485 * Computes the square of the Euclidean length (straight-line length) from 5486 * (0, 0) to (x, y). If you are comparing the lengths of vectors, you should 5487 * compare the length squared instead as it is slightly more efficient to calculate. 5488 * 5489 * @return {number} The square length of this vector. 5490 */ 5491 lengthSq() { 5492 return this.x * this.x + this.y * this.y; 5493 } 5494 /** 5495 * Computes the Euclidean length (straight-line length) from (0, 0) to (x, y). 5496 * 5497 * @return {number} The length of this vector. 5498 */ 5499 length() { 5500 return Math.sqrt(this.x * this.x + this.y * this.y); 5501 } 5502 /** 5503 * Computes the Manhattan length of this vector. 5504 * 5505 * @return {number} The length of this vector. 5506 */ 5507 manhattanLength() { 5508 return Math.abs(this.x) + Math.abs(this.y); 5509 } 5510 /** 5511 * Converts this vector to a unit vector - that is, sets it equal to a vector 5512 * with the same direction as this one, but with a vector length of `1`. 5513 * 5514 * @return {Vector2} A reference to this vector. 5515 */ 5516 normalize() { 5517 return this.divideScalar(this.length() || 1); 5518 } 5519 /** 5520 * Computes the angle in radians of this vector with respect to the positive x-axis. 5521 * 5522 * @return {number} The angle in radians. 5523 */ 5524 angle() { 5525 return Math.atan2(-this.y, -this.x) + Math.PI; 5526 } 5527 /** 5528 * Returns the angle between the given vector and this instance in radians. 5529 * 5530 * @param {Vector2} v - The vector to compute the angle with. 5531 * @return {number} The angle in radians. 5532 */ 5533 angleTo(e) { 5534 const t = Math.sqrt(this.lengthSq() * e.lengthSq()); 5535 if (t === 0) return Math.PI / 2; 5536 const i = this.dot(e) / t; 5537 return Math.acos(yt(i, -1, 1)); 5538 } 5539 /** 5540 * Computes the distance from the given vector to this instance. 5541 * 5542 * @param {Vector2} v - The vector to compute the distance to. 5543 * @return {number} The distance. 5544 */ 5545 distanceTo(e) { 5546 return Math.sqrt(this.distanceToSquared(e)); 5547 } 5548 /** 5549 * Computes the squared distance from the given vector to this instance. 5550 * If you are just comparing the distance with another distance, you should compare 5551 * the distance squared instead as it is slightly more efficient to calculate. 5552 * 5553 * @param {Vector2} v - The vector to compute the squared distance to. 5554 * @return {number} The squared distance. 5555 */ 5556 distanceToSquared(e) { 5557 const t = this.x - e.x, i = this.y - e.y; 5558 return t * t + i * i; 5559 } 5560 /** 5561 * Computes the Manhattan distance from the given vector to this instance. 5562 * 5563 * @param {Vector2} v - The vector to compute the Manhattan distance to. 5564 * @return {number} The Manhattan distance. 5565 */ 5566 manhattanDistanceTo(e) { 5567 return Math.abs(this.x - e.x) + Math.abs(this.y - e.y); 5568 } 5569 /** 5570 * Sets this vector to a vector with the same direction as this one, but 5571 * with the specified length. 5572 * 5573 * @param {number} length - The new length of this vector. 5574 * @return {Vector2} A reference to this vector. 5575 */ 5576 setLength(e) { 5577 return this.normalize().multiplyScalar(e); 5578 } 5579 /** 5580 * Linearly interpolates between the given vector and this instance, where 5581 * alpha is the percent distance along the line - alpha = 0 will be this 5582 * vector, and alpha = 1 will be the given one. 5583 * 5584 * @param {Vector2} v - The vector to interpolate towards. 5585 * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. 5586 * @return {Vector2} A reference to this vector. 5587 */ 5588 lerp(e, t) { 5589 return this.x += (e.x - this.x) * t, this.y += (e.y - this.y) * t, this; 5590 } 5591 /** 5592 * Linearly interpolates between the given vectors, where alpha is the percent 5593 * distance along the line - alpha = 0 will be first vector, and alpha = 1 will 5594 * be the second one. The result is stored in this instance. 5595 * 5596 * @param {Vector2} v1 - The first vector. 5597 * @param {Vector2} v2 - The second vector. 5598 * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. 5599 * @return {Vector2} A reference to this vector. 5600 */ 5601 lerpVectors(e, t, i) { 5602 return this.x = e.x + (t.x - e.x) * i, this.y = e.y + (t.y - e.y
5602) * i, this; 5603 } 5604 /** 5605 * Returns `true` if this vector is equal with the given one. 5606 * 5607 * @param {Vector2} v - The vector to test for equality. 5608 * @return {boolean} Whether this vector is equal with the given one. 5609 */ 5610 equals(e) { 5611 return e.x === this.x && e.y === this.y; 5612 } 5613 /** 5614 * Sets this vector's x value to be `array[ offset ]` and y 5615 * value to be `array[ offset + 1 ]`. 5616 * 5617 * @param {Array<number>} array - An array holding the vector component values. 5618 * @param {number} [offset=0] - The offset into the array. 5619 * @return {Vector2} A reference to this vector. 5620 */ 5621 fromArray(e, t = 0) { 5622 return this.x = e[t], this.y = e[t + 1], this; 5623 } 5624 /** 5625 * Writes the components of this vector to the given array. If no array is provided, 5626 * the method returns a new instance. 5627 * 5628 * @param {Array<number>} [array=[]] - The target array holding the vector components. 5629 * @param {number} [offset=0] - Index of the first element in the array. 5630 * @return {Array<number>} The vector components. 5631 */ 5632 toArray(e = [], t = 0) { 5633 return e[t] = this.x, e[t + 1] = this.y, e; 5634 } 5635 /** 5636 * Sets the components of this vector from the given buffer attribute. 5637 * 5638 * @param {BufferAttribute} attribute - The buffer attribute holding vector data. 5639 * @param {number} index - The index into the attribute. 5640 * @return {Vector2} A reference to this vector. 5641 */ 5642 fromBufferAttribute(e, t) { 5643 return this.x = e.getX(t), this.y = e.getY(t), this; 5644 } 5645 /** 5646 * Rotates this vector around the given center by the given angle. 5647 * 5648 * @param {Vector2} center - The point around which to rotate. 5649 * @param {number} angle - The angle to rotate, in radians. 5650 * @return {Vector2} A reference to this vector. 5651 */ 5652 rotateAround(e, t) { 5653 const i = Math.cos(t), r = Math.sin(t), s = this.x - e.x, a = this.y - e.y; 5654 return this.x = s * i - a * r + e.x, this.y = s * r + a * i + e.y, this; 5655 } 5656 /** 5657 * Sets each component of this vector to a pseudo-random value between `0` and 5658 * `1`, excluding `1`. 5659 * 5660 * @return {Vector2} A reference to this vector. 5661 */ 5662 random() { 5663 return this.x = Math.random(), this.y = Math.random(), this; 5664 } 5665 *[Symbol.iterator]() { 5666 yield this.x, yield this.y; 5667 } 5668}; 5669rh.prototype.isVector2 = !0; 5670let wt = rh; 5671class Wn { 5672 /** 5673 * Constructs a new quaternion. 5674 * 5675 * @param {number} [x=0] - The x value of this quaternion. 5676 * @param {number} [y=0] - The y value of this quaternion. 5677 * @param {number} [z=0] - The z value of this quaternion. 5678 * @param {number} [w=1] - The w value of this quaternion. 5679 */ 5680 constructor(e = 0, t = 0, i = 0, r = 1) { 5681 this.isQuaternion = !0, this._x = e, this._y = t, this._z = i, this._w = r; 5682 } 5683 /** 5684 * Interpolates between two quaternions via SLERP. This implementation assumes the 5685 * quaternion data are managed in flat arrays. 5686 * 5687 * @param {Array<number>} dst - The destination array. 5688 * @param {number} dstOffset - An offset into the destination array. 5689 * @param {Array<number>} src0 - The source array of the first quaternion. 5690 * @param {number} srcOffset0 - An offset into the first source array. 5691 * @param {Array<number>} src1 - The source array of the second quaternion. 5692 * @param {number} srcOffset1 - An offset into the second source array. 5693 * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate. 5694 * @see {@link Quaternion#slerp} 5695 */ 5696 static slerpFlat(e, t, i, r, s, a, l) { 5697 let o = i[r + 0], c = i[r + 1], u = i[r + 2], h = i[r + 3], d = s[a + 0], f = s[a + 1], p = s[a + 2], v = s[a + 3]; 5698 if (h !== v || o !== d || c !== f || u !== p) { 5699 let m = o * d + c * f + u * p + h * v; 5700 m < 0 && (d = -d, f = -f, p = -p, v = -v, m = -m); 5701 let g = 1 - l; 5702 if (m < 0.9995) { 5703 const _ = Math.acos(m), x = Math.sin(_); 5704 g = Math.sin(g * _) / x, l = Math.sin(l * _) / x, o = o * g + d * l, c = c * g + f * l, u = u * g + p * l, h = h * g + v * l; 5705 } else { 5706 o = o * g + d * l, c = c * g + f * l, u = u * g + p * l, h = h * g + v * l; 5707 const _ = 1 / Math.sqrt(o * o + c * c + u * u + h * h); 5708 o *= _, c *= _, u *= _, h *= _; 5709 } 5710 } 5711 e[t] = o, e[t + 1] = c, e[t + 2] = u, e[t + 3] = h; 5712 } 5713 /** 5714 * Multiplies two quaternions. This implementation assumes the quaternion data are managed 5715 * in flat arrays. 5716 * 5717 * @param {Array<number>} dst - The destination array.
vendor: 55,252 bytes, lines 5718-7334
5718 * @param {number} dstOffset - An offset into the destination array. 5719 * @param {Array<number>} src0 - The source array of the first quaternion. 5720 * @param {number} srcOffset0 - An offset into the first source array. 5721 * @param {Array<number>} src1 - The source array of the second quaternion. 5722 * @param {number} srcOffset1 - An offset into the second source array. 5723 * @return {Array<number>} The destination array. 5724 * @see {@link Quaternion#multiplyQuaternions}. 5725 */ 5726 static multiplyQuaternionsFlat(e, t, i, r, s, a) { 5727 const l = i[r], o = i[r + 1], c = i[r + 2], u = i[r + 3], h = s[a], d = s[a + 1], f = s[a + 2], p = s[a + 3]; 5728 return e[t] = l * p + u * h + o * f - c * d, e[t + 1] = o * p + u * d + c * h - l * f, e[t + 2] = c * p + u * f + l * d - o * h, e[t + 3] = u * p - l * h - o * d - c * f, e; 5729 } 5730 /** 5731 * The x value of this quaternion. 5732 * 5733 * @type {number} 5734 * @default 0 5735 */ 5736 get x() { 5737 return this._x; 5738 } 5739 set x(e) { 5740 this._x = e, this._onChangeCallback(); 5741 } 5742 /** 5743 * The y value of this quaternion. 5744 * 5745 * @type {number} 5746 * @default 0 5747 */ 5748 get y() { 5749 return this._y; 5750 } 5751 set y(e) { 5752 this._y = e, this._onChangeCallback(); 5753 } 5754 /** 5755 * The z value of this quaternion. 5756 * 5757 * @type {number} 5758 * @default 0 5759 */ 5760 get z() { 5761 return this._z; 5762 } 5763 set z(e) { 5764 this._z = e, this._onChangeCallback(); 5765 } 5766 /** 5767 * The w value of this quaternion. 5768 * 5769 * @type {number} 5770 * @default 1 5771 */ 5772 get w() { 5773 return this._w; 5774 } 5775 set w(e) { 5776 this._w = e, this._onChangeCallback(); 5777 } 5778 /** 5779 * Sets the quaternion components. 5780 * 5781 * @param {number} x - The x value of this quaternion. 5782 * @param {number} y - The y value of this quaternion. 5783 * @param {number} z - The z value of this quaternion. 5784 * @param {number} w - The w value of this quaternion. 5785 * @return {Quaternion} A reference to this quaternion. 5786 */ 5787 set(e, t, i, r) { 5788 return this._x = e, this._y = t, this._z = i, this._w = r, this._onChangeCallback(), this; 5789 } 5790 /** 5791 * Returns a new quaternion with copied values from this instance. 5792 * 5793 * @return {Quaternion} A clone of this instance. 5794 */ 5795 clone() { 5796 return new this.constructor(this._x, this._y, this._z, this._w); 5797 } 5798 /** 5799 * Copies the values of the given quaternion to this instance. 5800 * 5801 * @param {Quaternion} quaternion - The quaternion to copy. 5802 * @return {Quaternion} A reference to this quaternion. 5803 */ 5804 copy(e) { 5805 return this._x = e.x, this._y = e.y, this._z = e.z, this._w = e.w, this._onChangeCallback(), this; 5806 } 5807 /** 5808 * Sets this quaternion from the rotation specified by the given 5809 * Euler angles. 5810 * 5811 * @param {Euler} euler - The Euler angles. 5812 * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not. 5813 * @return {Quaternion} A reference to this quaternion. 5814 */ 5815 setFromEuler(e, t = !0) { 5816 const i = e._x, r = e._y, s = e._z, a = e._order, l = Math.cos, o = Math.sin, c = l(i / 2), u = l(r / 2), h = l(s / 2), d = o(i / 2), f = o(r / 2), p = o(s / 2); 5817 switch (a) { 5818 case "XYZ": 5819 this._x = d * u * h + c * f * p, this._y = c * f * h - d * u * p, this._z = c * u * p + d * f * h, this._w = c * u * h - d * f * p; 5820 break; 5821 case "YXZ": 5822 this._x = d * u * h + c * f * p, this._y = c * f * h - d * u * p, this._z = c * u * p - d * f * h, this._w = c * u * h + d * f * p; 5823 break; 5824 case "ZXY": 5825 this._x = d * u * h - c * f * p, this._y = c * f * h + d * u * p, this._z = c * u * p + d * f * h, this._w = c * u * h - d * f * p; 5826 break; 5827 case "ZYX": 5828 this._x = d * u * h - c * f * p, this._y = c * f * h + d * u * p, this._z = c * u * p - d * f * h, this._w = c * u * h + d * f * p; 5829 break; 5830 case "YZX": 5831 this._x = d * u * h + c * f * p, this._y = c * f * h + d * u * p, this._z = c * u * p - d * f * h, this._w = c * u * h - d * f * p; 5832 break; 5833 case "XZY": 5834 this._x = d * u * h - c * f * p, this._y = c * f * h - d * u * p, this._z = c * u * p + d * f * h, this._w = c * u * h + d * f * p; 5835 break; 5836 default: 5837 tt("Quaternion: .setFromEuler() encountered an unknown order: " + a); 5838 } 5839 return t === !0 && this._onChangeCallback(), this; 5840 } 5841 /** 5842 * Sets this quaternion from the given axis and angle. 5843 * 5844 * @param {Vector3} axis - The normalized axis. 5845 * @param {number} angle - The angle in radians. 5846 * @return {Quaternion} A reference to this quaternion. 5847 */ 5848 setFromAxisAngle(e, t) { 5849 const i = t / 2, r = Math.sin(i); 5850 return this._x = e.x * r, this._y = e.y * r, this._z = e.z * r, this._w = Math.cos(i), this._onChangeCallback(), this; 5851 } 5852 /** 5853 * Sets this quaternion from the given rotation matrix. 5854 * 5855 * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled). 5856 * @return {Quaternion} A reference to this quaternion. 5857 */ 5858 setFromRotationMatrix(e) { 5859 const t = e.elements, i = t[0], r = t[4], s = t[8], a = t[1], l = t[5], o = t[9], c = t[2], u = t[6], h = t[10], d = i + l + h; 5860 if (d > 0) { 5861 const f = 0.5 / Math.sqrt(d + 1); 5862 this._w = 0.25 / f, this._x = (u - o) * f, this._y = (s - c) * f, this._z = (a - r) * f; 5863 } else if (i > l && i > h) { 5864 const f = 2 * Math.sqrt(1 + i - l - h); 5865 this._w = (u - o) / f, this._x = 0.25 * f, this._y = (r + a) / f, this._z = (s + c) / f; 5866 } else if (l > h) { 5867 const f = 2 * Math.sqrt(1 + l - i - h); 5868 this._w = (s - c) / f, this._x = (r + a) / f, this._y = 0.25 * f, this._z = (o + u) / f; 5869 } else { 5870 const f = 2 * Math.sqrt(1 + h - i - l); 5871 this._w = (a - r) / f, this._x = (s + c) / f, this._y = (o + u) / f, this._z = 0.25 * f; 5872 } 5873 return this._onChangeCallback(), this; 5874 } 5875 /** 5876 * Sets this quaternion to the rotation required to rotate the direction vector 5877 * `vFrom` to the direction vector `vTo`. 5878 * 5879 * @param {Vector3} vFrom - The first (normalized) direction vector. 5880 * @param {Vector3} vTo - The second (normalized) direction vector. 5881 * @return {Quaternion} A reference to this quaternion. 5882 */ 5883 setFromUnitVectors(e, t) { 5884 let i = e.dot(t) + 1; 5885 return i < 1e-8 ? (i = 0, Math.abs(e.x) > Math.abs(e.z) ? (this._x = -e.y, this._y = e.x, this._z = 0, this._w = i) : (this._x = 0, this._y = -e.z, this._z = e.y, this._w = i)) : (this._x = e.y * t.z - e.z * t.y, this._y = e.z * t.x - e.x * t.z, this._z = e.x * t.y - e.y * t.x, this._w = i), this.normalize(); 5886 } 5887 /** 5888 * Returns the angle between this quaternion and the given one in radians. 5889 * 5890 * @param {Quaternion} q - The quaternion to compute the angle with. 5891 * @return {number} The angle in radians. 5892 */ 5893 angleTo(e) { 5894 return 2 * Math.acos(Math.abs(yt(this.dot(e), -1, 1))); 5895 } 5896 /** 5897 * Rotates this quaternion by a given angular step to the given quaternion. 5898 * The method ensures that the final quaternion will not overshoot `q`. 5899 * 5900 * @param {Quaternion} q - The target quaternion. 5901 * @param {number} step - The angular step in radians. 5902 * @return {Quaternion} A reference to this quaternion. 5903 */ 5904 rotateTowards(e, t) { 5905 const i = this.angleTo(e); 5906 if (i === 0) return this; 5907 const r = Math.min(1, t / i); 5908 return this.slerp(e, r), this; 5909 } 5910 /** 5911 * Sets this quaternion to the identity quaternion; that is, to the 5912 * quaternion that represents "no rotation". 5913 * 5914 * @return {Quaternion} A reference to this quaternion. 5915 */ 5916 identity() { 5917 return this.set(0, 0, 0, 1); 5918 } 5919 /** 5920 * Inverts this quaternion via {@link Quaternion#conjugate}. The 5921 * quaternion is assumed to have unit length. 5922 * 5923 * @return {Quaternion} A reference to this quaternion. 5924 */ 5925 invert() { 5926 return this.conjugate(); 5927 } 5928 /** 5929 * Returns the rotational conjugate of this quaternion. The conjugate of a 5930 * quaternion represents the same rotation in the opposite direction about 5931 * the rotational axis. 5932 * 5933 * @return {Quaternion} A reference to this quaternion. 5934 */ 5935 conjugate() { 5936 return this._x *= -1, this._y *= -1, this._z *= -1, this._onChangeCallback(), this; 5937 } 5938 /** 5939 * Calculates the dot product of this quaternion and the given one. 5940 * 5941 * @param {Quaternion} v - The quaternion to compute the dot product with. 5942 * @return {number} The result of the dot product. 5943 */ 5944 dot(e) { 5945 return this._x * e._x + this._y * e._y + this._z * e._z + this._w * e._w; 5946 } 5947 /** 5948 * Computes the squared Euclidean length (straight-line length) of this quaternion, 5949 * considered as a 4 dimensional vector. This can be useful if you are comparing the 5950 * lengths of two quaternions, as this is a slightly more efficient calculation than 5951 * {@link Quaternion#length}. 5952 * 5953 * @return {number} The squared Euclidean length. 5954 */ 5955 lengthSq() { 5956 return this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w; 5957 } 5958 /** 5959 * Computes the Euclidean length (straight-line length) of this quaternion, 5960 * considered as a 4 dimensional vector. 5961 * 5962 * @return {number} The Euclidean length. 5963 */ 5964 length() { 5965 return Math.sqrt(this._x * this._x + this._y * this._y + this._z * this._z + this._w * this._w); 5966 } 5967 /** 5968 * Normalizes this quaternion - that is, calculated the quaternion that performs 5969 * the same rotation as this one, but has a length equal to `1`. 5970 * 5971 * @return {Quaternion} A reference to this quaternion. 5972 */ 5973 normalize() { 5974 let e = this.length(); 5975 return e === 0 ? (this._x = 0, this._y = 0, this._z = 0, this._w = 1) : (e = 1 / e, this._x = this._x * e, this._y = this._y * e, this._z = this._z * e, this._w = this._w * e), this._onChangeCallback(), this; 5976 } 5977 /** 5978 * Multiplies this quaternion by the given one. 5979 * 5980 * @param {Quaternion} q - The quaternion. 5981 * @return {Quaternion} A reference to this quaternion. 5982 */ 5983 multiply(e) { 5984 return this.multiplyQuaternions(this, e); 5985 } 5986 /** 5987 * Pre-multiplies this quaternion by the given one. 5988 * 5989 * @param {Quaternion} q - The quaternion. 5990 * @return {Quaternion} A reference to this quaternion. 5991 */ 5992 premultiply(e) { 5993 return this.multiplyQuaternions(e, this); 5994 } 5995 /** 5996 * Multiplies the given quaternions and stores the result in this instance. 5997 * 5998 * @param {Quaternion} a - The first quaternion. 5999 * @param {Quaternion} b - The second quaternion. 6000 * @return {Quaternion} A reference to this quaternion. 6001 */ 6002 multiplyQuaternions(e, t) { 6003 const i = e._x, r = e._y, s = e._z, a = e._w, l = t._x, o = t._y, c = t._z, u = t._w; 6004 return this._x = i * u + a * l + r * c - s * o, this._y = r * u + a * o + s * l - i * c, this._z = s * u + a * c + i * o - r * l, this._w = a * u - i * l - r * o - s * c, this._onChangeCallback(), this; 6005 } 6006 /** 6007 * Performs a spherical linear interpolation between this quaternion and the target quaternion. 6008 * 6009 * @param {Quaternion} qb - The target quaternion. 6010 * @param {number} t - The interpolation factor. A value in the range `[0,1]` will interpolate. A value outside the range `[0,1]` will extrapolate. 6011 * @return {Quaternion} A reference to this quaternion. 6012 */ 6013 slerp(e, t) { 6014 let i = e._x, r = e._y, s = e._z, a = e._w, l = this.dot(e); 6015 l < 0 && (i = -i, r = -r, s = -s, a = -a, l = -l); 6016 let o = 1 - t; 6017 if (l < 0.9995) { 6018 const c = Math.acos(l), u = Math.sin(c); 6019 o = Math.sin(o * c) / u, t = Math.sin(t * c) / u, this._x = this._x * o + i * t, this._y = this._y * o + r * t, this._z = this._z * o + s * t, this._w = this._w * o + a * t, this._onChangeCallback(); 6020 } else 6021 this._x = this._x * o + i * t, this._y = this._y * o + r * t, this._z = this._z * o + s * t, this._w = this._w * o + a * t, this.normalize(); 6022 return this; 6023 } 6024 /** 6025 * Performs a spherical linear interpolation between the given quaternions 6026 * and stores the result in this quaternion. 6027 * 6028 * @param {Quaternion} qa - The source quaternion. 6029 * @param {Quaternion} qb - The target quaternion. 6030 * @param {number} t - The interpolation factor in the closed interval `[0, 1]`. 6031 * @return {Quaternion} A reference to this quaternion. 6032 */ 6033 slerpQuaternions(e, t, i) { 6034 return this.copy(e).slerp(t, i); 6035 } 6036 /** 6037 * Sets this quaternion to a uniformly random, normalized quaternion. 6038 * 6039 * @return {Quaternion} A reference to this quaternion. 6040 */ 6041 random() { 6042 const e = 2 * Math.PI * Math.random(), t = 2 * Math.PI * Math.random(), i = Math.random(), r = Math.sqrt(1 - i), s = Math.sqrt(i); 6043 return this.set( 6044 r * Math.sin(e), 6045 r * Math.cos(e), 6046 s * Math.sin(t), 6047 s * Math.cos(t) 6048 ); 6049 } 6050 /** 6051 * Returns `true` if this quaternion is equal with the given one. 6052 * 6053 * @param {Quaternion} quaternion - The quaternion to test for equality. 6054 * @return {boolean} Whether this quaternion is equal with the given one. 6055 */ 6056 equals(e) { 6057 return e._x === this._x && e._y === this._y && e._z === this._z && e._w === this._w; 6058 } 6059 /** 6060 * Sets this quaternion's components from the given array. 6061 * 6062 * @param {Array<number>} array - An array holding the quaternion component values. 6063 * @param {number} [offset=0] - The offset into the array. 6064 * @return {Quaternion} A reference to this quaternion. 6065 */ 6066 fromArray(e, t = 0) { 6067 return this._x = e[t], this._y = e[t + 1], this._z = e[t + 2], this._w = e[t + 3], this._onChangeCallback(), this; 6068 } 6069 /** 6070 * Writes the components of this quaternion to the given array. If no array is provided, 6071 * the method returns a new instance. 6072 * 6073 * @param {Array<number>} [array=[]] - The target array holding the quaternion components. 6074 * @param {number} [offset=0] - Index of the first element in the array. 6075 * @return {Array<number>} The quaternion components. 6076 */ 6077 toArray(e = [], t = 0) { 6078 return e[t] = this._x, e[t + 1] = this._y, e[t + 2] = this._z, e[t + 3] = this._w, e; 6079 } 6080 /** 6081 * Sets the components of this quaternion from the given buffer attribute. 6082 * 6083 * @param {BufferAttribute} attribute - The buffer attribute holding quaternion data. 6084 * @param {number} index - The index into the attribute. 6085 * @return {Quaternion} A reference to this quaternion. 6086 */ 6087 fromBufferAttribute(e, t) { 6088 return this._x = e.getX(t), this._y = e.getY(t), this._z = e.getZ(t), this._w = e.getW(t), this._onChangeCallback(), this; 6089 } 6090 /** 6091 * This methods defines the serialization result of this class. Returns the 6092 * numerical elements of this quaternion in an array of format `[x, y, z, w]`. 6093 * 6094 * @return {Array<number>} The serialized quaternion. 6095 */ 6096 toJSON() { 6097 return this.toArray(); 6098 } 6099 _onChange(e) { 6100 return this._onChangeCallback = e, this; 6101 } 6102 _onChangeCallback() { 6103 } 6104 *[Symbol.iterator]() { 6105 yield this._x, yield this._y, yield this._z, yield this._w; 6106 } 6107} 6108const sh = class sh { 6109 /** 6110 * Constructs a new 3D vector. 6111 * 6112 * @param {number} [x=0] - The x value of this vector. 6113 * @param {number} [y=0] - The y value of this vector. 6114 * @param {number} [z=0] - The z value of this vector. 6115 */ 6116 constructor(e = 0, t = 0, i = 0) { 6117 this.x = e, this.y = t, this.z = i; 6118 } 6119 /** 6120 * Sets the vector components. 6121 * 6122 * @param {number} x - The value of the x component. 6123 * @param {number} y - The value of the y component. 6124 * @param {number} z - The value of the z component. 6125 * @return {Vector3} A reference to this vector. 6126 */ 6127 set(e, t, i) { 6128 return i === void 0 && (i = this.z), this.x = e, this.y = t, this.z = i, this; 6129 } 6130 /** 6131 * Sets the vector components to the same value. 6132 * 6133 * @param {number} scalar - The value to set for all vector components. 6134 * @return {Vector3} A reference to this vector. 6135 */ 6136 setScalar(e) { 6137 return this.x = e, this.y = e, this.z = e, this; 6138 } 6139 /** 6140 * Sets the vector's x component to the given value. 6141 * 6142 * @param {number} x - The value to set. 6143 * @return {Vector3} A reference to this vector. 6144 */ 6145 setX(e) { 6146 return this.x = e, this; 6147 } 6148 /** 6149 * Sets the vector's y component to the given value. 6150 * 6151 * @param {number} y - The value to set. 6152 * @return {Vector3} A reference to this vector. 6153 */ 6154 setY(e) { 6155 return this.y = e, this; 6156 } 6157 /** 6158 * Sets the vector's z component to the given value. 6159 * 6160 * @param {number} z - The value to set. 6161 * @return {Vector3} A reference to this vector. 6162 */ 6163 setZ(e) { 6164 return this.z = e, this; 6165 } 6166 /** 6167 * Allows to set a vector component with an index. 6168 * 6169 * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z. 6170 * @param {number} value - The value to set. 6171 * @return {Vector3} A reference to this vector. 6172 */ 6173 setComponent(e, t) { 6174 switch (e) { 6175 case 0: 6176 this.x = t; 6177 break; 6178 case 1: 6179 this.y = t; 6180 break; 6181 case 2: 6182 this.z = t; 6183 break; 6184 default: 6185 throw new Error("index is out of range: " + e); 6186 } 6187 return this; 6188 } 6189 /** 6190 * Returns the value of the vector component which matches the given index. 6191 * 6192 * @param {number} index - The component index. `0` equals to x, `1` equals to y, `2` equals to z. 6193 * @return {number} A vector component value. 6194 */ 6195 getComponent(e) { 6196 switch (e) { 6197 case 0: 6198 return this.x; 6199 case 1: 6200 return this.y; 6201 case 2: 6202 return this.z; 6203 default: 6204 throw new Error("index is out of range: " + e); 6205 } 6206 } 6207 /** 6208 * Returns a new vector with copied values from this instance. 6209 * 6210 * @return {Vector3} A clone of this instance. 6211 */ 6212 clone() { 6213 return new this.constructor(this.x, this.y, this.z); 6214 } 6215 /** 6216 * Copies the values of the given vector to this instance. 6217 * 6218 * @param {Vector3} v - The vector to copy. 6219 * @return {Vector3} A reference to this vector. 6220 */ 6221 copy(e) { 6222 return this.x = e.x, this.y = e.y, this.z = e.z, this; 6223 } 6224 /** 6225 * Adds the given vector to this instance. 6226 * 6227 * @param {Vector3} v - The vector to add. 6228 * @return {Vector3} A reference to this vector. 6229 */ 6230 add(e) { 6231 return this.x += e.x, this.y += e.y, this.z += e.z, this; 6232 } 6233 /** 6234 * Adds the given scalar value to all components of this instance. 6235 * 6236 * @param {number} s - The scalar to add. 6237 * @return {Vector3} A reference to this vector. 6238 */ 6239 addScalar(e) { 6240 return this.x += e, this.y += e, this.z += e, this; 6241 } 6242 /** 6243 * Adds the given vectors and stores the result in this instance. 6244 * 6245 * @param {Vector3} a - The first vector. 6246 * @param {Vector3} b - The second vector. 6247 * @return {Vector3} A reference to this vector. 6248 */ 6249 addVectors(e, t) { 6250 return this.x = e.x + t.x, this.y = e.y + t.y, this.z = e.z + t.z, this; 6251 } 6252 /** 6253 * Adds the given vector scaled by the given factor to this instance. 6254 * 6255 * @param {Vector3|Vector4} v - The vector. 6256 * @param {number} s - The factor that scales `v`. 6257 * @return {Vector3} A reference to this vector. 6258 */ 6259 addScaledVector(e, t) { 6260 return this.x += e.x * t, this.y += e.y * t, this.z += e.z * t, this; 6261 } 6262 /** 6263 * Subtracts the given vector from this instance. 6264 * 6265 * @param {Vector3} v - The vector to subtract. 6266 * @return {Vector3} A reference to this vector. 6267 */ 6268 sub(e) { 6269 return this.x -= e.x, this.y -= e.y, this.z -= e.z, this; 6270 } 6271 /** 6272 * Subtracts the given scalar value from all components of this instance. 6273 * 6274 * @param {number} s - The scalar to subtract. 6275 * @return {Vector3} A reference to this vector. 6276 */ 6277 subScalar(e) { 6278 return this.x -= e, this.y -= e, this.z -= e, this; 6279 } 6280 /** 6281 * Subtracts the given vectors and stores the result in this instance. 6282 * 6283 * @param {Vector3} a - The first vector. 6284 * @param {Vector3} b - The second vector. 6285 * @return {Vector3} A reference to this vector. 6286 */ 6287 subVectors(e, t) { 6288 return this.x = e.x - t.x, this.y = e.y - t.y, this.z = e.z - t.z, this; 6289 } 6290 /** 6291 * Multiplies the given vector with this instance. 6292 * 6293 * @param {Vector3} v - The vector to multiply. 6294 * @return {Vector3} A reference to this vector. 6295 */ 6296 multiply(e) { 6297 return this.x *= e.x, this.y *= e.y, this.z *= e.z, this; 6298 } 6299 /** 6300 * Multiplies the given scalar value with all components of this instance. 6301 * 6302 * @param {number} scalar - The scalar to multiply. 6303 * @return {Vector3} A reference to this vector. 6304 */ 6305 multiplyScalar(e) { 6306 return this.x *= e, this.y *= e, this.z *= e, this; 6307 } 6308 /** 6309 * Multiplies the given vectors and stores the result in this instance. 6310 * 6311 * @param {Vector3} a - The first vector. 6312 * @param {Vector3} b - The second vector. 6313 * @return {Vector3} A reference to this vector. 6314 */ 6315 multiplyVectors(e, t) { 6316 return this.x = e.x * t.x, this.y = e.y * t.y, this.z = e.z * t.z, this; 6317 } 6318 /** 6319 * Applies the given Euler rotation to this vector. 6320 * 6321 * @param {Euler} euler - The Euler angles. 6322 * @return {Vector3} A reference to this vector. 6323 */ 6324 applyEuler(e) { 6325 return this.applyQuaternion(qh.setFromEuler(e)); 6326 } 6327 /** 6328 * Applies a rotation specified by an axis and an angle to this vector. 6329 * 6330 * @param {Vector3} axis - A normalized vector representing the rotation axis. 6331 * @param {number} angle - The angle in radians. 6332 * @return {Vector3} A reference to this vector. 6333 */ 6334 applyAxisAngle(e, t) { 6335 return this.applyQuaternion(qh.setFromAxisAngle(e, t)); 6336 } 6337 /** 6338 * Multiplies this vector with the given 3x3 matrix. 6339 * 6340 * @param {Matrix3} m - The 3x3 matrix. 6341 * @return {Vector3} A reference to this vector. 6342 */ 6343 applyMatrix3(e) { 6344 const t = this.x, i = this.y, r = this.z, s = e.elements; 6345 return this.x = s[0] * t + s[3] * i + s[6] * r, this.y = s[1] * t + s[4] * i + s[7] * r, this.z = s[2] * t + s[5] * i + s[8] * r, this; 6346 } 6347 /** 6348 * Multiplies this vector by the given normal matrix and normalizes 6349 * the result. 6350 * 6351 * @param {Matrix3} m - The normal matrix. 6352 * @return {Vector3} A reference to this vector. 6353 */ 6354 applyNormalMatrix(e) { 6355 return this.applyMatrix3(e).normalize(); 6356 } 6357 /** 6358 * Multiplies this vector (with an implicit 1 in the 4th dimension) by m, and 6359 * divides by perspective. 6360 * 6361 * @param {Matrix4} m - The matrix to apply. 6362 * @return {Vector3} A reference to this vector. 6363 */ 6364 applyMatrix4(e) { 6365 const t = this.x, i = this.y, r = this.z, s = e.elements, a = 1 / (s[3] * t + s[7] * i + s[11] * r + s[15]); 6366 return this.x = (s[0] * t + s[4] * i + s[8] * r + s[12]) * a, this.y = (s[1] * t + s[5] * i + s[9] * r + s[13]) * a, this.z = (s[2] * t + s[6] * i + s[10] * r + s[14]) * a, this; 6367 } 6368 /** 6369 * Applies the given Quaternion to this vector. 6370 * 6371 * @param {Quaternion} q - The Quaternion. 6372 * @return {Vector3} A reference to this vector. 6373 */ 6374 applyQuaternion(e) { 6375 const t = this.x, i = this.y, r = this.z, s = e.x, a = e.y, l = e.z, o = e.w, c = 2 * (a * r - l * i), u = 2 * (l * t - s * r), h = 2 * (s * i - a * t); 6376 return this.x = t + o * c + a * h - l * u, this.y = i + o * u + l * c - s * h, this.z = r + o * h + s * u - a * c, this; 6377 } 6378 /** 6379 * Projects this vector from world space into the camera's normalized 6380 * device coordinate (NDC) space. 6381 * 6382 * @param {Camera} camera - The camera. 6383 * @return {Vector3} A reference to this vector. 6384 */ 6385 project(e) { 6386 return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix); 6387 } 6388 /** 6389 * Unprojects this vector from the camera's normalized device coordinate (NDC) 6390 * space into world space. 6391 * 6392 * @param {Camera} camera - The camera. 6393 * @return {Vector3} A reference to this vector. 6394 */ 6395 unproject(e) { 6396 return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld); 6397 } 6398 /** 6399 * Transforms the direction of this vector by a matrix (the upper left 3 x 3 6400 * subset of the given 4x4 matrix and then normalizes the result. 6401 * 6402 * @param {Matrix4} m - The matrix. 6403 * @return {Vector3} A reference to this vector. 6404 */ 6405 transformDirection(e) { 6406 const t = this.x, i = this.y, r = this.z, s = e.elements; 6407 return this.x = s[0] * t + s[4] * i + s[8] * r, this.y = s[1] * t + s[5] * i + s[9] * r, this.z = s[2] * t + s[6] * i + s[10] * r, this.normalize(); 6408 } 6409 /** 6410 * Divides this instance by the given vector. 6411 * 6412 * @param {Vector3} v - The vector to divide. 6413 * @return {Vector3} A reference to this vector. 6414 */ 6415 divide(e) { 6416 return this.x /= e.x, this.y /= e.y, this.z /= e.z, this; 6417 } 6418 /** 6419 * Divides this vector by the given scalar. 6420 * 6421 * @param {number} scalar - The scalar to divide. 6422 * @return {Vector3} A reference to this vector. 6423 */ 6424 divideScalar(e) { 6425 return this.multiplyScalar(1 / e); 6426 } 6427 /** 6428 * If this vector's x, y or z value is greater than the given vector's x, y or z 6429 * value, replace that value with the corresponding min value. 6430 * 6431 * @param {Vector3} v - The vector. 6432 * @return {Vector3} A reference to this vector. 6433 */ 6434 min(e) { 6435 return this.x = Math.min(this.x, e.x), this.y = Math.min(this.y, e.y), this.z = Math.min(this.z, e.z), this; 6436 } 6437 /** 6438 * If this vector's x, y or z value is less than the given vector's x, y or z 6439 * value, replace that value with the corresponding max value. 6440 * 6441 * @param {Vector3} v - The vector. 6442 * @return {Vector3} A reference to this vector. 6443 */ 6444 max(e) { 6445 return this.x = Math.max(this.x, e.x), this.y = Math.max(this.y, e.y), this.z = Math.max(this.z, e.z), this; 6446 } 6447 /** 6448 * If this vector's x, y or z value is greater than the max vector's x, y or z 6449 * value, it is replaced by the corresponding value. 6450 * If this vector's x, y or z value is less than the min vector's x, y or z value, 6451 * it is replaced by the corresponding value. 6452 * 6453 * @param {Vector3} min - The minimum x, y and z values. 6454 * @param {Vector3} max - The maximum x, y and z values in the desired range. 6455 * @return {Vector3} A reference to this vector. 6456 */ 6457 clamp(e, t) { 6458 return this.x = yt(this.x, e.x, t.x), this.y = yt(this.y, e.y, t.y), this.z = yt(this.z, e.z, t.z), this; 6459 } 6460 /** 6461 * If this vector's x, y or z values are greater than the max value, they are 6462 * replaced by the max value. 6463 * If this vector's x, y or z values are less than the min value, they are 6464 * replaced by the min value. 6465 * 6466 * @param {number} minVal - The minimum value the components will be clamped to. 6467 * @param {number} maxVal - The maximum value the components will be clamped to. 6468 * @return {Vector3} A reference to this vector. 6469 */ 6470 clampScalar(e, t) { 6471 return this.x = yt(this.x, e, t), this.y = yt(this.y, e, t), this.z = yt(this.z, e, t), this; 6472 } 6473 /** 6474 * If this vector's length is greater than the max value, it is replaced by 6475 * the max value. 6476 * If this vector's length is less than the min value, it is replaced by the 6477 * min value. 6478 * 6479 * @param {number} min - The minimum value the vector length will be clamped to. 6480 * @param {number} max - The maximum value the vector length will be clamped to. 6481 * @return {Vector3} A reference to this vector. 6482 */ 6483 clampLength(e, t) { 6484 const i = this.length(); 6485 return this.divideScalar(i || 1).multiplyScalar(yt(i, e, t)); 6486 } 6487 /** 6488 * The components of this vector are rounded down to the nearest integer value. 6489 * 6490 * @return {Vector3} A reference to this vector. 6491 */ 6492 floor() { 6493 return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this.z = Math.floor(this.z), this; 6494 } 6495 /** 6496 * The components of this vector are rounded up to the nearest integer value. 6497 * 6498 * @return {Vector3} A reference to this vector. 6499 */ 6500 ceil() { 6501 return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this.z = Math.ceil(this.z), this; 6502 } 6503 /** 6504 * The components of this vector are rounded to the nearest integer value 6505 * 6506 * @return {Vector3} A reference to this vector. 6507 */ 6508 round() { 6509 return this.x = Math.round(this.x), this.y = Math.round(this.y), this.z = Math.round(this.z), this; 6510 } 6511 /** 6512 * The components of this vector are rounded towards zero (up if negative, 6513 * down if positive) to an integer value. 6514 * 6515 * @return {Vector3} A reference to this vector. 6516 */ 6517 roundToZero() { 6518 return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this.z = Math.trunc(this.z), this; 6519 } 6520 /** 6521 * Inverts this vector - i.e. sets x = -x, y = -y and z = -z. 6522 * 6523 * @return {Vector3} A reference to this vector. 6524 */ 6525 negate() { 6526 return this.x = -this.x, this.y = -this.y, this.z = -this.z, this; 6527 } 6528 /** 6529 * Calculates the dot product of the given vector with this instance. 6530 * 6531 * @param {Vector3} v - The vector to compute the dot product with. 6532 * @return {number} The result of the dot product. 6533 */ 6534 dot(e) { 6535 return this.x * e.x + this.y * e.y + this.z * e.z; 6536 } 6537 /** 6538 * Computes the square of the Euclidean length (straight-line length) from 6539 * (0, 0, 0) to (x, y, z). If you are comparing the lengths of vectors, you should 6540 * compare the length squared instead as it is slightly more efficient to calculate. 6541 * 6542 * @return {number} The square length of this vector. 6543 */ 6544 lengthSq() { 6545 return this.x * this.x + this.y * this.y + this.z * this.z; 6546 } 6547 /** 6548 * Computes the Euclidean length (straight-line length) from (0, 0, 0) to (x, y, z). 6549 * 6550 * @return {number} The length of this vector. 6551 */ 6552 length() { 6553 return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z); 6554 } 6555 /** 6556 * Computes the Manhattan length of this vector. 6557 * 6558 * @return {number} The length of this vector. 6559 */ 6560 manhattanLength() { 6561 return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z); 6562 } 6563 /** 6564 * Converts this vector to a unit vector - that is, sets it equal to a vector 6565 * with the same direction as this one, but with a vector length of `1`. 6566 * 6567 * @return {Vector3} A reference to this vector. 6568 */ 6569 normalize() { 6570 return this.divideScalar(this.length() || 1); 6571 } 6572 /** 6573 * Sets this vector to a vector with the same direction as this one, but 6574 * with the specified length. 6575 * 6576 * @param {number} length - The new length of this vector. 6577 * @return {Vector3} A reference to this vector. 6578 */ 6579 setLength(e) { 6580 return this.normalize().multiplyScalar(e); 6581 } 6582 /** 6583 * Linearly interpolates between the given vector and this instance, where 6584 * alpha is the percent distance along the line - alpha = 0 will be this 6585 * vector, and alpha = 1 will be the given one. 6586 * 6587 * @param {Vector3} v - The vector to interpolate towards. 6588 * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. 6589 * @return {Vector3} A reference to this vector. 6590 */ 6591 lerp(e, t) { 6592 return this.x += (e.x - this.x) * t, this.y += (e.y - this.y) * t, this.z += (e.z - this.z) * t, this; 6593 } 6594 /** 6595 * Linearly interpolates between the given vectors, where alpha is the percent 6596 * distance along the line - alpha = 0 will be first vector, and alpha = 1 will 6597 * be the second one. The result is stored in this instance. 6598 * 6599 * @param {Vector3} v1 - The first vector. 6600 * @param {Vector3} v2 - The second vector. 6601 * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. 6602 * @return {Vector3} A reference to this vector. 6603 */ 6604 lerpVectors(e, t, i) { 6605 return this.x = e.x + (t.x - e.x) * i, this.y = e.y + (t.y - e.y) * i, this.z = e.z + (t.z - e.z) * i, this; 6606 } 6607 /** 6608 * Calculates the cross product of the given vector with this instance. 6609 * 6610 * @param {Vector3} v - The vector to compute the cross product with. 6611 * @return {Vector3} The result of the cross product. 6612 */ 6613 cross(e) { 6614 return this.crossVectors(this, e); 6615 } 6616 /** 6617 * Calculates the cross product of the given vectors and stores the result 6618 * in this instance. 6619 * 6620 * @param {Vector3} a - The first vector. 6621 * @param {Vector3} b - The second vector. 6622 * @return {Vector3} A reference to this vector. 6623 */ 6624 crossVectors(e, t) { 6625 const i = e.x, r = e.y, s = e.z, a = t.x, l = t.y, o = t.z; 6626 return this.x = r * o - s * l, this.y = s * a - i * o, this.z = i * l - r * a, this; 6627 } 6628 /** 6629 * Projects this vector onto the given one. 6630 * 6631 * @param {Vector3} v - The vector to project to. 6632 * @return {Vector3} A reference to this vector. 6633 */ 6634 projectOnVector(e) { 6635 const t = e.lengthSq(); 6636 if (t === 0) return this.set(0, 0, 0); 6637 const i = e.dot(this) / t; 6638 return this.copy(e).multiplyScalar(i); 6639 } 6640 /** 6641 * Projects this vector onto a plane by subtracting this 6642 * vector projected onto the plane's normal from this vector. 6643 * 6644 * @param {Vector3} planeNormal - The plane normal. 6645 * @return {Vector3} A reference to this vector. 6646 */ 6647 projectOnPlane(e) { 6648 return ml.copy(this).projectOnVector(e), this.sub(ml); 6649 } 6650 /** 6651 * Reflects this vector off a plane orthogonal to the given normal vector. 6652 * 6653 * @param {Vector3} normal - The (normalized) normal vector. 6654 * @return {Vector3} A reference to this vector. 6655 */ 6656 reflect(e) { 6657 return this.sub(ml.copy(e).multiplyScalar(2 * this.dot(e))); 6658 } 6659 /** 6660 * Returns the angle between the given vector and this instance in radians. 6661 * 6662 * @param {Vector3} v - The vector to compute the angle with. 6663 * @return {number} The angle in radians. 6664 */ 6665 angleTo(e) { 6666 const t = Math.sqrt(this.lengthSq() * e.lengthSq()); 6667 if (t === 0) return Math.PI / 2; 6668 const i = this.dot(e) / t; 6669 return Math.acos(yt(i, -1, 1)); 6670 } 6671 /** 6672 * Computes the distance from the given vector to this instance. 6673 * 6674 * @param {Vector3} v - The vector to compute the distance to. 6675 * @return {number} The distance. 6676 */ 6677 distanceTo(e) { 6678 return Math.sqrt(this.distanceToSquared(e)); 6679 } 6680 /** 6681 * Computes the squared distance from the given vector to this instance. 6682 * If you are just comparing the distance with another distance, you should compare 6683 * the distance squared instead as it is slightly more efficient to calculate. 6684 * 6685 * @param {Vector3} v - The vector to compute the squared distance to. 6686 * @return {number} The squared distance. 6687 */ 6688 distanceToSquared(e) { 6689 const t = this.x - e.x, i = this.y - e.y, r = this.z - e.z; 6690 return t * t + i * i + r * r; 6691 } 6692 /** 6693 * Computes the Manhattan distance from the given vector to this instance. 6694 * 6695 * @param {Vector3} v - The vector to compute the Manhattan distance to. 6696 * @return {number} The Manhattan distance. 6697 */ 6698 manhattanDistanceTo(e) { 6699 return Math.abs(this.x - e.x) + Math.abs(this.y - e.y) + Math.abs(this.z - e.z); 6700 } 6701 /** 6702 * Sets the vector components from the given spherical coordinates. 6703 * 6704 * @param {Spherical} s - The spherical coordinates. 6705 * @return {Vector3} A reference to this vector. 6706 */ 6707 setFromSpherical(e) { 6708 return this.setFromSphericalCoords(e.radius, e.phi, e.theta); 6709 } 6710 /** 6711 * Sets the vector components from the given spherical coordinates. 6712 * 6713 * @param {number} radius - The radius. 6714 * @param {number} phi - The phi angle in radians. 6715 * @param {number} theta - The theta angle in radians. 6716 * @return {Vector3} A reference to this vector. 6717 */ 6718 setFromSphericalCoords(e, t, i) { 6719 const r = Math.sin(t) * e; 6720 return this.x = r * Math.sin(i), this.y = Math.cos(t) * e, this.z = r * Math.cos(i), this; 6721 } 6722 /** 6723 * Sets the vector components from the given cylindrical coordinates. 6724 * 6725 * @param {Cylindrical} c - The cylindrical coordinates. 6726 * @return {Vector3} A reference to this vector. 6727 */ 6728 setFromCylindrical(e) { 6729 return this.setFromCylindricalCoords(e.radius, e.theta, e.y); 6730 } 6731 /** 6732 * Sets the vector components from the given cylindrical coordinates. 6733 * 6734 * @param {number} radius - The radius. 6735 * @param {number} theta - The theta angle in radians. 6736 * @param {number} y - The y value. 6737 * @return {Vector3} A reference to this vector. 6738 */ 6739 setFromCylindricalCoords(e, t, i) { 6740 return this.x = e * Math.sin(t), this.y = i, this.z = e * Math.cos(t), this; 6741 } 6742 /** 6743 * Sets the vector components to the position elements of the 6744 * given transformation matrix. 6745 * 6746 * @param {Matrix4} m - The 4x4 matrix. 6747 * @return {Vector3} A reference to this vector. 6748 */ 6749 setFromMatrixPosition(e) { 6750 const t = e.elements; 6751 return this.x = t[12], this.y = t[13], this.z = t[14], this; 6752 } 6753 /** 6754 * Sets the vector components to the scale elements of the 6755 * given transformation matrix. 6756 * 6757 * @param {Matrix4} m - The 4x4 matrix. 6758 * @return {Vector3} A reference to this vector. 6759 */ 6760 setFromMatrixScale(e) { 6761 const t = this.setFromMatrixColumn(e, 0).length(), i = this.setFromMatrixColumn(e, 1).length(), r = this.setFromMatrixColumn(e, 2).length(); 6762 return this.x = t, this.y = i, this.z = r, this; 6763 } 6764 /** 6765 * Sets the vector components from the specified matrix column. 6766 * 6767 * @param {Matrix4} m - The 4x4 matrix. 6768 * @param {number} index - The column index. 6769 * @return {Vector3} A reference to this vector. 6770 */ 6771 setFromMatrixColumn(e, t) { 6772 return this.fromArray(e.elements, t * 4); 6773 } 6774 /** 6775 * Sets the vector components from the specified matrix column. 6776 * 6777 * @param {Matrix3} m - The 3x3 matrix. 6778 * @param {number} index - The column index. 6779 * @return {Vector3} A reference to this vector. 6780 */ 6781 setFromMatrix3Column(e, t) { 6782 return this.fromArray(e.elements, t * 3); 6783 } 6784 /** 6785 * Sets the vector components from the given Euler angles. 6786 * 6787 * @param {Euler} e - The Euler angles to set. 6788 * @return {Vector3} A reference to this vector. 6789 */ 6790 setFromEuler(e) { 6791 return this.x = e._x, this.y = e._y, this.z = e._z, this; 6792 } 6793 /** 6794 * Sets the vector components from the RGB components of the 6795 * given color. 6796 * 6797 * @param {Color} c - The color to set. 6798 * @return {Vector3} A reference to this vector. 6799 */ 6800 setFromColor(e) { 6801 return this.x = e.r, this.y = e.g, this.z = e.b, this; 6802 } 6803 /** 6804 * Returns `true` if this vector is equal with the given one. 6805 * 6806 * @param {Vector3} v - The vector to test for equality. 6807 * @return {boolean} Whether this vector is equal with the given one. 6808 */ 6809 equals(e) { 6810 return e.x === this.x && e.y === this.y && e.z === this.z; 6811 } 6812 /** 6813 * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]` 6814 * and z value to be `array[ offset + 2 ]`. 6815 * 6816 * @param {Array<number>} array - An array holding the vector component values. 6817 * @param {number} [offset=0] - The offset into the array. 6818 * @return {Vector3} A reference to this vector. 6819 */ 6820 fromArray(e, t = 0) { 6821 return this.x = e[t], this.y = e[t + 1], this.z = e[t + 2], this; 6822 } 6823 /** 6824 * Writes the components of this vector to the given array. If no array is provided, 6825 * the method returns a new instance. 6826 * 6827 * @param {Array<number>} [array=[]] - The target array holding the vector components. 6828 * @param {number} [offset=0] - Index of the first element in the array. 6829 * @return {Array<number>} The vector components. 6830 */ 6831 toArray(e = [], t = 0) { 6832 return e[t] = this.x, e[t + 1] = this.y, e[t + 2] = this.z, e; 6833 } 6834 /** 6835 * Sets the components of this vector from the given buffer attribute. 6836 * 6837 * @param {BufferAttribute} attribute - The buffer attribute holding vector data. 6838 * @param {number} index - The index into the attribute. 6839 * @return {Vector3} A reference to this vector. 6840 */ 6841 fromBufferAttribute(e, t) { 6842 return this.x = e.getX(t), this.y = e.getY(t), this.z = e.getZ(t), this; 6843 } 6844 /** 6845 * Sets each component of this vector to a pseudo-random value between `0` and 6846 * `1`, excluding `1`. 6847 * 6848 * @return {Vector3} A reference to this vector. 6849 */ 6850 random() { 6851 return this.x = Math.random(), this.y = Math.random(), this.z = Math.random(), this; 6852 } 6853 /** 6854 * Sets this vector to a uniformly random point on a unit sphere. 6855 * 6856 * @return {Vector3} A reference to this vector. 6857 */ 6858 randomDirection() { 6859 const e = Math.random() * Math.PI * 2, t = Math.random() * 2 - 1, i = Math.sqrt(1 - t * t); 6860 return this.x = i * Math.cos(e), this.y = t, this.z = i * Math.sin(e), this; 6861 } 6862 *[Symbol.iterator]() { 6863 yield this.x, yield this.y, yield this.z; 6864 } 6865}; 6866sh.prototype.isVector3 = !0; 6867let W = sh; 6868const ml = /* @__PURE__ */ new W(), qh = /* @__PURE__ */ new Wn(), ah = class ah { 6869 /** 6870 * Constructs a new 3x3 matrix. The arguments are supposed to be 6871 * in row-major order. If no arguments are provided, the constructor 6872 * initializes the matrix as an identity matrix. 6873 * 6874 * @param {number} [n11] - 1-1 matrix element. 6875 * @param {number} [n12] - 1-2 matrix element. 6876 * @param {number} [n13] - 1-3 matrix element. 6877 * @param {number} [n21] - 2-1 matrix element. 6878 * @param {number} [n22] - 2-2 matrix element. 6879 * @param {number} [n23] - 2-3 matrix element. 6880 * @param {number} [n31] - 3-1 matrix element. 6881 * @param {number} [n32] - 3-2 matrix element. 6882 * @param {number} [n33] - 3-3 matrix element. 6883 */ 6884 constructor(e, t, i, r, s, a, l, o, c) { 6885 this.elements = [ 6886 1, 6887 0, 6888 0, 6889 0, 6890 1, 6891 0, 6892 0, 6893 0, 6894 1 6895 ], e !== void 0 && this.set(e, t, i, r, s, a, l, o, c); 6896 } 6897 /** 6898 * Sets the elements of the matrix.The arguments are supposed to be 6899 * in row-major order. 6900 * 6901 * @param {number} [n11] - 1-1 matrix element. 6902 * @param {number} [n12] - 1-2 matrix element. 6903 * @param {number} [n13] - 1-3 matrix element. 6904 * @param {number} [n21] - 2-1 matrix element. 6905 * @param {number} [n22] - 2-2 matrix element. 6906 * @param {number} [n23] - 2-3 matrix element. 6907 * @param {number} [n31] - 3-1 matrix element. 6908 * @param {number} [n32] - 3-2 matrix element. 6909 * @param {number} [n33] - 3-3 matrix element. 6910 * @return {Matrix3} A reference to this matrix. 6911 */ 6912 set(e, t, i, r, s, a, l, o, c) { 6913 const u = this.elements; 6914 return u[0] = e, u[1] = r, u[2] = l, u[3] = t, u[4] = s, u[5] = o, u[6] = i, u[7] = a, u[8] = c, this; 6915 } 6916 /** 6917 * Sets this matrix to the 3x3 identity matrix. 6918 * 6919 * @return {Matrix3} A reference to this matrix. 6920 */ 6921 identity() { 6922 return this.set( 6923 1, 6924 0, 6925 0, 6926 0, 6927 1, 6928 0, 6929 0, 6930 0, 6931 1 6932 ), this; 6933 } 6934 /** 6935 * Copies the values of the given matrix to this instance. 6936 * 6937 * @param {Matrix3} m - The matrix to copy. 6938 * @return {Matrix3} A reference to this matrix. 6939 */ 6940 copy(e) { 6941 const t = this.elements, i = e.elements; 6942 return t[0] = i[0], t[1] = i[1], t[2] = i[2], t[3] = i[3], t[4] = i[4], t[5] = i[5], t[6] = i[6], t[7] = i[7], t[8] = i[8], this; 6943 } 6944 /** 6945 * Extracts the basis of this matrix into the three axis vectors provided. 6946 * 6947 * @param {Vector3} xAxis - The basis's x axis. 6948 * @param {Vector3} yAxis - The basis's y axis. 6949 * @param {Vector3} zAxis - The basis's z axis. 6950 * @return {Matrix3} A reference to this matrix. 6951 */ 6952 extractBasis(e, t, i) { 6953 return e.setFromMatrix3Column(this, 0), t.setFromMatrix3Column(this, 1), i.setFromMatrix3Column(this, 2), this; 6954 } 6955 /** 6956 * Set this matrix to the upper 3x3 matrix of the given 4x4 matrix. 6957 * 6958 * @param {Matrix4} m - The 4x4 matrix. 6959 * @return {Matrix3} A reference to this matrix. 6960 */ 6961 setFromMatrix4(e) { 6962 const t = e.elements; 6963 return this.set( 6964 t[0], 6965 t[4], 6966 t[8], 6967 t[1], 6968 t[5], 6969 t[9], 6970 t[2], 6971 t[6], 6972 t[10] 6973 ), this; 6974 } 6975 /** 6976 * Post-multiplies this matrix by the given 3x3 matrix. 6977 * 6978 * @param {Matrix3} m - The matrix to multiply with. 6979 * @return {Matrix3} A reference to this matrix. 6980 */ 6981 multiply(e) { 6982 return this.multiplyMatrices(this, e); 6983 } 6984 /** 6985 * Pre-multiplies this matrix by the given 3x3 matrix. 6986 * 6987 * @param {Matrix3} m - The matrix to multiply with. 6988 * @return {Matrix3} A reference to this matrix. 6989 */ 6990 premultiply(e) { 6991 return this.multiplyMatrices(e, this); 6992 } 6993 /** 6994 * Multiples the given 3x3 matrices and stores the result 6995 * in this matrix. 6996 * 6997 * @param {Matrix3} a - The first matrix. 6998 * @param {Matrix3} b - The second matrix. 6999 * @return {Matrix3} A reference to this matrix. 7000 */ 7001 multiplyMatrices(e, t) { 7002 const i = e.elements, r = t.elements, s = this.elements, a = i[0], l = i[3], o = i[6], c = i[1], u = i[4], h = i[7], d = i[2], f = i[5], p = i[8], v = r[0], m = r[3], g = r[6], _ = r[1], x = r[4], E = r[7], R = r[2], T = r[5], w = r[8]; 7003 return s[0] = a * v + l * _ + o * R, s[3] = a * m + l * x + o * T, s[6] = a * g + l * E + o * w, s[1] = c * v + u * _ + h * R, s[4] = c * m + u * x + h * T, s[7] = c * g + u * E + h * w, s[2] = d * v + f * _ + p * R, s[5] = d * m + f * x + p * T, s[8] = d * g + f * E + p * w, this; 7004 } 7005 /** 7006 * Multiplies every component of the matrix by the given scalar. 7007 * 7008 * @param {number} s - The scalar. 7009 * @return {Matrix3} A reference to this matrix. 7010 */ 7011 multiplyScalar(e) { 7012 const t = this.elements; 7013 return t[0] *= e, t[3] *= e, t[6] *= e, t[1] *= e, t[4] *= e, t[7] *= e, t[2] *= e, t[5] *= e, t[8] *= e, this; 7014 } 7015 /** 7016 * Computes and returns the determinant of this matrix. 7017 * 7018 * @return {number} The determinant. 7019 */ 7020 determinant() { 7021 const e = this.elements, t = e[0], i = e[1], r = e[2], s = e[3], a = e[4], l = e[5], o = e[6], c = e[7], u = e[8]; 7022 return t * a * u - t * l * c - i * s * u + i * l * o + r * s * c - r * a * o; 7023 } 7024 /** 7025 * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution). 7026 * You can not invert with a determinant of zero. If you attempt this, the method produces 7027 * a zero matrix instead. 7028 * 7029 * @return {Matrix3} A reference to this matrix. 7030 */ 7031 invert() { 7032 const e = this.elements, t = e[0], i = e[1], r = e[2], s = e[3], a = e[4], l = e[5], o = e[6], c = e[7], u = e[8], h = u * a - l * c, d = l * o - u * s, f = c * s - a * o, p = t * h + i * d + r * f; 7033 if (p === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0); 7034 const v = 1 / p; 7035 return e[0] = h * v, e[1] = (r * c - u * i) * v, e[2] = (l * i - r * a) * v, e[3] = d * v, e[4] = (u * t - r * o) * v, e[5] = (r * s - l * t) * v, e[6] = f * v, e[7] = (i * o - c * t) * v, e[8] = (a * t - i * s) * v, this; 7036 } 7037 /** 7038 * Transposes this matrix in place. 7039 * 7040 * @return {Matrix3} A reference to this matrix. 7041 */ 7042 transpose() { 7043 let e; 7044 const t = this.elements; 7045 return e = t[1], t[1] = t[3], t[3] = e, e = t[2], t[2] = t[6], t[6] = e, e = t[5], t[5] = t[7], t[7] = e, this; 7046 } 7047 /** 7048 * Computes the normal matrix which is the inverse transpose of the upper 7049 * left 3x3 portion of the given 4x4 matrix. 7050 * 7051 * @param {Matrix4} matrix4 - The 4x4 matrix. 7052 * @return {Matrix3} A reference to this matrix. 7053 */ 7054 getNormalMatrix(e) { 7055 return this.setFromMatrix4(e).invert().transpose(); 7056 } 7057 /** 7058 * Transposes this matrix into the supplied array, and returns itself unchanged. 7059 * 7060 * @param {Array<number>} r - An array to store the transposed matrix elements. 7061 * @return {Matrix3} A reference to this matrix. 7062 */ 7063 transposeIntoArray(e) { 7064 const t = this.elements; 7065 return e[0] = t[0], e[1] = t[3], e[2] = t[6], e[3] = t[1], e[4] = t[4], e[5] = t[7], e[6] = t[2], e[7] = t[5], e[8] = t[8], this; 7066 } 7067 /** 7068 * Sets the UV transform matrix from offset, repeat, rotation, and center. 7069 * 7070 * @param {number} tx - Offset x. 7071 * @param {number} ty - Offset y. 7072 * @param {number} sx - Repeat x. 7073 * @param {number} sy - Repeat y. 7074 * @param {number} rotation - Rotation, in radians. Positive values rotate counterclockwise. 7075 * @param {number} cx - Center x of rotation. 7076 * @param {number} cy - Center y of rotation 7077 * @return {Matrix3} A reference to this matrix. 7078 */ 7079 setUvTransform(e, t, i, r, s, a, l) { 7080 const o = Math.cos(s), c = Math.sin(s); 7081 return this.set( 7082 i * o, 7083 i * c, 7084 -i * (o * a + c * l) + a + e, 7085 -r * c, 7086 r * o, 7087 -r * (-c * a + o * l) + l + t, 7088 0, 7089 0, 7090 1 7091 ), this; 7092 } 7093 /** 7094 * Scales this matrix with the given scalar values. 7095 * 7096 * @param {number} sx - The amount to scale in the X axis. 7097 * @param {number} sy - The amount to scale in the Y axis. 7098 * @return {Matrix3} A reference to this matrix. 7099 */ 7100 scale(e, t) { 7101 return this.premultiply(gl.makeScale(e, t)), this; 7102 } 7103 /** 7104 * Rotates this matrix by the given angle. 7105 * 7106 * @param {number} theta - The rotation in radians. 7107 * @return {Matrix3} A reference to this matrix. 7108 */ 7109 rotate(e) { 7110 return this.premultiply(gl.makeRotation(-e)), this; 7111 } 7112 /** 7113 * Translates this matrix by the given scalar values. 7114 * 7115 * @param {number} tx - The amount to translate in the X axis. 7116 * @param {number} ty - The amount to translate in the Y axis. 7117 * @return {Matrix3} A reference to this matrix. 7118 */ 7119 translate(e, t) { 7120 return this.premultiply(gl.makeTranslation(e, t)), this; 7121 } 7122 // for 2D Transforms 7123 /** 7124 * Sets this matrix as a 2D translation transform. 7125 * 7126 * @param {number|Vector2} x - The amount to translate in the X axis or alternatively a translation vector. 7127 * @param {number} y - The amount to translate in the Y axis. 7128 * @return {Matrix3} A reference to this matrix. 7129 */ 7130 makeTranslation(e, t) { 7131 return e.isVector2 ? this.set( 7132 1, 7133 0, 7134 e.x, 7135 0, 7136 1, 7137 e.y, 7138 0, 7139 0, 7140 1 7141 ) : this.set( 7142 1, 7143 0, 7144 e, 7145 0, 7146 1, 7147 t, 7148 0, 7149 0, 7150 1 7151 ), this; 7152 } 7153 /** 7154 * Sets this matrix as a 2D rotational transformation. 7155 * 7156 * @param {number} theta - The rotation in radians. 7157 * @return {Matrix3} A reference to this matrix. 7158 */ 7159 makeRotation(e) { 7160 const t = Math.cos(e), i = Math.sin(e); 7161 return this.set( 7162 t, 7163 -i, 7164 0, 7165 i, 7166 t, 7167 0, 7168 0, 7169 0, 7170 1 7171 ), this; 7172 } 7173 /** 7174 * Sets this matrix as a 2D scale transform. 7175 * 7176 * @param {number} x - The amount to scale in the X axis. 7177 * @param {number} y - The amount to scale in the Y axis. 7178 * @return {Matrix3} A reference to this matrix. 7179 */ 7180 makeScale(e, t) { 7181 return this.set( 7182 e, 7183 0, 7184 0, 7185 0, 7186 t, 7187 0, 7188 0, 7189 0, 7190 1 7191 ), this; 7192 } 7193 /** 7194 * Returns `true` if this matrix is equal with the given one. 7195 * 7196 * @param {Matrix3} matrix - The matrix to test for equality. 7197 * @return {boolean} Whether this matrix is equal with the given one. 7198 */ 7199 equals(e) { 7200 const t = this.elements, i = e.elements; 7201 for (let r = 0; r < 9; r++) 7202 if (t[r] !== i[r]) return !1; 7203 return !0; 7204 } 7205 /** 7206 * Sets the elements of the matrix from the given array. 7207 * 7208 * @param {Array<number>} array - The matrix elements in column-major order. 7209 * @param {number} [offset=0] - Index of the first element in the array. 7210 * @return {Matrix3} A reference to this matrix. 7211 */ 7212 fromArray(e, t = 0) { 7213 for (let i = 0; i < 9; i++) 7214 this.elements[i] = e[i + t]; 7215 return this; 7216 } 7217 /** 7218 * Writes the elements of this matrix to the given array. If no array is provided, 7219 * the method returns a new instance. 7220 * 7221 * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order. 7222 * @param {number} [offset=0] - Index of the first element in the array. 7223 * @return {Array<number>} The matrix elements in column-major order. 7224 */ 7225 toArray(e = [], t = 0) { 7226 const i = this.elements; 7227 return e[t] = i[0], e[t + 1] = i[1], e[t + 2] = i[2], e[t + 3] = i[3], e[t + 4] = i[4], e[t + 5] = i[5], e[t + 6] = i[6], e[t + 7] = i[7], e[t + 8] = i[8], e; 7228 } 7229 /** 7230 * Returns a matrix with copied values from this instance. 7231 * 7232 * @return {Matrix3} A clone of this instance. 7233 */ 7234 clone() { 7235 return new this.constructor().fromArray(this.elements); 7236 } 7237}; 7238ah.prototype.isMatrix3 = !0; 7239let ot = ah; 7240const gl = /* @__PURE__ */ new ot(), Yh = /* @__PURE__ */ new ot().set( 7241 0.4123908, 7242 0.3575843, 7243 0.1804808, 7244 0.212639, 7245 0.7151687, 7246 0.0721923, 7247 0.0193308, 7248 0.1191948, 7249 0.9505322 7250), Kh = /* @__PURE__ */ new ot().set( 7251 3.2409699, 7252 -1.5373832, 7253 -0.4986108, 7254 -0.9692436, 7255 1.8759675, 7256 0.0415551, 7257 0.0556301, 7258 -0.203977, 7259 1.0569715 7260); 7261function A_() { 7262 const n = { 7263 enabled: !0, 7264 workingColorSpace: Po, 7265 /** 7266 * Implementations of supported color spaces. 7267 * 7268 * Required: 7269 * - primaries: chromaticity coordinates [ rx ry gx gy bx by ] 7270 * - whitePoint: reference white [ x y ] 7271 * - transfer: transfer function (pre-defined) 7272 * - toXYZ: Matrix3 RGB to XYZ transform 7273 * - fromXYZ: Matrix3 XYZ to RGB transform 7274 * - luminanceCoefficients: RGB luminance coefficients 7275 * 7276 * Optional: 7277 * - outputColorSpaceConfig: { drawingBufferColorSpace: ColorSpace, toneMappingMode: 'extended' | 'standard' } 7278 * - workingColorSpaceConfig: { unpackColorSpace: ColorSpace } 7279 * 7280 * Reference: 7281 * - https://www.russellcottrell.com/photo/matrixCalculator.htm 7282 */ 7283 spaces: {}, 7284 convert: function(r, s, a) { 7285 return this.enabled === !1 || s === a || !s || !a || (this.spaces[s].transfer === Nt && (r.r = Oi(r.r), r.g = Oi(r.g), r.b = Oi(r.b)), this.spaces[s].primaries !== this.spaces[a].primaries && (r.applyMatrix3(this.spaces[s].toXYZ), r.applyMatrix3(this.spaces[a].fromXYZ)), this.spaces[a].transfer === Nt && (r.r = ds(r.r), r.g = ds(r.g), r.b = ds(r.b))), r; 7286 }, 7287 workingToColorSpace: function(r, s) { 7288 return this.convert(r, this.workingColorSpace, s); 7289 }, 7290 colorSpaceToWorking: function(r, s) { 7291 return this.convert(r, s, this.workingColorSpace); 7292 }, 7293 getPrimaries: function(r) { 7294 return this.spaces[r].primaries; 7295 }, 7296 getTransfer: function(r) { 7297 return r === Ji ? Lo : this.spaces[r].transfer; 7298 }, 7299 getToneMappingMode: function(r) { 7300 return this.spaces[r].outputColorSpaceConfig.toneMappingMode || "standard"; 7301 }, 7302 getLuminanceCoefficients: function(r, s = this.workingColorSpace) { 7303 return r.fromArray(this.spaces[s].luminanceCoefficients); 7304 }, 7305 define: function(r) { 7306 Object.assign(this.spaces, r); 7307 }, 7308 // Internal APIs 7309 _getMatrix: function(r, s, a) { 7310 return r.copy(this.spaces[s].toXYZ).multiply(this.spaces[a].fromXYZ); 7311 }, 7312 _getDrawingBufferColorSpace: function(r) { 7313 return this.spaces[r].outputColorSpaceConfig.drawingBufferColorSpace; 7314 }, 7315 _getUnpackColorSpace: function(r = this.workingColorSpace) { 7316 return this.spaces[r].workingColorSpaceConfig.unpackColorSpace; 7317 }, 7318 // Deprecated 7319 fromWorkingColorSpace: function(r, s) { 7320 return Kc("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."), n.workingToColorSpace(r, s); 7321 }, 7322 toWorkingColorSpace: function(r, s) { 7323 return Kc("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."), n.colorSpaceToWorking(r, s); 7324 } 7325 }, e = [0.64, 0.33, 0.3, 0.6, 0.15, 0.06], t = [0.2126, 0.7152, 0.0722], i = [0.3127, 0.329]; 7326 return n.define({ 7327 [Po]: { 7328 primaries: e, 7329 whitePoint: i, 7330 transfer: Lo, 7331 toXYZ: Yh, 7332 fromXYZ: Kh, 7333 luminanceCoefficients: t, 7334 workingColorSpaceConfig: { unpackColorSpace: Hn },
7335 outputColorSpaceConfig: { drawingBufferColorSpace: Hn } 7336 }, 7337 [Hn]: { 7338 primaries: e, 7339 whitePoint: i, 7340 transfer: Nt, 7341 toXYZ: Yh, 7342 fromXYZ: Kh, 7343 luminanceCoefficients: t, 7344 outputColorSpaceConfig: { drawingBufferColorSpace: Hn } 7345 } 7346 }), n; 7347} 7348const _t = /* @__PURE__ */ A_(); 7349function Oi(n) { 7350 return n < 0.04045 ? n * 0.0773993808 : Math.pow(n * 0.9478672986 + 0.0521327014, 2.4); 7351} 7352function ds(n) { 7353 return n < 31308e-7 ? n * 12.92 : 1.055 * Math.pow(n, 0.41666) - 0.055; 7354} 7355let Fr; 7356class R_ { 7357 /** 7358 * Returns a data URI containing a representation of the given image. 7359 * 7360 * @param {(HTMLImageElement|HTMLCanvasElement)} image - The image object. 7361 * @param {string} [type='image/png'] - Indicates the image format. 7362 * @return {string} The data URI. 7363 */ 7364 static getDataURL(e, t = "image/png") { 7365 if (/^data:/i.test(e.src) || typeof HTMLCanvasElement > "u") 7366 return e.src; 7367 let i; 7368 if (e instanceof HTMLCanvasElement) 7369 i = e; 7370 else { 7371 Fr === void 0 && (Fr = No("canvas")), Fr.width = e.width, Fr.height = e.height; 7372 const r = Fr.getContext("2d"); 7373 e instanceof ImageData ? r.putImageData(e, 0, 0) : r.drawImage(e, 0, 0, e.width, e.height), i = Fr; 7374 } 7375 return i.toDataURL(t); 7376 } 7377 /** 7378 * Converts the given sRGB image data to linear color space. 7379 * 7380 * @param {(HTMLImageElement|HTMLCanvasElement|ImageBitmap|Object)} image - The image object. 7381 * @return {HTMLCanvasElement|Object} The converted image. 7382 */ 7383 static sRGBToLinear(e) { 7384 if (typeof HTMLImageElement < "u" && e instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && e instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && e instanceof ImageBitmap) { 7385 const t = No("canvas"); 7386 t.width = e.width, t.height = e.height; 7387 const i = t.getContext("2d"); 7388 i.drawImage(e, 0, 0, e.width, e.height); 7389 const r = i.getImageData(0, 0, e.width, e.height), s = r.data; 7390 for (let a = 0; a < s.length; a++) 7391 s[a] = Oi(s[a] / 255) * 255; 7392 return i.putImageData(r, 0, 0), t; 7393 } else if (e.data) { 7394 const t = e.data.slice(0); 7395 for (let i = 0; i < t.length; i++) 7396 t instanceof Uint8Array || t instanceof Uint8ClampedArray ? t[i] = Math.floor(Oi(t[i] / 255) * 255) : t[i] = Oi(t[i]); 7397 return { 7398 data: t, 7399 width: e.width, 7400 height: e.height 7401 }; 7402 } else 7403 return tt("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."), e; 7404 } 7405} 7406let C_ = 0; 7407class Gu { 7408 /** 7409 * Constructs a new video texture. 7410 * 7411 * @param {any} [data=null] - The data definition of a texture. 7412 */ 7413 constructor(e = null) { 7414 this.isSource = !0, Object.defineProperty(this, "id", { value: C_++ }), this.uuid = wa(), this.data = e, this.dataReady = !0, this.version = 0; 7415 } 7416 /** 7417 * Returns the dimensions of the source into the given target vector. 7418 * 7419 * @param {(Vector2|Vector3)} target - The target object the result is written into. 7420 * @return {(Vector2|Vector3)} The dimensions of the source. 7421 */ 7422 getSize(e) { 7423 const t = this.data; 7424 return typeof HTMLVideoElement < "u" && t instanceof HTMLVideoElement ? e.set(t.videoWidth, t.videoHeight, 0) : typeof VideoFrame < "u" && t instanceof VideoFrame ? e.set(t.displayWidth, t.displayHeight, 0) : t !== null ? e.set(t.width, t.height, t.depth || 0) : e.set(0, 0, 0), e; 7425 } 7426 /** 7427 * When the property is set to `true`, the engine allocates the memory 7428 * for the texture (if necessary) and triggers the actual texture upload 7429 * to the GPU next time the source is used. 7430 * 7431 * @type {boolean} 7432 * @default false 7433 * @param {boolean} value 7434 */ 7435 set needsUpdate(e) { 7436 e === !0 && this.version++; 7437 } 7438 /** 7439 * Serializes the source into JSON. 7440 * 7441 * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. 7442 * @return {Object} A JSON object representing the serialized source. 7443 * @see {@link ObjectLoader#parse} 7444 */ 7445 toJSON(e) { 7446 const t = e === void 0 || typeof e == "string"; 7447 if (!t && e.images[this.uuid] !== void 0) 7448 return e.images[this.uuid]; 7449 const i = { 7450 uuid: this.uuid, 7451 url: "" 7452 }, r = this.data; 7453 if (r !== null) { 7454 let s; 7455 if (Array.isArray(r)) { 7456 s = []; 7457 for (let a = 0, l = r.length; a < l; a++) 7458 r[a].isDataTexture ? s.push(vl(r[a].image)) : s.push(vl(r[a])); 7459 } else 7460 s = vl(r); 7461 i.url = s; 7462 } 7463 return t || (e.images[this.uuid] = i), i; 7464 } 7465} 7466function vl(n) { 7467 return typeof HTMLImageElement < "u" && n instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && n instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && n instanceof ImageBitmap ? R_.getDataURL(n) : n.data ? { 7468 data: Array.from(n.data), 7469 width: n.width, 7470 height: n.height, 7471 type: n.data.constructor.name 7472 } : (tt("Texture: Unable to serialize Texture."), {}); 7473} 7474let P_ = 0; 7475const _l = /* @__PURE__ */ new W(); 7476class gn extends Ir {
vendor: 27,629 bytes, lines 7477-8240
7477 /** 7478 * Constructs a new texture. 7479 * 7480 * @param {?Object} [image=Texture.DEFAULT_IMAGE] - The image holding the texture data. 7481 * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. 7482 * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. 7483 * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. 7484 * @param {number} [magFilter=LinearFilter] - The mag filter value. 7485 * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value. 7486 * @param {number} [format=RGBAFormat] - The texture format. 7487 * @param {number} [type=UnsignedByteType] - The texture type. 7488 * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. 7489 * @param {string} [colorSpace=NoColorSpace] - The color space. 7490 */ 7491 constructor(e = gn.DEFAULT_IMAGE, t = gn.DEFAULT_MAPPING, i = Di, r = Di, s = fn, a = Mr, l = ni, o = Pn, c = gn.DEFAULT_ANISOTROPY, u = Ji) { 7492 super(), this.isTexture = !0, Object.defineProperty(this, "id", { value: P_++ }), this.uuid = wa(), this.name = "", this.source = new Gu(e), this.mipmaps = [], this.mapping = t, this.channel = 0, this.wrapS = i, this.wrapT = r, this.magFilter = s, this.minFilter = a, this.anisotropy = c, this.format = l, this.internalFormat = null, this.type = o, this.offset = new wt(0, 0), this.repeat = new wt(1, 1), this.center = new wt(0, 0), this.rotation = 0, this.matrixAutoUpdate = !0, this.matrix = new ot(), this.generateMipmaps = !0, this.premultiplyAlpha = !1, this.flipY = !0, this.unpackAlignment = 4, this.colorSpace = u, this.userData = {}, this.updateRanges = [], this.version = 0, this.onUpdate = null, this.renderTarget = null, this.isRenderTargetTexture = !1, this.isArrayTexture = !!(e && e.depth && e.depth > 1), this.pmremVersion = 0, this.normalized = !1; 7493 } 7494 /** 7495 * The width of the texture in pixels. 7496 */ 7497 get width() { 7498 return this.source.getSize(_l).x; 7499 } 7500 /** 7501 * The height of the texture in pixels. 7502 */ 7503 get height() { 7504 return this.source.getSize(_l).y; 7505 } 7506 /** 7507 * The depth of the texture in pixels. 7508 */ 7509 get depth() { 7510 return this.source.getSize(_l).z; 7511 } 7512 /** 7513 * The image object holding the texture data. 7514 * 7515 * @type {?Object} 7516 */ 7517 get image() { 7518 return this.source.data; 7519 } 7520 set image(e) { 7521 this.source.data = e; 7522 } 7523 /** 7524 * Updates the texture transformation matrix from the properties {@link Texture#offset}, 7525 * {@link Texture#repeat}, {@link Texture#rotation}, and {@link Texture#center}. 7526 */ 7527 updateMatrix() { 7528 this.matrix.setUvTransform(this.offset.x, this.offset.y, this.repeat.x, this.repeat.y, this.rotation, this.center.x, this.center.y); 7529 } 7530 /** 7531 * Adds a range of data in the data texture to be updated on the GPU. 7532 * 7533 * @param {number} start - Position at which to start update. 7534 * @param {number} count - The number of components to update. 7535 */ 7536 addUpdateRange(e, t) { 7537 this.updateRanges.push({ start: e, count: t }); 7538 } 7539 /** 7540 * Clears the update ranges. 7541 */ 7542 clearUpdateRanges() { 7543 this.updateRanges.length = 0; 7544 } 7545 /** 7546 * Returns a new texture with copied values from this instance. 7547 * 7548 * @return {Texture} A clone of this instance. 7549 */ 7550 clone() { 7551 return new this.constructor().copy(this); 7552 } 7553 /** 7554 * Copies the values of the given texture to this instance. 7555 * 7556 * @param {Texture} source - The texture to copy. 7557 * @return {Texture} A reference to this instance. 7558 */ 7559 copy(e) { 7560 return this.name = e.name, this.source = e.source, this.mipmaps = e.mipmaps.slice(0), this.mapping = e.mapping, this.channel = e.channel, this.wrapS = e.wrapS, this.wrapT = e.wrapT, this.magFilter = e.magFilter, this.minFilter = e.minFilter, this.anisotropy = e.anisotropy, this.format = e.format, this.internalFormat = e.internalFormat, this.type = e.type, this.normalized = e.normalized, this.offset.copy(e.offset), this.repeat.copy(e.repeat), this.center.copy(e.center), this.rotation = e.rotation, this.matrixAutoUpdate = e.matrixAutoUpdate, this.matrix.copy(e.matrix), this.generateMipmaps = e.generateMipmaps, this.premultiplyAlpha = e.premultiplyAlpha, this.flipY = e.flipY, this.unpackAlignment = e.unpackAlignment, this.colorSpace = e.colorSpace, this.renderTarget = e.renderTarget, this.isRenderTargetTexture = e.isRenderTargetTexture, this.isArrayTexture = e.isArrayTexture, this.userData = JSON.parse(JSON.stringify(e.userData)), this.needsUpdate = !0, this; 7561 } 7562 /** 7563 * Sets this texture's properties based on `values`. 7564 * @param {Object} values - A container with texture parameters. 7565 */ 7566 setValues(e) { 7567 for (const t in e) { 7568 const i = e[t]; 7569 if (i === void 0) { 7570 tt(`Texture.setValues(): parameter '${t}' has value of undefined.`); 7571 continue; 7572 } 7573 const r = this[t]; 7574 if (r === void 0) { 7575 tt(`Texture.setValues(): property '${t}' does not exist.`); 7576 continue; 7577 } 7578 r && i && r.isVector2 && i.isVector2 || r && i && r.isVector3 && i.isVector3 || r && i && r.isMatrix3 && i.isMatrix3 ? r.copy(i) : this[t] = i; 7579 } 7580 } 7581 /** 7582 * Serializes the texture into JSON. 7583 * 7584 * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. 7585 * @return {Object} A JSON object representing the serialized texture. 7586 * @see {@link ObjectLoader#parse} 7587 */ 7588 toJSON(e) { 7589 const t = e === void 0 || typeof e == "string"; 7590 if (!t && e.textures[this.uuid] !== void 0) 7591 return e.textures[this.uuid]; 7592 const i = { 7593 metadata: { 7594 version: 4.7, 7595 type: "Texture", 7596 generator: "Texture.toJSON" 7597 }, 7598 uuid: this.uuid, 7599 name: this.name, 7600 image: this.source.toJSON(e).uuid, 7601 mapping: this.mapping, 7602 channel: this.channel, 7603 repeat: [this.repeat.x, this.repeat.y], 7604 offset: [this.offset.x, this.offset.y], 7605 center: [this.center.x, this.center.y], 7606 rotation: this.rotation, 7607 wrap: [this.wrapS, this.wrapT], 7608 format: this.format, 7609 internalFormat: this.internalFormat, 7610 type: this.type, 7611 normalized: this.normalized, 7612 colorSpace: this.colorSpace, 7613 minFilter: this.minFilter, 7614 magFilter: this.magFilter, 7615 anisotropy: this.anisotropy, 7616 flipY: this.flipY, 7617 generateMipmaps: this.generateMipmaps, 7618 premultiplyAlpha: this.premultiplyAlpha, 7619 unpackAlignment: this.unpackAlignment 7620 }; 7621 return Object.keys(this.userData).length > 0 && (i.userData = this.userData), t || (e.textures[this.uuid] = i), i; 7622 } 7623 /** 7624 * Frees the GPU-related resources allocated by this instance. Call this 7625 * method whenever this instance is no longer used in your app. 7626 * 7627 * @fires Texture#dispose 7628 */ 7629 dispose() { 7630 this.dispatchEvent({ type: "dispose" }); 7631 } 7632 /** 7633 * Transforms the given uv vector with the textures uv transformation matrix. 7634 * 7635 * @param {Vector2} uv - The uv vector. 7636 * @return {Vector2} The transformed uv vector. 7637 */ 7638 transformUv(e) { 7639 if (this.mapping !== Rp) return e; 7640 if (e.applyMatrix3(this.matrix), e.x < 0 || e.x > 1) 7641 switch (this.wrapS) { 7642 case vc: 7643 e.x = e.x - Math.floor(e.x); 7644 break; 7645 case Di: 7646 e.x = e.x < 0 ? 0 : 1; 7647 break; 7648 case _c: 7649 Math.abs(Math.floor(e.x) % 2) === 1 ? e.x = Math.ceil(e.x) - e.x : e.x = e.x - Math.floor(e.x); 7650 break; 7651 } 7652 if (e.y < 0 || e.y > 1) 7653 switch (this.wrapT) { 7654 case vc: 7655 e.y = e.y - Math.floor(e.y); 7656 break; 7657 case Di: 7658 e.y = e.y < 0 ? 0 : 1; 7659 break; 7660 case _c: 7661 Math.abs(Math.floor(e.y) % 2) === 1 ? e.y = Math.ceil(e.y) - e.y : e.y = e.y - Math.floor(e.y); 7662 break; 7663 } 7664 return this.flipY && (e.y = 1 - e.y), e; 7665 } 7666 /** 7667 * Setting this property to `true` indicates the engine the texture 7668 * must be updated in the next render. This triggers a texture upload 7669 * to the GPU and ensures correct texture parameter configuration. 7670 * 7671 * @type {boolean} 7672 * @default false 7673 * @param {boolean} value 7674 */ 7675 set needsUpdate(e) { 7676 e === !0 && (this.version++, this.source.needsUpdate = !0); 7677 } 7678 /** 7679 * Setting this property to `true` indicates the engine the PMREM 7680 * must be regenerated. 7681 * 7682 * @type {boolean} 7683 * @default false 7684 * @param {boolean} value 7685 */ 7686 set needsPMREMUpdate(e) { 7687 e === !0 && this.pmremVersion++; 7688 } 7689} 7690gn.DEFAULT_IMAGE = null; 7691gn.DEFAULT_MAPPING = Rp; 7692gn.DEFAULT_ANISOTROPY = 1; 7693const oh = class oh { 7694 /** 7695 * Constructs a new 4D vector. 7696 * 7697 * @param {number} [x=0] - The x value of this vector. 7698 * @param {number} [y=0] - The y value of this vector. 7699 * @param {number} [z=0] - The z value of this vector. 7700 * @param {number} [w=1] - The w value of this vector. 7701 */ 7702 constructor(e = 0, t = 0, i = 0, r = 1) { 7703 this.x = e, this.y = t, this.z = i, this.w = r; 7704 } 7705 /** 7706 * Alias for {@link Vector4#z}. 7707 * 7708 * @type {number} 7709 */ 7710 get width() { 7711 return this.z; 7712 } 7713 set width(e) { 7714 this.z = e; 7715 } 7716 /** 7717 * Alias for {@link Vector4#w}. 7718 * 7719 * @type {number} 7720 */ 7721 get height() { 7722 return this.w; 7723 } 7724 set height(e) { 7725 this.w = e; 7726 } 7727 /** 7728 * Sets the vector components. 7729 * 7730 * @param {number} x - The value of the x component. 7731 * @param {number} y - The value of the y component. 7732 * @param {number} z - The value of the z component. 7733 * @param {number} w - The value of the w component. 7734 * @return {Vector4} A reference to this vector. 7735 */ 7736 set(e, t, i, r) { 7737 return this.x = e, this.y = t, this.z = i, this.w = r, this; 7738 } 7739 /** 7740 * Sets the vector components to the same value. 7741 * 7742 * @param {number} scalar - The value to set for all vector components. 7743 * @return {Vector4} A reference to this vector. 7744 */ 7745 setScalar(e) { 7746 return this.x = e, this.y = e, this.z = e, this.w = e, this; 7747 } 7748 /** 7749 * Sets the vector's x component to the given value 7750 * 7751 * @param {number} x - The value to set. 7752 * @return {Vector4} A reference to this vector. 7753 */ 7754 setX(e) { 7755 return this.x = e, this; 7756 } 7757 /** 7758 * Sets the vector's y component to the given value 7759 * 7760 * @param {number} y - The value to set. 7761 * @return {Vector4} A reference to this vector. 7762 */ 7763 setY(e) { 7764 return this.y = e, this; 7765 } 7766 /** 7767 * Sets the vector's z component to the given value 7768 * 7769 * @param {number} z - The value to set. 7770 * @return {Vector4} A reference to this vector. 7771 */ 7772 setZ(e) { 7773 return this.z = e, this; 7774 } 7775 /** 7776 * Sets the vector's w component to the given value 7777 * 7778 * @param {number} w - The value to set. 7779 * @return {Vector4} A reference to this vector. 7780 */ 7781 setW(e) { 7782 return this.w = e, this; 7783 } 7784 /** 7785 * Allows to set a vector component with an index. 7786 * 7787 * @param {number} index - The component index. `0` equals to x, `1` equals to y, 7788 * `2` equals to z, `3` equals to w. 7789 * @param {number} value - The value to set. 7790 * @return {Vector4} A reference to this vector. 7791 */ 7792 setComponent(e, t) { 7793 switch (e) { 7794 case 0: 7795 this.x = t; 7796 break; 7797 case 1: 7798 this.y = t; 7799 break; 7800 case 2: 7801 this.z = t; 7802 break; 7803 case 3: 7804 this.w = t; 7805 break; 7806 default: 7807 throw new Error("index is out of range: " + e); 7808 } 7809 return this; 7810 } 7811 /** 7812 * Returns the value of the vector component which matches the given index. 7813 * 7814 * @param {number} index - The component index. `0` equals to x, `1` equals to y, 7815 * `2` equals to z, `3` equals to w. 7816 * @return {number} A vector component value. 7817 */ 7818 getComponent(e) { 7819 switch (e) { 7820 case 0: 7821 return this.x; 7822 case 1: 7823 return this.y; 7824 case 2: 7825 return this.z; 7826 case 3: 7827 return this.w; 7828 default: 7829 throw new Error("index is out of range: " + e); 7830 } 7831 } 7832 /** 7833 * Returns a new vector with copied values from this instance. 7834 * 7835 * @return {Vector4} A clone of this instance. 7836 */ 7837 clone() { 7838 return new this.constructor(this.x, this.y, this.z, this.w); 7839 } 7840 /** 7841 * Copies the values of the given vector to this instance. 7842 * 7843 * @param {Vector3|Vector4} v - The vector to copy. 7844 * @return {Vector4} A reference to this vector. 7845 */ 7846 copy(e) { 7847 return this.x = e.x, this.y = e.y, this.z = e.z, this.w = e.w !== void 0 ? e.w : 1, this; 7848 } 7849 /** 7850 * Adds the given vector to this instance. 7851 * 7852 * @param {Vector4} v - The vector to add. 7853 * @return {Vector4} A reference to this vector. 7854 */ 7855 add(e) { 7856 return this.x += e.x, this.y += e.y, this.z += e.z, this.w += e.w, this; 7857 } 7858 /** 7859 * Adds the given scalar value to all components of this instance. 7860 * 7861 * @param {number} s - The scalar to add. 7862 * @return {Vector4} A reference to this vector. 7863 */ 7864 addScalar(e) { 7865 return this.x += e, this.y += e, this.z += e, this.w += e, this; 7866 } 7867 /** 7868 * Adds the given vectors and stores the result in this instance. 7869 * 7870 * @param {Vector4} a - The first vector. 7871 * @param {Vector4} b - The second vector. 7872 * @return {Vector4} A reference to this vector. 7873 */ 7874 addVectors(e, t) { 7875 return this.x = e.x + t.x, this.y = e.y + t.y, this.z = e.z + t.z, this.w = e.w + t.w, this; 7876 } 7877 /** 7878 * Adds the given vector scaled by the given factor to this instance. 7879 * 7880 * @param {Vector4} v - The vector. 7881 * @param {number} s - The factor that scales `v`. 7882 * @return {Vector4} A reference to this vector. 7883 */ 7884 addScaledVector(e, t) { 7885 return this.x += e.x * t, this.y += e.y * t, this.z += e.z * t, this.w += e.w * t, this; 7886 } 7887 /** 7888 * Subtracts the given vector from this instance. 7889 * 7890 * @param {Vector4} v - The vector to subtract. 7891 * @return {Vector4} A reference to this vector. 7892 */ 7893 sub(e) { 7894 return this.x -= e.x, this.y -= e.y, this.z -= e.z, this.w -= e.w, this; 7895 } 7896 /** 7897 * Subtracts the given scalar value from all components of this instance. 7898 * 7899 * @param {number} s - The scalar to subtract. 7900 * @return {Vector4} A reference to this vector. 7901 */ 7902 subScalar(e) { 7903 return this.x -= e, this.y -= e, this.z -= e, this.w -= e, this; 7904 } 7905 /** 7906 * Subtracts the given vectors and stores the result in this instance. 7907 * 7908 * @param {Vector4} a - The first vector. 7909 * @param {Vector4} b - The second vector. 7910 * @return {Vector4} A reference to this vector. 7911 */ 7912 subVectors(e, t) { 7913 return this.x = e.x - t.x, this.y = e.y - t.y, this.z = e.z - t.z, this.w = e.w - t.w, this; 7914 } 7915 /** 7916 * Multiplies the given vector with this instance. 7917 * 7918 * @param {Vector4} v - The vector to multiply. 7919 * @return {Vector4} A reference to this vector. 7920 */ 7921 multiply(e) { 7922 return this.x *= e.x, this.y *= e.y, this.z *= e.z, this.w *= e.w, this; 7923 } 7924 /** 7925 * Multiplies the given scalar value with all components of this instance. 7926 * 7927 * @param {number} scalar - The scalar to multiply. 7928 * @return {Vector4} A reference to this vector. 7929 */ 7930 multiplyScalar(e) { 7931 return this.x *= e, this.y *= e, this.z *= e, this.w *= e, this; 7932 } 7933 /** 7934 * Multiplies this vector with the given 4x4 matrix. 7935 * 7936 * @param {Matrix4} m - The 4x4 matrix. 7937 * @return {Vector4} A reference to this vector. 7938 */ 7939 applyMatrix4(e) { 7940 const t = this.x, i = this.y, r = this.z, s = this.w, a = e.elements; 7941 return this.x = a[0] * t + a[4] * i + a[8] * r + a[12] * s, this.y = a[1] * t + a[5] * i + a[9] * r + a[13] * s, this.z = a[2] * t + a[6] * i + a[10] * r + a[14] * s, this.w = a[3] * t + a[7] * i + a[11] * r + a[15] * s, this; 7942 } 7943 /** 7944 * Divides this instance by the given vector. 7945 * 7946 * @param {Vector4} v - The vector to divide. 7947 * @return {Vector4} A reference to this vector. 7948 */ 7949 divide(e) { 7950 return this.x /= e.x, this.y /= e.y, this.z /= e.z, this.w /= e.w, this; 7951 } 7952 /** 7953 * Divides this vector by the given scalar. 7954 * 7955 * @param {number} scalar - The scalar to divide. 7956 * @return {Vector4} A reference to this vector. 7957 */ 7958 divideScalar(e) { 7959 return this.multiplyScalar(1 / e); 7960 } 7961 /** 7962 * Sets the x, y and z components of this 7963 * vector to the quaternion's axis and w to the angle. 7964 * 7965 * @param {Quaternion} q - The Quaternion to set. 7966 * @return {Vector4} A reference to this vector. 7967 */ 7968 setAxisAngleFromQuaternion(e) { 7969 this.w = 2 * Math.acos(e.w); 7970 const t = Math.sqrt(1 - e.w * e.w); 7971 return t < 1e-4 ? (this.x = 1, this.y = 0, this.z = 0) : (this.x = e.x / t, this.y = e.y / t, this.z = e.z / t), this; 7972 } 7973 /** 7974 * Sets the x, y and z components of this 7975 * vector to the axis of rotation and w to the angle. 7976 * 7977 * @param {Matrix4} m - A 4x4 matrix of which the upper left 3x3 matrix is a pure rotation matrix. 7978 * @return {Vector4} A reference to this vector. 7979 */ 7980 setAxisAngleFromRotationMatrix(e) { 7981 let t, i, r, s; 7982 const o = e.elements, c = o[0], u = o[4], h = o[8], d = o[1], f = o[5], p = o[9], v = o[2], m = o[6], g = o[10]; 7983 if (Math.abs(u - d) < 0.01 && Math.abs(h - v) < 0.01 && Math.abs(p - m) < 0.01) { 7984 if (Math.abs(u + d) < 0.1 && Math.abs(h + v) < 0.1 && Math.abs(p + m) < 0.1 && Math.abs(c + f + g - 3) < 0.1) 7985 return this.set(1, 0, 0, 0), this; 7986 t = Math.PI; 7987 const x = (c + 1) / 2, E = (f + 1) / 2, R = (g + 1) / 2, T = (u + d) / 4, w = (h + v) / 4, y = (p + m) / 4; 7988 return x > E && x > R ? x < 0.01 ? (i = 0, r = 0.707106781, s = 0.707106781) : (i = Math.sqrt(x), r = T / i, s = w / i) : E > R ? E < 0.01 ? (i = 0.707106781, r = 0, s = 0.707106781) : (r = Math.sqrt(E), i = T / r, s = y / r) : R < 0.01 ? (i = 0.707106781, r = 0.707106781, s = 0) : (s = Math.sqrt(R), i = w / s, r = y / s), this.set(i, r, s, t), this; 7989 } 7990 let _ = Math.sqrt((m - p) * (m - p) + (h - v) * (h - v) + (d - u) * (d - u)); 7991 return Math.abs(_) < 1e-3 && (_ = 1), this.x = (m - p) / _, this.y = (h - v) / _, this.z = (d - u) / _, this.w = Math.acos((c + f + g - 1) / 2), this; 7992 } 7993 /** 7994 * Sets the vector components to the position elements of the 7995 * given transformation matrix. 7996 * 7997 * @param {Matrix4} m - The 4x4 matrix. 7998 * @return {Vector4} A reference to this vector. 7999 */ 8000 setFromMatrixPosition(e) { 8001 const t = e.elements; 8002 return this.x = t[12], this.y = t[13], this.z = t[14], this.w = t[15], this; 8003 } 8004 /** 8005 * If this vector's x, y, z or w value is greater than the given vector's x, y, z or w 8006 * value, replace that value with the corresponding min value. 8007 * 8008 * @param {Vector4} v - The vector. 8009 * @return {Vector4} A reference to this vector. 8010 */ 8011 min(e) { 8012 return this.x = Math.min(this.x, e.x), this.y = Math.min(this.y, e.y), this.z = Math.min(this.z, e.z), this.w = Math.min(this.w, e.w), this; 8013 } 8014 /** 8015 * If this vector's x, y, z or w value is less than the given vector's x, y, z or w 8016 * value, replace that value with the corresponding max value. 8017 * 8018 * @param {Vector4} v - The vector. 8019 * @return {Vector4} A reference to this vector. 8020 */ 8021 max(e) { 8022 return this.x = Math.max(this.x, e.x), this.y = Math.max(this.y, e.y), this.z = Math.max(this.z, e.z), this.w = Math.max(this.w, e.w), this; 8023 } 8024 /** 8025 * If this vector's x, y, z or w value is greater than the max vector's x, y, z or w 8026 * value, it is replaced by the corresponding value. 8027 * If this vector's x, y, z or w value is less than the min vector's x, y, z or w value, 8028 * it is replaced by the corresponding value. 8029 * 8030 * @param {Vector4} min - The minimum x, y and z values. 8031 * @param {Vector4} max - The maximum x, y and z values in the desired range. 8032 * @return {Vector4} A reference to this vector. 8033 */ 8034 clamp(e, t) { 8035 return this.x = yt(this.x, e.x, t.x), this.y = yt(this.y, e.y, t.y), this.z = yt(this.z, e.z, t.z), this.w = yt(this.w, e.w, t.w), this; 8036 } 8037 /** 8038 * If this vector's x, y, z or w values are greater than the max value, they are 8039 * replaced by the max value. 8040 * If this vector's x, y, z or w values are less than the min value, they are 8041 * replaced by the min value. 8042 * 8043 * @param {number} minVal - The minimum value the components will be clamped to. 8044 * @param {number} maxVal - The maximum value the components will be clamped to. 8045 * @return {Vector4} A reference to this vector. 8046 */ 8047 clampScalar(e, t) { 8048 return this.x = yt(this.x, e, t), this.y = yt(this.y, e, t), this.z = yt(this.z, e, t), this.w = yt(this.w, e, t), this; 8049 } 8050 /** 8051 * If this vector's length is greater than the max value, it is replaced by 8052 * the max value. 8053 * If this vector's length is less than the min value, it is replaced by the 8054 * min value. 8055 * 8056 * @param {number} min - The minimum value the vector length will be clamped to. 8057 * @param {number} max - The maximum value the vector length will be clamped to. 8058 * @return {Vector4} A reference to this vector. 8059 */ 8060 clampLength(e, t) { 8061 const i = this.length(); 8062 return this.divideScalar(i || 1).multiplyScalar(yt(i, e, t)); 8063 } 8064 /** 8065 * The components of this vector are rounded down to the nearest integer value. 8066 * 8067 * @return {Vector4} A reference to this vector. 8068 */ 8069 floor() { 8070 return this.x = Math.floor(this.x), this.y = Math.floor(this.y), this.z = Math.floor(this.z), this.w = Math.floor(this.w), this; 8071 } 8072 /** 8073 * The components of this vector are rounded up to the nearest integer value. 8074 * 8075 * @return {Vector4} A reference to this vector. 8076 */ 8077 ceil() { 8078 return this.x = Math.ceil(this.x), this.y = Math.ceil(this.y), this.z = Math.ceil(this.z), this.w = Math.ceil(this.w), this; 8079 } 8080 /** 8081 * The components of this vector are rounded to the nearest integer value 8082 * 8083 * @return {Vector4} A reference to this vector. 8084 */ 8085 round() { 8086 return this.x = Math.round(this.x), this.y = Math.round(this.y), this.z = Math.round(this.z), this.w = Math.round(this.w), this; 8087 } 8088 /** 8089 * The components of this vector are rounded towards zero (up if negative, 8090 * down if positive) to an integer value. 8091 * 8092 * @return {Vector4} A reference to this vector. 8093 */ 8094 roundToZero() { 8095 return this.x = Math.trunc(this.x), this.y = Math.trunc(this.y), this.z = Math.trunc(this.z), this.w = Math.trunc(this.w), this; 8096 } 8097 /** 8098 * Inverts this vector - i.e. sets x = -x, y = -y, z = -z, w = -w. 8099 * 8100 * @return {Vector4} A reference to this vector. 8101 */ 8102 negate() { 8103 return this.x = -this.x, this.y = -this.y, this.z = -this.z, this.w = -this.w, this; 8104 } 8105 /** 8106 * Calculates the dot product of the given vector with this instance. 8107 * 8108 * @param {Vector4} v - The vector to compute the dot product with. 8109 * @return {number} The result of the dot product. 8110 */ 8111 dot(e) { 8112 return this.x * e.x + this.y * e.y + this.z * e.z + this.w * e.w; 8113 } 8114 /** 8115 * Computes the square of the Euclidean length (straight-line length) from 8116 * (0, 0, 0, 0) to (x, y, z, w). If you are comparing the lengths of vectors, you should 8117 * compare the length squared instead as it is slightly more efficient to calculate. 8118 * 8119 * @return {number} The square length of this vector. 8120 */ 8121 lengthSq() { 8122 return this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w; 8123 } 8124 /** 8125 * Computes the Euclidean length (straight-line length) from (0, 0, 0, 0) to (x, y, z, w). 8126 * 8127 * @return {number} The length of this vector. 8128 */ 8129 length() { 8130 return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w); 8131 } 8132 /** 8133 * Computes the Manhattan length of this vector. 8134 * 8135 * @return {number} The length of this vector. 8136 */ 8137 manhattanLength() { 8138 return Math.abs(this.x) + Math.abs(this.y) + Math.abs(this.z) + Math.abs(this.w); 8139 } 8140 /** 8141 * Converts this vector to a unit vector - that is, sets it equal to a vector 8142 * with the same direction as this one, but with a vector length of `1`. 8143 * 8144 * @return {Vector4} A reference to this vector. 8145 */ 8146 normalize() { 8147 return this.divideScalar(this.length() || 1); 8148 } 8149 /** 8150 * Sets this vector to a vector with the same direction as this one, but 8151 * with the specified length. 8152 * 8153 * @param {number} length - The new length of this vector. 8154 * @return {Vector4} A reference to this vector. 8155 */ 8156 setLength(e) { 8157 return this.normalize().multiplyScalar(e); 8158 } 8159 /** 8160 * Linearly interpolates between the given vector and this instance, where 8161 * alpha is the percent distance along the line - alpha = 0 will be this 8162 * vector, and alpha = 1 will be the given one. 8163 * 8164 * @param {Vector4} v - The vector to interpolate towards. 8165 * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. 8166 * @return {Vector4} A reference to this vector. 8167 */ 8168 lerp(e, t) { 8169 return this.x += (e.x - this.x) * t, this.y += (e.y - this.y) * t, this.z += (e.z - this.z) * t, this.w += (e.w - this.w) * t, this; 8170 } 8171 /** 8172 * Linearly interpolates between the given vectors, where alpha is the percent 8173 * distance along the line - alpha = 0 will be first vector, and alpha = 1 will 8174 * be the second one. The result is stored in this instance. 8175 * 8176 * @param {Vector4} v1 - The first vector. 8177 * @param {Vector4} v2 - The second vector. 8178 * @param {number} alpha - The interpolation factor, typically in the closed interval `[0, 1]`. 8179 * @return {Vector4} A reference to this vector. 8180 */ 8181 lerpVectors(e, t, i) { 8182 return this.x = e.x + (t.x - e.x) * i, this.y = e.y + (t.y - e.y) * i, this.z = e.z + (t.z - e.z) * i, this.w = e.w + (t.w - e.w) * i, this; 8183 } 8184 /** 8185 * Returns `true` if this vector is equal with the given one. 8186 * 8187 * @param {Vector4} v - The vector to test for equality. 8188 * @return {boolean} Whether this vector is equal with the given one. 8189 */ 8190 equals(e) { 8191 return e.x === this.x && e.y === this.y && e.z === this.z && e.w === this.w; 8192 } 8193 /** 8194 * Sets this vector's x value to be `array[ offset ]`, y value to be `array[ offset + 1 ]`, 8195 * z value to be `array[ offset + 2 ]`, w value to be `array[ offset + 3 ]`. 8196 * 8197 * @param {Array<number>} array - An array holding the vector component values. 8198 * @param {number} [offset=0] - The offset into the array. 8199 * @return {Vector4} A reference to this vector. 8200 */ 8201 fromArray(e, t = 0) { 8202 return this.x = e[t], this.y = e[t + 1], this.z = e[t + 2], this.w = e[t + 3], this; 8203 } 8204 /** 8205 * Writes the components of this vector to the given array. If no array is provided, 8206 * the method returns a new instance. 8207 * 8208 * @param {Array<number>} [array=[]] - The target array holding the vector components. 8209 * @param {number} [offset=0] - Index of the first element in the array. 8210 * @return {Array<number>} The vector components. 8211 */ 8212 toArray(e = [], t = 0) { 8213 return e[t] = this.x, e[t + 1] = this.y, e[t + 2] = this.z, e[t + 3] = this.w, e; 8214 } 8215 /** 8216 * Sets the components of this vector from the given buffer attribute. 8217 * 8218 * @param {BufferAttribute} attribute - The buffer attribute holding vector data. 8219 * @param {number} index - The index into the attribute. 8220 * @return {Vector4} A reference to this vector. 8221 */ 8222 fromBufferAttribute(e, t) { 8223 return this.x = e.getX(t), this.y = e.getY(t), this.z = e.getZ(t), this.w = e.getW(t), this; 8224 } 8225 /** 8226 * Sets each component of this vector to a pseudo-random value between `0` and 8227 * `1`, excluding `1`. 8228 * 8229 * @return {Vector4} A reference to this vector. 8230 */ 8231 random() { 8232 return this.x = Math.random(), this.y = Math.random(), this.z = Math.random(), this.w = Math.random(), this; 8233 } 8234 *[Symbol.iterator]() { 8235 yield this.x, yield this.y, yield this.z, yield this.w; 8236 } 8237}; 8238oh.prototype.isVector4 = !0; 8239let Gt = oh; 8240class L_ extends Ir {
8241 /** 8242 * Render target options. 8243 * 8244 * @typedef {Object} RenderTarget~Options 8245 * @property {boolean} [generateMipmaps=false] - Whether to generate mipmaps or not. 8246 * @property {number} [magFilter=LinearFilter] - The mag filter. 8247 * @property {number} [minFilter=LinearFilter] - The min filter. 8248 * @property {number} [format=RGBAFormat] - The texture format. 8249 * @property {number} [type=UnsignedByteType] - The texture type. 8250 * @property {?string} [internalFormat=null] - The texture's internal format. 8251 * @property {number} [wrapS=ClampToEdgeWrapping] - The texture's uv wrapping mode. 8252 * @property {number} [wrapT=ClampToEdgeWrapping] - The texture's uv wrapping mode. 8253 * @property {number} [anisotropy=1] - The texture's anisotropy value. 8254 * @property {string} [colorSpace=NoColorSpace] - The texture's color space. 8255 * @property {boolean} [depthBuffer=true] - Whether to allocate a depth buffer or not. 8256 * @property {boolean} [stencilBuffer=false] - Whether to allocate a stencil buffer or not. 8257 * @property {boolean} [resolveDepthBuffer=true] - Whether to resolve the depth buffer or not. 8258 * @property {boolean} [resolveStencilBuffer=true] - Whether to resolve the stencil buffer or not. 8259 * @property {?Texture} [depthTexture=null] - Reference to a depth texture. 8260 * @property {number} [samples=0] - The MSAA samples count. 8261 * @property {number} [count=1] - Defines the number of color attachments . Must be at least `1`. 8262 * @property {number} [depth=1] - The texture depth. 8263 * @property {boolean} [multiview=false] - Whether this target is used for multiview rendering. 8264 */ 8265 /** 8266 * Constructs a new render target. 8267 * 8268 * @param {number} [width=1] - The width of the render target. 8269 * @param {number} [height=1] - The height of the render target. 8270 * @param {RenderTarget~Options} [options] - The configuration object. 8271 */ 8272 constructor(e = 1, t = 1, i = {}) { 8273 super(), i = Object.assign({ 8274 generateMipmaps: !1, 8275 internalFormat: null, 8276 minFilter: fn, 8277 depthBuffer: !0, 8278 stencilBuffer: !1, 8279 resolveDepthBuffer: !0, 8280 resolveStencilBuffer: !0, 8281 depthTexture: null, 8282 samples: 0, 8283 count: 1, 8284 depth: 1, 8285 multiview: !1 8286 }, i), this.isRenderTarget = !0, this.width = e, this.height = t, this.depth = i.depth, this.scissor = new Gt(0, 0, e, t), this.scissorTest = !1, this.viewport = new Gt(0, 0, e, t), this.textures = []; 8287 const r = { width: e, height: t, depth: i.depth }, s = new gn(r), a = i.count; 8288 for (let l = 0; l < a; l++) 8289 this.textures[l] = s.clone(), this.textures[l].isRenderTargetTexture = !0, this.textures[l].renderTarget = this; 8290 this._setTextureOptions(i), this.depthBuffer = i.depthBuffer, this.stencilBuffer = i.stencilBuffer, this.resolveDepthBuffer = i.resolveDepthBuffer, this.resolveStencilBuffer = i.resolveStencilBuffer, this._depthTexture = null, this.depthTexture = i.depthTexture, this.samples = i.samples, this.multiview = i.multiview; 8291 } 8292 _setTextureOptions(e = {}) { 8293 const t = { 8294 minFilter: fn, 8295 generateMipmaps: !1, 8296 flipY: !1, 8297 internalFormat: null 8298 }; 8299 e.mapping !== void 0 && (t.mapping = e.mapping), e.wrapS !== void 0 && (t.wrapS = e.wrapS), e.wrapT !== void 0 && (t.wrapT = e.wrapT), e.wrapR !== void 0 && (t.wrapR = e.wrapR), e.magFilter !== void 0 && (t.magFilter = e.magFilter), e.minFilter !== void 0 && (t.minFilter = e.minFilter), e.format !== void 0 && (t.format = e.format), e.type !== void 0 && (t.type = e.type), e.anisotropy !== void 0 && (t.anisotropy = e.anisotropy), e.colorSpace !== void 0 && (t.colorSpace = e.colorSpace), e.flipY !== void 0 && (t.flipY = e.flipY), e.generateMipmaps !== void 0 && (t.generateMipmaps = e.generateMipmaps), e.internalFormat !== void 0 && (t.internalFormat = e.internalFormat); 8300 for (let i = 0; i < this.textures.length; i++) 8301 this.textures[i].setValues(t); 8302 } 8303 /** 8304 * The texture representing the default color attachment. 8305 * 8306 * @type {Texture} 8307 */ 8308 get texture() { 8309 return this.textures[0]; 8310 } 8311 set texture(e) { 8312 this.textures[0] = e; 8313 } 8314 set depthTexture(e) { 8315 this._depthTexture !== null && (this._depthTexture.renderTarget = null), e !== null && (e.renderTarget = this), this._depthTexture = e; 8316 } 8317 /** 8318 * Instead of saving the depth in a renderbuffer, a texture 8319 * can be used instead which is useful for further processing 8320 * e.g. in context of post-processing. 8321 * 8322 * @type {?DepthTexture} 8323 * @default null 8324 */ 8325 get depthTexture() { 8326 return this._depthTexture; 8327 } 8328 /** 8329 * Sets the size of this render target. 8330 * 8331 * @param {number} width - The width. 8332 * @param {number} height - The height. 8333 * @param {number} [depth=1] - The depth. 8334 */ 8335 setSize(e, t, i = 1) { 8336 if (this.width !== e || this.height !== t || this.depth !== i) { 8337 this.width = e, this.height = t, this.depth = i; 8338 for (let r = 0, s = this.textures.length; r < s; r++) 8339 this.textures[r].image.width = e, this.textures[r].image.height = t, this.textures[r].image.depth = i, this.textures[r].isData3DTexture !== !0 && (this.textures[r].isArrayTexture = this.textures[r].image.depth > 1); 8340 this.dispose(); 8341 } 8342 this.viewport.set(0, 0, e, t), this.scissor.set(0, 0, e, t); 8343 } 8344 /** 8345 * Returns a new render target with copied values from this instance. 8346 * 8347 * @return {RenderTarget} A clone of this instance. 8348 */ 8349 clone() { 8350 return new this.constructor().copy(this); 8351 } 8352 /** 8353 * Copies the settings of the given render target. This is a structural copy so 8354 * no resources are shared between render targets after the copy. That includes 8355 * all MRT textures and the depth texture. 8356 *
8357 * @param {RenderTarget} source - The render target to copy. 8358 * @return {RenderTarget} A reference to this instance. 8359 */ 8360 copy(e) { 8361 this.width = e.width, this.height = e.height, this.depth = e.depth, this.scissor.copy(e.scissor), this.scissorTest = e.scissorTest, this.viewport.copy(e.viewport), this.textures.length = 0; 8362 for (let t = 0, i = e.textures.length; t < i; t++) { 8363 this.textures[t] = e.textures[t].clone(), this.textures[t].isRenderTargetTexture = !0, this.textures[t].renderTarget = this; 8364 const r = Object.assign({}, e.textures[t].image); 8365 this.textures[t].source = new Gu(r); 8366 } 8367 return this.depthBuffer = e.depthBuffer, this.stencilBuffer = e.stencilBuffer, this.resolveDepthBuffer = e.resolveDepthBuffer, this.resolveStencilBuffer = e.resolveStencilBuffer, e.depthTexture !== null && (this.depthTexture = e.depthTexture.clone()), this.samples = e.samples, this.multiview = e.multiview, this; 8368 } 8369 /** 8370 * Frees the GPU-related resources allocated by this instance. Call this 8371 * method whenever this instance is no longer used in your app. 8372 * 8373 * @fires RenderTarget#dispose 8374 */ 8375 dispose() { 8376 this.dispatchEvent({ type: "dispose" }); 8377 } 8378} 8379class fi extends L_ { 8380 /** 8381 * Constructs a new 3D render target. 8382 * 8383 * @param {number} [width=1] - The width of the render target. 8384 * @param {number} [height=1] - The height of the render target. 8385 * @param {RenderTarget~Options} [options] - The configuration object. 8386 */ 8387 constructor(e = 1, t = 1, i = {}) { 8388 super(e, t, i), this.isWebGLRenderTarget = !0; 8389 } 8390} 8391class Op extends gn { 8392 /** 8393 * Constructs a new data array texture. 8394 * 8395 * @param {?TypedArray} [data=null] - The buffer data. 8396 * @param {number} [width=1] - The width of the texture. 8397 * @param {number} [height=1] - The height of the texture. 8398 * @param {number} [depth=1] - The depth of the texture. 8399 */ 8400 constructor(e = null, t = 1, i = 1, r = 1) { 8401 super(null), this.isDataArrayTexture = !0, this.image = { data: e, width: t, height: i, depth: r }, this.magFilter = sn, this.minFilter = sn, this.wrapR = Di, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1, this.layerUpdates = /* @__PURE__ */ new Set(); 8402 } 8403 /** 8404 * Describes that a specific layer of the texture needs to be updated. 8405 * Normally when {@link Texture#needsUpdate} is set to `true`, the 8406 * entire data texture array is sent to the GPU. Marking specific 8407 * layers will only transmit subsets of all mipmaps associated with a 8408 * specific depth in the array which is often much more performant. 8409 * 8410 * @param {number} layerIndex - The layer index that should be updated. 8411 */ 8412 addLayerUpdate(e) { 8413 this.layerUpdates.add(e); 8414 } 8415 /** 8416 * Resets the layer updates registry. 8417 */ 8418 clearLayerUpdates() { 8419 this.layerUpdates.clear(); 8420 } 8421} 8422class N_ extends gn { 8423 /** 8424 * Constructs a new data array texture. 8425 * 8426 * @param {?TypedArray} [data=null] - The buffer data. 8427 * @param {number} [width=1] - The width of the texture. 8428 * @param {number} [height=1] - The height of the texture. 8429 * @param {number} [depth=1] - The depth of the texture. 8430 */ 8431 constructor(e = null, t = 1, i = 1, r = 1) { 8432 super(null), this.isData3DTexture = !0, this.image = { data: e, width: t, height: i, depth: r }, this.magFilter = sn, this.minFilter = sn, this.wrapR = Di, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1; 8433 } 8434} 8435const Go = class Go { 8436 /** 8437 * Constructs a new 4x4 matrix. The arguments are supposed to be 8438 * in row-major order. If no arguments are provided, the constructor 8439 * initializes the matrix as an identity matrix. 8440 * 8441 * @param {number} [n11] - 1-1 matrix element. 8442 * @param {number} [n12] - 1-2 matrix element. 8443 * @param {number} [n13] - 1-3 matrix element. 8444 * @param {number} [n14] - 1-4 matrix element. 8445 * @param {number} [n21] - 2-1 matrix element. 8446 * @param {number} [n22] - 2-2 matrix element. 8447 * @param {number} [n23] - 2-3 matrix element. 8448 * @param {number} [n24] - 2-4 matrix element. 8449 * @param {number} [n31] - 3-1 matrix element. 8450 * @param {number} [n32] - 3-2 matrix element. 8451 * @param {number} [n33] - 3-3 matrix element. 8452 * @param {number} [n34] - 3-4 matrix element. 8453 * @param {number} [n41] - 4-1 matrix element. 8454 * @param {number}
8454 [n42] - 4-2 matrix element. 8455 * @param {number} [n43] - 4-3 matrix element. 8456 * @param {number} [n44] - 4-4 matrix element. 8457 */ 8458 constructor(e, t, i, r, s, a, l, o, c, u, h, d, f, p, v, m) { 8459 this.elements = [ 8460 1, 8461 0, 8462 0, 8463 0, 8464 0, 8465 1, 8466 0, 8467 0, 8468 0, 8469 0, 8470 1, 8471 0, 8472 0, 8473 0, 8474 0, 8475 1 8476 ], e !== void 0 && this.set(e, t, i, r, s, a, l, o, c, u, h, d, f, p, v, m); 8477 } 8478 /** 8479 * Sets the elements of the matrix.The arguments are supposed to be 8480 * in row-major order. 8481 * 8482 * @param {number} [n11] - 1-1 matrix element. 8483 * @param {number} [n12] - 1-2 matrix element. 8484 * @param {number} [n13] - 1-3 matrix element. 8485 * @param {number} [n14] - 1-4 matrix element. 8486 * @param {number} [n21] - 2-1 matrix element. 8487 * @param {number} [n22] - 2-2 matrix element. 8488 * @param {number} [n23] - 2-3 matrix element. 8489 * @param {number} [n24] - 2-4 matrix element. 8490 * @param {number} [n31] - 3-1 matrix element. 8491 * @param {number} [n32] - 3-2 matrix element. 8492 * @param {number} [n33] - 3-3 matrix element. 8493 * @param {number} [n34] - 3-4 matrix element. 8494 * @param {number} [n41] - 4-1 matrix element. 8495 * @param {number} [n42] - 4-2 matrix element. 8496 * @param {number} [n43] - 4-3 matrix element. 8497 * @param {number} [n44] - 4-4 matrix element. 8498 * @return {Matrix4} A reference to this matrix. 8499 */ 8500 set(e, t, i, r, s, a, l, o, c, u, h, d, f, p, v, m) { 8501 const g = this.elements; 8502 return g[0] = e, g[4] = t, g[8] = i, g[12] = r, g[1] = s, g[5] = a, g[9] = l, g[13] = o, g[2] = c, g[6] = u, g[10] = h, g[14] = d, g[3] = f, g[7] = p, g[11] = v, g[15] = m, this; 8503 } 8504 /** 8505 * Sets this matrix to the 4x4 identity matrix. 8506 * 8507 * @return {Matrix4} A reference to this matrix. 8508 */ 8509 identity() { 8510 return this.set( 8511 1, 8512 0, 8513 0, 8514 0, 8515 0, 8516 1, 8517 0, 8518 0, 8519 0, 8520 0, 8521 1, 8522 0, 8523 0, 8524 0, 8525 0, 8526 1 8527 ), this; 8528 } 8529 /** 8530 * Returns a matrix with copied values from this instance. 8531 * 8532 * @return {Matrix4} A clone of this instance. 8533 */ 8534 clone() { 8535 return new Go().fromArray(this.elements); 8536 } 8537 /** 8538 * Copies the values of the given matrix to this instance. 8539 * 8540 * @param {Matrix4} m - The matrix to copy. 8541 * @return {Matrix4} A reference to this matrix. 8542 */ 8543 copy(e) { 8544 const t = this.elements, i = e.elements; 8545 return t[0] = i[0], t[1] = i[1], t[2] = i[2], t[3] = i[3], t[4] = i[4], t[5] = i[5], t[6] = i[6], t[7] = i[7], t[8] = i[8], t[9] = i[9], t[10] = i[10], t[11] = i[11], t[12] = i[12], t[13] = i[13], t[14] = i[14], t[15] = i[15], this; 8546 } 8547 /** 8548 * Copies the translation component of the given matrix 8549 * into this matrix's translation component. 8550 * 8551 * @param {Matrix4} m - The matrix to copy the translation component. 8552 * @return {Matrix4} A reference to this matrix. 8553 */ 8554 copyPosition(e) { 8555 const t = this.elements, i = e.elements; 8556 return t[12] = i[12], t[13] = i[13], t[14] = i[14], this; 8557 } 8558 /** 8559 * Set the upper 3x3 elements of this matrix to the values of given 3x3 matrix. 8560 * 8561 * @param {Matrix3} m - The 3x3 matrix. 8562 * @return {Matrix4} A reference to this matrix. 8563 */ 8564 setFromMatrix3(e) { 8565 const t = e.elements; 8566 return this.set( 8567 t[0], 8568 t[3], 8569 t[6], 8570 0, 8571 t[1], 8572 t[4], 8573 t[7], 8574 0, 8575 t[2], 8576 t[5], 8577 t[8], 8578 0, 8579 0, 8580 0, 8581 0, 8582 1 8583 ), this; 8584 } 8585 /** 8586 * Extracts the basis of this matrix into the three axis vectors provided. 8587 * 8588 * @param {Vector3} xAxis - The basis's x axis. 8589 * @param {Vector3} yAxis - The basis's y axis. 8590 * @param {Vector3} zAxis - The basis's z axis. 8591 * @return {Matrix4} A reference to this matrix. 8592 */ 8593 extractBasis(e, t, i) { 8594 return this.determinant() === 0 ? (e.set(1, 0, 0), t.set(0, 1, 0), i.set(0, 0, 1), this) : (e.setFromMatrixColumn(this, 0), t.setFromMatrixColumn(this, 1), i.setFromMatrixColumn(this, 2), this); 8595 } 8596 /** 8597 * Sets the given basis vectors to this matrix. 8598 * 8599 * @param {Vector3} xAxis - The basis's x axis. 8600 * @param {Vector3} yAxis - The basis's y axis. 8601 * @param {Vector3} zAxis - The basis's z axis. 8602 * @return {Matrix4} A reference to this matrix. 8603 */ 8604 makeBasis(e, t, i) { 8605 return this.set( 8606 e.x, 8607 t.x, 8608 i.x, 8609 0, 8610 e.y, 8611 t.y, 8612 i.y, 8613 0, 8614 e.z, 8615 t.z, 8616 i.z, 8617 0, 8618 0, 8619 0, 8620 0, 8621 1 8622 ), this; 8623 } 8624 /** 8625 * Extracts the rotation component of the given matrix 8626 * into this matrix's rotation component. 8627 * 8628 * Note: This method does not support reflection matrices. 8629 * 8630 * @param {Matrix4} m - The matrix. 8631 * @return {Matrix4} A reference to this matrix. 8632 */ 8633 extractRotation(e) { 8634 if (e.determinant() === 0) 8635 return this.identity(); 8636 const t = this.elements, i = e.elements, r = 1 / Br.setFromMatrixColumn(e, 0).length(), s = 1 / Br.setFromMatrixColumn(e, 1).length(), a = 1 / Br.setFromMatrixColumn(e, 2).length(); 8637 return t[0] = i[0] * r, t[1] = i[1] * r, t[2] = i[2] * r, t[3] = 0, t[4] = i[4] * s, t[5] = i[5] * s, t[6] = i[6] * s, t[7] = 0, t[8] = i[8] * a, t[9] = i[9] * a, t[10] = i[10] * a, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, this; 8638 } 8639 /**
8640 * Sets the rotation component (the upper left 3x3 matrix) of this matrix to 8641 * the rotation specified by the given Euler angles. The rest of 8642 * the matrix is set to the identity. Depending on the {@link Euler#order}, 8643 * there are six possible outcomes. See [this page](https://en.wikipedia.org/wiki/Euler_angles#Rotation_matrix) 8644 * for a complete list. 8645 * 8646 * @param {Euler} euler - The Euler angles. 8647 * @return {Matrix4} A reference to this matrix. 8648 */ 8649 makeRotationFromEuler(e) { 8650 const t = this.elements, i = e.x, r = e.y, s = e.z, a = Math.cos(i), l = Math.sin(i), o = Math.cos(r), c = Math.sin(r), u = Math.cos(s), h = Math.sin(s); 8651 if (e.order === "XYZ") { 8652 const d = a * u, f = a * h, p = l * u, v = l * h; 8653 t[0] = o * u, t[4] = -o * h, t[8] = c, t[1] = f + p * c, t[5] = d - v * c, t[9] = -l * o, t[2] = v - d * c, t[6] = p + f * c, t[10] = a * o; 8654 } else if (e.order === "YXZ") { 8655 const d = o * u, f = o * h, p = c * u, v = c * h; 8656 t[0] = d + v * l, t[4] = p * l - f, t[8] = a * c, t[1] = a * h, t[5] = a * u, t[9] = -l, t[2] = f * l - p, t[6] = v + d * l, t[10] = a * o; 8657 } else if (e.order === "ZXY") { 8658 const d = o * u, f = o * h, p = c * u, v = c * h; 8659 t[0] = d - v * l, t[4] = -a * h, t[8] = p + f * l, t[1] = f + p * l, t[5] = a * u, t[9] = v - d * l, t[2] = -a * c, t[6] = l, t[10] = a * o; 8660 } else if (e.order === "ZYX") { 8661 const d = a * u, f = a * h, p = l * u, v = l * h; 8662 t[0] = o * u, t[4] = p * c - f, t[8] = d * c + v, t[1] = o * h, t[5] = v * c + d, t[9] = f * c - p, t[2] = -c, t[6] = l * o, t[10] = a * o; 8663 } else if (e.order === "YZX") { 8664 const d = a * o, f = a * c, p = l * o, v = l * c; 8665 t[0] = o * u, t[4] = v - d * h, t[8] = p * h + f, t[1] = h, t[5] = a * u, t[9] = -l * u, t[2] = -c * u, t[6] = f * h + p, t[10] = d - v * h; 8666 } else if (e.order === "XZY") { 8667 const d = a * o, f = a * c, p = l * o, v = l * c; 8668 t[0] = o * u, t[4] = -h, t[8] = c * u, t[1] = d * h + v, t[5] = a * u, t[9] = f * h - p, t[2] = p * h - f, t[6] = l * u, t[10] = v * h + d; 8669 } 8670 return t[3] = 0, t[7] = 0, t[11] = 0, t[12] = 0, t[13] = 0, t[14] = 0, t[15] = 1, this; 8671 } 8672 /** 8673 * Sets the rotation component of this matrix to the rotation specified by 8674 * the given Quaternion as outlined [here](https://en.wikipedia.org/wiki/Rotation_matrix#Quaternion) 8675 * The rest of the matrix is set to the identity. 8676 * 8677 * @param {Quaternion} q - The Quaternion. 8678 * @return {Matrix4} A reference to this matrix. 8679 */ 8680 makeRotationFromQuaternion(e) { 8681 return this.compose(I_, e, D_); 8682 } 8683 /** 8684 * Sets the rotation component of the transformation matrix, looking from `eye` towards 8685 * `target`, and oriented by the up-direction. 8686 * 8687 * @param {Vector3} eye - The eye vector. 8688 * @param {Vector3} target - The target vector. 8689 * @param {Vector3} up - The up vector. 8690 * @return {Matrix4} A reference to this matrix. 8691 */ 8692 lookAt(e, t, i) { 8693 const r = this.elements; 8694 return An.subVectors(e, t), An.lengthSq() === 0 && (An.z = 1), An.normalize(), Gi.crossVectors(i, An), Gi.lengthSq() === 0 && (Math.abs(i.z) === 1 ? An.x += 1e-4 : An.z += 1e-4, An.normalize(), Gi.crossVectors(i, An)), Gi.normalize(), Ia.crossVectors(An, Gi), r[0] = Gi.x, r[4] = Ia.x, r[8] = An.x, r[1] = Gi.y, r[5] = Ia.y, r[9] = An.y, r[2] = Gi.z, r[6] = Ia.z, r[10] = An.z, this; 8695 } 8696 /** 8697 * Post-multiplies this matrix by the given 4x4 matrix. 8698 * 8699 * @param {Matrix4} m - The matrix to multiply with. 8700 * @return {Matrix4} A reference to this matrix. 8701 */ 8702 multiply(e) { 8703 return this.multiplyMatrices(this, e); 8704 } 8705 /** 8706 * Pre-multiplies this matrix by the given 4x4 matrix. 8707 * 8708 * @param {Matrix4} m - The matrix to multiply with. 8709 * @return {Matrix4} A reference to this matrix. 8710 */ 8711 premultiply(e) { 8712 return this.multiplyMatrices(e, this); 8713 } 8714 /** 8715 * Multiples the given 4x4 matrices and stores the result 8716 * in this matrix. 8717 * 8718 * @param {Matrix4} a - The first matrix. 8719 * @param {Matrix4} b - The second matrix. 8720 * @return {Matrix4} A reference to this matrix. 8721 */ 8722 multiplyMatrices(e, t) { 8723 const i = e.elements, r = t.elements, s = this.elements, a = i[0], l = i[4], o = i[8], c = i[12], u = i[1], h = i[5], d = i[9], f = i[13], p = i[2], v = i[6], m = i[10], g = i[14], _ = i[3], x = i[7], E = i[11], R = i[15], T = r[0], w = r[4], y = r[8], M = r[12], L = r[1], C = r[5], U = r[9], V = r[13], F = r[2], I = r[6], k = r[10], H = r[14], X = r[3], K = r[7], ae = r[11], se = r[15]; 8724 return s[0] = a * T + l * L + o * F + c * X, s[4] = a * w + l * C + o * I + c * K, s[8] = a * y + l * U + o * k + c * ae, s[12] = a * M + l * V + o * H + c * se, s[1] = u * T + h * L + d * F + f * X, s[5] = u * w + h * C + d * I + f * K, s[9] = u * y + h * U + d * k + f * ae, s[13] = u * M + h * V + d * H + f * se, s[2] = p * T + v * L + m * F + g * X, s[6] = p * w + v * C + m * I + g * K, s[10] = p * y + v * U + m * k + g * ae, s[14] = p * M + v * V + m * H + g * se, s[3] = _ * T + x * L + E * F + R * X, s[7] = _ * w + x * C + E * I + R * K, s[11] = _ * y + x * U + E * k + R * ae, s[15] = _ * M + x * V + E * H + R * se, this; 8725 } 8726 /** 8727 * Multiplies every component of the matrix by the given scalar. 8728 * 8729 * @param {number} s - The scalar. 8730 * @return {Matrix4} A reference to this matrix. 8731 */ 8732 multiplyScalar(e) { 8733 const t = this.elements; 8734 return t[0] *= e, t[4] *= e, t[8] *= e, t[12] *= e, t[1] *= e, t[5] *= e, t[9] *= e, t[13] *= e, t[2] *= e, t[6] *= e, t[10] *= e, t[14] *= e, t[3] *= e, t[7] *= e, t[11] *= e, t[15] *= e, this; 8735 } 8736 /** 8737 * Computes and returns the determinant of this matrix. 8738 * 8739 * Based on the method outlined [here](http://www.euclideanspace.com/maths/algebra/matrix/functions/inverse/fourD/index.html). 8740 * 8741 * @return {number} The determinant. 8742 */ 8743 determinant() { 8744 const e = this.elements, t = e[0], i = e[4], r = e[8], s = e[12], a = e[1], l = e[5], o = e[9], c = e[13], u = e[2], h = e[6], d = e[10], f = e[14], p = e[3], v = e[7], m = e[11], g = e[15], _ = o * f - c * d, x = l * f - c * h, E = l * d - o * h, R = a * f - c * u, T = a * d - o * u, w = a * h - l * u; 8745 return t * (v * _ - m * x + g * E) - i * (p * _ - m * R + g * T) + r * (p * x - v * R + g *
vendor: 4,249 bytes, lines 8745-8854
8745w) - s * (p * E - v * T + m * w); 8746 } 8747 /** 8748 * Transposes this matrix in place. 8749 * 8750 * @return {Matrix4} A reference to this matrix. 8751 */ 8752 transpose() { 8753 const e = this.elements; 8754 let t; 8755 return t = e[1], e[1] = e[4], e[4] = t, t = e[2], e[2] = e[8], e[8] = t, t = e[6], e[6] = e[9], e[9] = t, t = e[3], e[3] = e[12], e[12] = t, t = e[7], e[7] = e[13], e[13] = t, t = e[11], e[11] = e[14], e[14] = t, this; 8756 } 8757 /** 8758 * Sets the position component for this matrix from the given vector, 8759 * without affecting the rest of the matrix. 8760 * 8761 * @param {number|Vector3} x - The x component of the vector or alternatively the vector object. 8762 * @param {number} y - The y component of the vector. 8763 * @param {number} z - The z component of the vector. 8764 * @return {Matrix4} A reference to this matrix. 8765 */ 8766 setPosition(e, t, i) { 8767 const r = this.elements; 8768 return e.isVector3 ? (r[12] = e.x, r[13] = e.y, r[14] = e.z) : (r[12] = e, r[13] = t, r[14] = i), this; 8769 } 8770 /** 8771 * Inverts this matrix, using the [analytic method](https://en.wikipedia.org/wiki/Invertible_matrix#Analytic_solution). 8772 * You can not invert with a determinant of zero. If you attempt this, the method produces 8773 * a zero matrix instead. 8774 * 8775 * @return {Matrix4} A reference to this matrix. 8776 */ 8777 invert() { 8778 const e = this.elements, t = e[0], i = e[1], r = e[2], s = e[3], a = e[4], l = e[5], o = e[6], c = e[7], u = e[8], h = e[9], d = e[10], f = e[11], p = e[12], v = e[13], m = e[14], g = e[15], _ = t * l - i * a, x = t * o - r * a, E = t * c - s * a, R = i * o - r * l, T = i * c - s * l, w = r * c - s * o, y = u * v - h * p, M = u * m - d * p, L = u * g - f * p, C = h * m - d * v, U = h * g - f * v, V = d * g - f * m, F = _ * V - x * U + E * C + R * L - T * M + w * y; 8779 if (F === 0) return this.set(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); 8780 const I = 1 / F; 8781 return e[0] = (l * V - o * U + c * C) * I, e[1] = (r * U - i * V - s * C) * I, e[2] = (v * w - m * T + g * R) * I, e[3] = (d * T - h * w - f * R) * I, e[4] = (o * L - a * V - c * M) * I, e[5] = (t * V - r * L + s * M) * I, e[6] = (m * E - p * w - g * x) * I, e[7] = (u * w - d * E + f * x) * I, e[8] = (a * U - l * L + c * y) * I, e[9] = (i * L - t * U - s * y) * I, e[10] = (p * T - v * E + g * _) * I, e[11] = (h * E - u * T - f * _) * I, e[12] = (l * M - a * C - o * y) * I, e[13] = (t * C - i * M + r * y) * I, e[14] = (v * x - p * R - m * _) * I, e[15] = (u * R - h * x + d * _) * I, this; 8782 } 8783 /** 8784 * Multiplies the columns of this matrix by the given vector. 8785 * 8786 * @param {Vector3} v - The scale vector. 8787 * @return {Matrix4} A reference to this matrix. 8788 */ 8789 scale(e) { 8790 const t = this.elements, i = e.x, r = e.y, s = e.z; 8791 return t[0] *= i, t[4] *= r, t[8] *= s, t[1] *= i, t[5] *= r, t[9] *= s, t[2] *= i, t[6] *= r, t[10] *= s, t[3] *= i, t[7] *= r, t[11] *= s, this; 8792 } 8793 /** 8794 * Gets the maximum scale value of the three axes. 8795 * 8796 * @return {number} The maximum scale. 8797 */ 8798 getMaxScaleOnAxis() { 8799 const e = this.elements, t = e[0] * e[0] + e[1] * e[1] + e[2] * e[2], i = e[4] * e[4] + e[5] * e[5] + e[6] * e[6], r = e[8] * e[8] + e[9] * e[9] + e[10] * e[10]; 8800 return Math.sqrt(Math.max(t, i, r)); 8801 } 8802 /** 8803 * Sets this matrix as a translation transform from the given vector. 8804 * 8805 * @param {number|Vector3} x - The amount to translate in the X axis or alternatively a translation vector. 8806 * @param {number} y - The amount to translate in the Y axis. 8807 * @param {number} z - The amount to translate in the z axis. 8808 * @return {Matrix4} A reference to this matrix. 8809 */ 8810 makeTranslation(e, t, i) { 8811 return e.isVector3 ? this.set( 8812 1, 8813 0, 8814 0, 8815 e.x, 8816 0, 8817 1, 8818 0, 8819 e.y, 8820 0, 8821 0, 8822 1, 8823 e.z, 8824 0, 8825 0, 8826 0, 8827 1 8828 ) : this.set( 8829 1, 8830 0, 8831 0, 8832 e, 8833 0, 8834 1, 8835 0, 8836 t, 8837 0, 8838 0, 8839 1, 8840 i, 8841 0, 8842 0, 8843 0, 8844 1 8845 ), this; 8846 } 8847 /** 8848 * Sets this matrix as a rotational transformation around the X axis by 8849 * the given angle. 8850 * 8851 * @param {number} theta - The rotation in radians. 8852 * @return {Matrix4} A reference to this matrix. 8853 */ 8854 makeRotationX(e) {
vendor: 7,080 bytes, lines 8855-9088
8855 const t = Math.cos(e), i = Math.sin(e); 8856 return this.set( 8857 1, 8858 0, 8859 0, 8860 0, 8861 0, 8862 t, 8863 -i, 8864 0, 8865 0, 8866 i, 8867 t, 8868 0, 8869 0, 8870 0, 8871 0, 8872 1 8873 ), this; 8874 } 8875 /** 8876 * Sets this matrix as a rotational transformation around the Y axis by 8877 * the given angle. 8878 * 8879 * @param {number} theta - The rotation in radians. 8880 * @return {Matrix4} A reference to this matrix. 8881 */ 8882 makeRotationY(e) { 8883 const t = Math.cos(e), i = Math.sin(e); 8884 return this.set( 8885 t, 8886 0, 8887 i, 8888 0, 8889 0, 8890 1, 8891 0, 8892 0, 8893 -i, 8894 0, 8895 t, 8896 0, 8897 0, 8898 0, 8899 0, 8900 1 8901 ), this; 8902 } 8903 /** 8904 * Sets this matrix as a rotational transformation around the Z axis by 8905 * the given angle. 8906 * 8907 * @param {number} theta - The rotation in radians. 8908 * @return {Matrix4} A reference to this matrix. 8909 */ 8910 makeRotationZ(e) { 8911 const t = Math.cos(e), i = Math.sin(e); 8912 return this.set( 8913 t, 8914 -i, 8915 0, 8916 0, 8917 i, 8918 t, 8919 0, 8920 0, 8921 0, 8922 0, 8923 1, 8924 0, 8925 0, 8926 0, 8927 0, 8928 1 8929 ), this; 8930 } 8931 /** 8932 * Sets this matrix as a rotational transformation around the given axis by 8933 * the given angle. 8934 * 8935 * This is a somewhat controversial but mathematically sound alternative to 8936 * rotating via Quaternions. See the discussion [here](https://www.gamedev.net/articles/programming/math-and-physics/do-we-really-need-quaternions-r1199). 8937 * 8938 * @param {Vector3} axis - The normalized rotation axis. 8939 * @param {number} angle - The rotation in radians. 8940 * @return {Matrix4} A reference to this matrix. 8941 */ 8942 makeRotationAxis(e, t) { 8943 const i = Math.cos(t), r = Math.sin(t), s = 1 - i, a = e.x, l = e.y, o = e.z, c = s * a, u = s * l; 8944 return this.set( 8945 c * a + i, 8946 c * l - r * o, 8947 c * o + r * l, 8948 0, 8949 c * l + r * o, 8950 u * l + i, 8951 u * o - r * a, 8952 0, 8953 c * o - r * l, 8954 u * o + r * a, 8955 s * o * o + i, 8956 0, 8957 0, 8958 0, 8959 0, 8960 1 8961 ), this; 8962 } 8963 /** 8964 * Sets this matrix as a scale transformation. 8965 * 8966 * @param {number} x - The amount to scale in the X axis. 8967 * @param {number} y - The amount to scale in the Y axis. 8968 * @param {number} z - The amount to scale in the Z axis. 8969 * @return {Matrix4} A reference to this matrix. 8970 */ 8971 makeScale(e, t, i) { 8972 return this.set( 8973 e, 8974 0, 8975 0, 8976 0, 8977 0, 8978 t, 8979 0, 8980 0, 8981 0, 8982 0, 8983 i, 8984 0, 8985 0, 8986 0, 8987 0, 8988 1 8989 ), this; 8990 } 8991 /** 8992 * Sets this matrix as a shear transformation. 8993 * 8994 * @param {number} xy - The amount to shear X by Y. 8995 * @param {number} xz - The amount to shear X by Z. 8996 * @param {number} yx - The amount to shear Y by X. 8997 * @param {number} yz - The amount to shear Y by Z. 8998 * @param {number} zx - The amount to shear Z by X. 8999 * @param {number} zy - The amount to shear Z by Y. 9000 * @return {Matrix4} A reference to this matrix. 9001 */ 9002 makeShear(e, t, i, r, s, a) { 9003 return this.set( 9004 1, 9005 i, 9006 s, 9007 0, 9008 e, 9009 1, 9010 a, 9011 0, 9012 t, 9013 r, 9014 1, 9015 0, 9016 0, 9017 0, 9018 0, 9019 1 9020 ), this; 9021 } 9022 /** 9023 * Sets this matrix to the transformation composed of the given position, 9024 * rotation (Quaternion) and scale. 9025 * 9026 * @param {Vector3} position - The position vector. 9027 * @param {Quaternion} quaternion - The rotation as a Quaternion. 9028 * @param {Vector3} scale - The scale vector. 9029 * @return {Matrix4} A reference to this matrix. 9030 */ 9031 compose(e, t, i) { 9032 const r = this.elements, s = t._x, a = t._y, l = t._z, o = t._w, c = s + s, u = a + a, h = l + l, d = s * c, f = s * u, p = s * h, v = a * u, m = a * h, g = l * h, _ = o * c, x = o * u, E = o * h, R = i.x, T = i.y, w = i.z; 9033 return r[0] = (1 - (v + g)) * R, r[1] = (f + E) * R, r[2] = (p - x) * R, r[3] = 0, r[4] = (f - E) * T, r[5] = (1 - (d + g)) * T, r[6] = (m + _) * T, r[7] = 0, r[8] = (p + x) * w, r[9] = (m - _) * w, r[10] = (1 - (d + v)) * w, r[11] = 0, r[12] = e.x, r[13] = e.y, r[14] = e.z, r[15] = 1, this; 9034 } 9035 /** 9036 * Decomposes this matrix into its position, rotation and scale components 9037 * and provides the result in the given objects. 9038 * 9039 * Note: Not all matrices are decomposable in this way. For example, if an 9040 * object has a non-uniformly scaled parent, then the object's world matrix 9041 * may not be decomposable, and this method may not be appropriate. 9042 * 9043 * @param {Vector3} position - The position vector. 9044 * @param {Quaternion} quaternion - The rotation as a Quaternion. 9045 * @param {Vector3} scale - The scale vector. 9046 * @return {Matrix4} A reference to this matrix. 9047 */ 9048 decompose(e, t, i) { 9049 const r = this.elements; 9050 e.x = r[12], e.y = r[13], e.z = r[14]; 9051 const s = this.determinant(); 9052 if (s === 0) 9053 return i.set(1, 1, 1), t.identity(), this; 9054 let a = Br.set(r[0], r[1], r[2]).length(); 9055 const l = Br.set(r[4], r[5], r[6]).length(), o = Br.set(r[8], r[9], r[10]).length(); 9056 s < 0 && (a = -a), Xn.copy(this); 9057 const c = 1 / a, u = 1 / l, h = 1 / o; 9058 return Xn.elements[0] *= c, Xn.elements[1] *= c, Xn.elements[2] *= c, Xn.elements[4] *= u, Xn.elements[5] *= u, Xn.elements[6] *= u, Xn.elements[8] *= h, Xn.elements[9] *= h, Xn.elements[10] *= h, t.setFromRotationMatrix(Xn), i.x = a, i.y = l, i.z = o, this; 9059 } 9060 /** 9061 * Creates a perspective projection matrix. This is used internally by 9062 * {@link PerspectiveCamera#updateProjectionMatrix}. 9063 9064 * @param {number} left - Left boundary of the viewing frustum at the near plane. 9065 * @param {number} right - Right boundary of the viewing frustum at the near plane. 9066 * @param {number} top - Top boundary of the viewing frustum at the near plane. 9067 * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane. 9068 * @param {number} near - The distance from the camera to the near plane. 9069 * @param {number} far - The distance from the camera to the far plane. 9070 * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system. 9071 * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth. 9072 * @return {Matrix4} A reference to this matrix. 9073 */ 9074 makePerspective(e, t, i, r, s, a, l = ui, o = !1) { 9075 const c = this.elements, u = 2 * s / (t - e), h = 2 * s / (i - r), d = (t + e) / (t - e), f = (i + r) / (i - r); 9076 let p, v; 9077 if (o) 9078 p = s / (a - s), v = a * s / (a - s); 9079 else if (l === ui) 9080 p = -(a + s) / (a - s), v = -2 * a * s / (a - s); 9081 else if (l === la) 9082 p = -a / (a - s), v = -a * s / (a - s); 9083 else 9084 throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: " + l); 9085 return c[0] = u, c[4] = 0, c[8] = d, c[12] = 0, c[1] = 0, c[5] = h, c[9] = f, c[13] = 0, c[2] = 0, c[6] = 0, c[10] = p, c[14] = v, c[3] = 0, c[7] = 0, c[11] = -1, c[15] = 0, this; 9086 } 9087 /** 9088 * Creates a orthographic projection matrix. This is used internally by
9089 * {@link OrthographicCamera#updateProjectionMatrix}. 9090 9091 * @param {number} left - Left boundary of the viewing frustum at the near plane. 9092 * @param {number} right - Right boundary of the viewing frustum at the near plane. 9093 * @param {number} top - Top boundary of the viewing frustum at the near plane. 9094 * @param {number} bottom - Bottom boundary of the viewing frustum at the near plane. 9095 * @param {number} near - The distance from the camera to the near plane. 9096 * @param {number} far - The distance from the camera to the far plane. 9097 * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} [coordinateSystem=WebGLCoordinateSystem] - The coordinate system. 9098 * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth. 9099 * @return {Matrix4} A reference to this matrix. 9100 */ 9101 makeOrthographic(e, t, i, r, s, a, l = ui, o = !1) { 9102 const c = this.elements, u = 2 / (t - e), h = 2 / (i - r), d = -(t + e) / (t - e), f = -(i + r) / (i - r); 9103 let p, v; 9104 if (o) 9105 p = 1 / (a - s), v = a / (a - s); 9106 else if (l === ui) 9107 p = -2 / (a - s), v = -(a + s) / (a - s); 9108 else if (l === la) 9109 p = -1 / (a - s), v = -s / (a - s); 9110 else 9111 throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: " + l); 9112 return c[0] = u, c[4] = 0, c[8] = 0, c[12] = d, c[1] = 0, c[5] = h, c[9] = 0, c[13] = f, c[2] = 0, c[6] = 0, c[10] = p, c[14] = v, c[3] = 0, c[7] = 0, c[11] = 0, c[15] = 1, this; 9113 } 9114 /** 9115 * Returns `true` if this matrix is equal with the given one. 9116 * 9117 * @param {Matrix4} matrix - The matrix to test for equality. 9118 * @return {boolean} Whether this matrix is equal with the given one. 9119 */ 9120 equals(e) { 9121 const t = this.elements, i = e.elements; 9122 for (let r = 0; r < 16; r++) 9123 if (t[r] !== i[r]) return !1; 9124 return !0; 9125 } 9126 /** 9127 * Sets the elements of the matrix from the given array. 9128 * 9129 * @param {Array<number>} array - The matrix elements in column-major order. 9130 * @param {number} [offset=0] - Index of the first element in the array. 9131 * @return {Matrix4} A reference to this matrix. 9132 */ 9133 fromArray(e, t = 0) { 9134 for (let i = 0; i < 16; i++) 9135 this.elements[i] = e[i + t]; 9136 return this; 9137 } 9138 /** 9139 * Writes the elements of this matrix to the given array. If no array is provided, 9140 * the method returns a new instance. 9141 * 9142 * @param {Array<number>} [array=[]] - The target array holding the matrix elements in column-major order. 9143 * @param {number} [offset=0] - Index of the first element in the array. 9144 * @return {Array<number>} The matrix elements in column-major order. 9145 */ 9146 toArray(e = [], t = 0) { 9147 const i = this.elements; 9148 return e[t] = i[0], e[t + 1] = i[1], e[t + 2] = i[2], e[t + 3] = i[3], e[t + 4] = i[4], e[t + 5] = i[5], e[t + 6] = i[6], e[t + 7] = i[7], e[t + 8] = i[8], e[t + 9] = i[9], e[t + 10] = i[10], e[t + 11] = i[11], e[t + 12] = i[12], e[t + 13] = i[13], e[t + 14] = i[14], e[t + 15] = i[15], e; 9149 } 9150}; 9151Go.prototype.isMatrix4 = !0; 9152let kt = Go; 9153const Br = /* @__PURE__ */ new W(), Xn = /* @__PURE__ */ new kt(), I_ = /* @__PURE__ */ new W(0, 0, 0), D_ = /* @__PURE__ */ new W(1, 1, 1), Gi = /* @__PURE__ */ new W(), Ia = /* @__PURE__ */ new W(), An = /* @__PURE__ */ new W(), Jh = /* @__PURE__ */ new kt(), Zh = /* @__PURE__ */ new Wn(); 9154class ar { 9155 /** 9156 * Constructs a new euler instance. 9157 * 9158 * @param {number} [x=0] - The angle of the x axis in radians. 9159 * @param {number} [y=0] - The angle of the y axis in radians. 9160 * @param {number} [z=0] - The angle of the z axis in radians. 9161 * @param {string} [order=Euler.DEFAULT_ORDER] - A string representing the order that the rotations are applied. 9162 */ 9163 constructor(e = 0, t = 0, i = 0, r = ar.DEFAULT_ORDER) { 9164 this.isEuler = !0, this._x = e, this._y = t, this._z = i, this._order = r; 9165 } 9166 /** 9167 * The angle of the x axis in radians. 9168 * 9169 * @type {number} 9170 * @default 0 9171 */ 9172 get x() { 9173 return this._x; 9174 } 9175 set x(e) { 9176 this._x = e, this._onChangeCallback(); 9177 } 9178 /** 9179 * The angle of the y axis in radians. 9180 * 9181 * @type {number} 9182 * @default 0 9183 */ 9184 get y() { 9185 return this._y; 9186 } 9187 set y(e) { 9188 this._y = e, this._onChangeCallback(); 9189 } 9190 /** 9191 * The angle of the z axis in radians. 9192 * 9193 * @type {number} 9194 * @default 0 9195 */ 9196 get z() { 9197 return this._z; 9198 } 9199 set z(e) { 9200 this._z = e, this._onChangeCallback(); 9201 } 9202 /** 9203 * A string representing the order that the rotations are applied. 9204 * 9205 * @type {string} 9206 * @default 'XYZ' 9207 */ 9208 get order() { 9209 return this._order;
vendor: 10,907 bytes, lines 9210-9509
9210 } 9211 set order(e) { 9212 this._order = e, this._onChangeCallback(); 9213 } 9214 /** 9215 * Sets the Euler components. 9216 * 9217 * @param {number} x - The angle of the x axis in radians. 9218 * @param {number} y - The angle of the y axis in radians. 9219 * @param {number} z - The angle of the z axis in radians. 9220 * @param {string} [order] - A string representing the order that the rotations are applied. 9221 * @return {Euler} A reference to this Euler instance. 9222 */ 9223 set(e, t, i, r = this._order) { 9224 return this._x = e, this._y = t, this._z = i, this._order = r, this._onChangeCallback(), this; 9225 } 9226 /** 9227 * Returns a new Euler instance with copied values from this instance. 9228 * 9229 * @return {Euler} A clone of this instance. 9230 */ 9231 clone() { 9232 return new this.constructor(this._x, this._y, this._z, this._order); 9233 } 9234 /** 9235 * Copies the values of the given Euler instance to this instance. 9236 * 9237 * @param {Euler} euler - The Euler instance to copy. 9238 * @return {Euler} A reference to this Euler instance. 9239 */ 9240 copy(e) { 9241 return this._x = e._x, this._y = e._y, this._z = e._z, this._order = e._order, this._onChangeCallback(), this; 9242 } 9243 /** 9244 * Sets the angles of this Euler instance from a pure rotation matrix. 9245 * 9246 * @param {Matrix4} m - A 4x4 matrix of which the upper 3x3 of matrix is a pure rotation matrix (i.e. unscaled). 9247 * @param {string} [order] - A string representing the order that the rotations are applied. 9248 * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not. 9249 * @return {Euler} A reference to this Euler instance. 9250 */ 9251 setFromRotationMatrix(e, t = this._order, i = !0) { 9252 const r = e.elements, s = r[0], a = r[4], l = r[8], o = r[1], c = r[5], u = r[9], h = r[2], d = r[6], f = r[10]; 9253 switch (t) { 9254 case "XYZ": 9255 this._y = Math.asin(yt(l, -1, 1)), Math.abs(l) < 0.9999999 ? (this._x = Math.atan2(-u, f), this._z = Math.atan2(-a, s)) : (this._x = Math.atan2(d, c), this._z = 0); 9256 break; 9257 case "YXZ": 9258 this._x = Math.asin(-yt(u, -1, 1)), Math.abs(u) < 0.9999999 ? (this._y = Math.atan2(l, f), this._z = Math.atan2(o, c)) : (this._y = Math.atan2(-h, s), this._z = 0); 9259 break; 9260 case "ZXY": 9261 this._x = Math.asin(yt(d, -1, 1)), Math.abs(d) < 0.9999999 ? (this._y = Math.atan2(-h, f), this._z = Math.atan2(-a, c)) : (this._y = 0, this._z = Math.atan2(o, s)); 9262 break; 9263 case "ZYX": 9264 this._y = Math.asin(-yt(h, -1, 1)), Math.abs(h) < 0.9999999 ? (this._x = Math.atan2(d, f), this._z = Math.atan2(o, s)) : (this._x = 0, this._z = Math.atan2(-a, c)); 9265 break; 9266 case "YZX": 9267 this._z = Math.asin(yt(o, -1, 1)), Math.abs(o) < 0.9999999 ? (this._x = Math.atan2(-u, c), this._y = Math.atan2(-h, s)) : (this._x = 0, this._y = Math.atan2(l, f)); 9268 break; 9269 case "XZY": 9270 this._z = Math.asin(-yt(a, -1, 1)), Math.abs(a) < 0.9999999 ? (this._x = Math.atan2(d, c), this._y = Math.atan2(l, s)) : (this._x = Math.atan2(-u, f), this._y = 0); 9271 break; 9272 default: 9273 tt("Euler: .setFromRotationMatrix() encountered an unknown order: " + t); 9274 } 9275 return this._order = t, i === !0 && this._onChangeCallback(), this; 9276 } 9277 /** 9278 * Sets the angles of this Euler instance from a normalized quaternion. 9279 * 9280 * @param {Quaternion} q - A normalized Quaternion. 9281 * @param {string} [order] - A string representing the order that the rotations are applied. 9282 * @param {boolean} [update=true] - Whether the internal `onChange` callback should be executed or not. 9283 * @return {Euler} A reference to this Euler instance. 9284 */ 9285 setFromQuaternion(e, t, i) { 9286 return Jh.makeRotationFromQuaternion(e), this.setFromRotationMatrix(Jh, t, i); 9287 } 9288 /** 9289 * Sets the angles of this Euler instance from the given vector. 9290 * 9291 * @param {Vector3} v - The vector. 9292 * @param {string} [order] - A string representing the order that the rotations are applied. 9293 * @return {Euler} A reference to this Euler instance. 9294 */ 9295 setFromVector3(e, t = this._order) { 9296 return this.set(e.x, e.y, e.z, t); 9297 } 9298 /** 9299 * Resets the euler angle with a new order by creating a quaternion from this 9300 * euler angle and then setting this euler angle with the quaternion and the 9301 * new order. 9302 * 9303 * Warning: This discards revolution information. 9304 * 9305 * @param {string} [newOrder] - A string representing the new order that the rotations are applied. 9306 * @return {Euler} A reference to this Euler instance. 9307 */ 9308 reorder(e) { 9309 return Zh.setFromEuler(this), this.setFromQuaternion(Zh, e); 9310 } 9311 /** 9312 * Returns `true` if this Euler instance is equal with the given one. 9313 * 9314 * @param {Euler} euler - The Euler instance to test for equality. 9315 * @return {boolean} Whether this Euler instance is equal with the given one. 9316 */ 9317 equals(e) { 9318 return e._x === this._x && e._y === this._y && e._z === this._z && e._order === this._order; 9319 } 9320 /** 9321 * Sets this Euler instance's components to values from the given array. The first three 9322 * entries of the array are assign to the x,y and z components. An optional fourth entry 9323 * defines the Euler order. 9324 * 9325 * @param {Array<number,number,number,?string>} array - An array holding the Euler component values. 9326 * @return {Euler} A reference to this Euler instance. 9327 */ 9328 fromArray(e) { 9329 return this._x = e[0], this._y = e[1], this._z = e[2], e[3] !== void 0 && (this._order = e[3]), this._onChangeCallback(), this; 9330 } 9331 /** 9332 * Writes the components of this Euler instance to the given array. If no array is provided, 9333 * the method returns a new instance. 9334 * 9335 * @param {Array<number,number,number,string>} [array=[]] - The target array holding the Euler components. 9336 * @param {number} [offset=0] - Index of the first element in the array. 9337 * @return {Array<number,number,number,string>} The Euler components. 9338 */ 9339 toArray(e = [], t = 0) { 9340 return e[t] = this._x, e[t + 1] = this._y, e[t + 2] = this._z, e[t + 3] = this._order, e; 9341 } 9342 _onChange(e) { 9343 return this._onChangeCallback = e, this; 9344 } 9345 _onChangeCallback() { 9346 } 9347 *[Symbol.iterator]() { 9348 yield this._x, yield this._y, yield this._z, yield this._order; 9349 } 9350} 9351ar.DEFAULT_ORDER = "XYZ"; 9352class Vu { 9353 /** 9354 * Constructs a new layers instance, with membership 9355 * initially set to layer `0`. 9356 */ 9357 constructor() { 9358 this.mask = 1; 9359 } 9360 /** 9361 * Sets membership to the given layer, and remove membership all other layers. 9362 * 9363 * @param {number} layer - The layer to set. 9364 */ 9365 set(e) { 9366 this.mask = (1 << e | 0) >>> 0; 9367 } 9368 /** 9369 * Adds membership of the given layer. 9370 * 9371 * @param {number} layer - The layer to enable. 9372 */ 9373 enable(e) { 9374 this.mask |= 1 << e | 0; 9375 } 9376 /** 9377 * Adds membership to all layers. 9378 */ 9379 enableAll() { 9380 this.mask = -1; 9381 } 9382 /** 9383 * Toggles the membership of the given layer. 9384 * 9385 * @param {number} layer - The layer to toggle. 9386 */ 9387 toggle(e) { 9388 this.mask ^= 1 << e | 0; 9389 } 9390 /** 9391 * Removes membership of the given layer. 9392 * 9393 * @param {number} layer - The layer to enable. 9394 */ 9395 disable(e) { 9396 this.mask &= ~(1 << e | 0); 9397 } 9398 /** 9399 * Removes the membership from all layers. 9400 */ 9401 disableAll() { 9402 this.mask = 0; 9403 } 9404 /** 9405 * Returns `true` if this and the given layers object have at least one 9406 * layer in common. 9407 * 9408 * @param {Layers} layers - The layers to test. 9409 * @return {boolean } Whether this and the given layers object have at least one layer in common or not. 9410 */ 9411 test(e) { 9412 return (this.mask & e.mask) !== 0; 9413 } 9414 /** 9415 * Returns `true` if the given layer is enabled. 9416 * 9417 * @param {number} layer - The layer to test. 9418 * @return {boolean } Whether the given layer is enabled or not. 9419 */ 9420 isEnabled(e) { 9421 return (this.mask & (1 << e | 0)) !== 0; 9422 } 9423} 9424let U_ = 0; 9425const Qh = /* @__PURE__ */ new W(), zr = /* @__PURE__ */ new Wn(), wi = /* @__PURE__ */ new kt(), Da = /* @__PURE__ */ new W(), Ds = /* @__PURE__ */ new W(), O_ = /* @__PURE__ */ new W(), k_ = /* @__PURE__ */ new Wn(), ed = /* @__PURE__ */ new W(1, 0, 0), td = /* @__PURE__ */ new W(0, 1, 0), nd = /* @__PURE__ */ new W(0, 0, 1), id = { type: "added" }, F_ = { type: "removed" }, Hr = { type: "childadded", child: null }, yl = { type: "childremoved", child: null }; 9426class Zt extends Ir { 9427 /** 9428 * Constructs a new 3D object. 9429 */ 9430 constructor() { 9431 super(), this.isObject3D = !0, Object.defineProperty(this, "id", { value: U_++ }), this.uuid = wa(), this.name = "", this.type = "Object3D", this.parent = null, this.children = [], this.up = Zt.DEFAULT_UP.clone(); 9432 const e = new W(), t = new ar(), i = new Wn(), r = new W(1, 1, 1); 9433 function s() { 9434 i.setFromEuler(t, !1); 9435 } 9436 function a() { 9437 t.setFromQuaternion(i, void 0, !1); 9438 } 9439 t._onChange(s), i._onChange(a), Object.defineProperties(this, { 9440 /** 9441 * Represents the object's local position. 9442 * 9443 * @name Object3D#position 9444 * @type {Vector3} 9445 * @default (0,0,0) 9446 */ 9447 position: { 9448 configurable: !0, 9449 enumerable: !0, 9450 value: e 9451 }, 9452 /** 9453 * Represents the object's local rotation as Euler angles, in radians. 9454 * 9455 * @name Object3D#rotation 9456 * @type {Euler} 9457 * @default (0,0,0) 9458 */ 9459 rotation: { 9460 configurable: !0, 9461 enumerable: !0, 9462 value: t 9463 }, 9464 /** 9465 * Represents the object's local rotation as Quaternions. 9466 * 9467 * @name Object3D#quaternion 9468 * @type {Quaternion} 9469 */ 9470 quaternion: { 9471 configurable: !0, 9472 enumerable: !0, 9473 value: i 9474 }, 9475 /** 9476 * Represents the object's local scale. 9477 * 9478 * @name Object3D#scale 9479 * @type {Vector3} 9480 * @default (1,1,1) 9481 */ 9482 scale: { 9483 configurable: !0, 9484 enumerable: !0, 9485 value: r 9486 }, 9487 /** 9488 * Represents the object's model-view matrix. 9489 * 9490 * @name Object3D#modelViewMatrix 9491 * @type {Matrix4} 9492 */ 9493 modelViewMatrix: { 9494 value: new kt() 9495 }, 9496 /** 9497 * Represents the object's normal matrix. 9498 * 9499 * @name Object3D#normalMatrix 9500 * @type {Matrix3} 9501 */ 9502 normalMatrix: { 9503 value: new ot() 9504 } 9505 }), this.matrix = new kt(), this.matrixWorld = new kt(), this.matrixAutoUpdate = Zt.DEFAULT_MATRIX_AUTO_UPDATE, this.matrixWorldAutoUpdate = Zt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE, this.matrixWorldNeedsUpdate = !1, this.layers = new Vu(), this.visible = !0, this.castShadow = !1, this.receiveShadow = !1, this.frustumCulled = !0, this.renderOrder = 0, this.animations = [], this.customDepthMaterial = void 0, this.customDistanceMaterial = void 0, this.static = !1, this.userData = {}, this.pivot = null; 9506 } 9507 /** 9508 * A callback that is executed immediately before a 3D object is rendered to a shadow map. 9509 *
9510 * @param {Renderer|WebGLRenderer} renderer - The renderer. 9511 * @param {Object3D} object - The 3D object. 9512 * @param {Camera} camera - The camera that is used to render the scene. 9513 * @param {Camera} shadowCamera - The shadow camera. 9514 * @param {BufferGeometry} geometry - The 3D object's geometry. 9515 * @param {Material} depthMaterial - The depth material. 9516 * @param {Object} group - The geometry group data. 9517 */ 9518 onBeforeShadow() { 9519 } 9520 /** 9521 * A callback that is executed immediately after a 3D object is rendered to a shadow map. 9522 * 9523 * @param {Renderer|WebGLRenderer} renderer - The renderer. 9524 * @param {Object3D} object - The 3D object. 9525 * @param {Camera} camera - The camera that is used to render the scene. 9526 * @param {Camera} shadowCamera - The shadow camera. 9527 * @param {BufferGeometry} geometry - The 3D object's geometry. 9528 * @param {Material} depthMaterial - The depth material. 9529 * @param {Object} group - The geometry group data. 9530 */ 9531 onAfterShadow() { 9532 } 9533 /** 9534 * A callback that is executed immediately before a 3D object is rendered. 9535 * 9536 * @param {Renderer|WebGLRenderer} renderer - The renderer. 9537 * @param {Object3D} object - The 3D object. 9538 * @param {Camera} camera - The camera that is used to render the scene. 9539 * @param {BufferGeometry} geometry - The 3D object's geometry. 9540 * @param {Material} material - The 3D object's material. 9541 * @param {Object} group - The geometry group data. 9542 */ 9543 onBeforeRender() { 9544 } 9545 /** 9546 * A callback that is executed immediately after a 3D object is rendered. 9547 * 9548 * @param {Renderer|WebGLRenderer} renderer - The renderer. 9549 * @param {Object3D} object - The 3D object. 9550 * @param {Camera} camera - The camera that is used to render the scene. 9551 * @param {BufferGeometry} geometry - The 3D object's geometry. 9552 * @param {Material} material - The 3D object's material. 9553 * @param {Object} group - The geometry group data. 9554 */ 9555 onAfterRender() { 9556 } 9557 /** 9558 * Applies the given transformation matrix to the object and updates the object's position, 9559 * rotation and scale. 9560 * 9561 * @param {Matrix4} matrix - The transformation matrix. 9562 */ 9563 applyMatrix4(e) { 9564 this.matrixAutoUpdate && this.updateMatrix(), this.matrix.premultiply(e), this.matrix.decompose(this.position, this.quaternion, this.scale); 9565 } 9566 /** 9567 * Applies a rotation represented by given the quaternion to the 3D object. 9568 * 9569 * @param {Quaternion} q - The quaternion. 9570 * @return {Object3D} A reference to this instance. 9571 */ 9572 applyQuaternion(e) { 9573 return this.quaternion.premultiply(e), this; 9574 } 9575 /** 9576 * Sets the given rotation represented as an axis/angle couple to the 3D object. 9577 * 9578 * @param {Vector3} axis - The (normalized) axis vector. 9579 * @param {number} angle - The angle in radians. 9580 */ 9581 setRotationFromAxisAngle(e, t) { 9582 this.quaternion.setFromAxisAngle(e, t); 9583 } 9584 /** 9585 * Sets the given rotation represented as Euler angles to the 3D object. 9586 * 9587 * @param {Euler} euler - The Euler angles. 9588 */ 9589 setRotationFromEuler(e) { 9590 this.quaternion.setFromEuler(e, !0); 9591 } 9592 /** 9593 * Sets the given rotation represented as rotation matrix to the 3D object. 9594 * 9595 * @param {Matrix4} m - Although a 4x4 matrix is expected, the upper 3x3 portion must be 9596 * a pure rotation matrix (i.e, unscaled). 9597 */ 9598 setRotationFromMatrix(e) { 9599 this.quaternion.setFromRotationMatrix(e); 9600 } 9601 /** 9602 * Sets the given rotation represented as a Quaternion to the 3D object. 9603 * 9604 * @param {Quaternion} q - The Quaternion 9605 */ 9606 setRotationFromQuaternion(e) { 9607 this.quaternion.copy(e); 9608 } 9609 /** 9610 * Rotates the 3D object along an axis in local space. 9611 * 9612 * @param {Vector3} axis - The (normalized) axis vector. 9613 * @param {number} angle - The angle in radians. 9614 * @return {Object3D} A reference to this instance. 9615 */ 9616 rotateOnAxis(e, t) { 9617 return zr.setFromAxisAngle(e, t), this.quaternion.multiply(zr), this; 9618 } 9619 /** 9620 * Rotates the 3D object along an axis in world space. 9621 * 9622 * @param {Vector3} axis - The (normalized) axis vector. 9623 * @param {number} angle - The angle in radians. 9624 * @return {Object3D} A reference to this instance. 9625 */ 9626 rotateOnWorldAxis(e, t) { 9627 return zr.setFromAxisAngle(e, t), this.quaternion.premultiply(zr), this; 9628 } 9629 /** 9630 * Rotates the 3D object around its X axis in local space. 9631 * 9632 * @param {number} angle - The angle in radians. 9633 * @return {Object3D} A reference to this instance. 9634 */ 9635 rotateX(e) { 9636 return this.rotateOnAxis(ed, e); 9637 } 9638 /** 9639 * Rotates the 3D object around its Y axis in local space. 9640 * 9641 * @param {number} angle - The angle in radians. 9642 * @return {Object3D} A reference to this instance. 9643 */ 9644 rotateY(e) { 9645 return this.rotateOnAxis(td, e); 9646 } 9647 /** 9648 * Rotates the 3D object around its Z axis in local space. 9649 * 9650 * @param {number} angle - The angle in radians. 9651 * @return {Object3D} A reference to this instance. 9652 */ 9653 rotateZ(e) { 9654 return this.rotateOnAxis(nd, e); 9655 } 9656 /** 9657 * Translate the 3D object by a distance along the given axis in local space. 9658 * 9659 * @param {Vector3} axis - The (normalized) axis vector. 9660 * @param {number} distance - The distance in world units. 9661 * @return {Object3D} A reference to this instance. 9662 */ 9663 translateOnAxis(e, t) { 9664 return Qh.copy(e).applyQuaternion(this.quaternion), this.position.add(Qh.multiplyScalar(t)), this; 9665 } 9666 /** 9667 * Translate the 3D object by a distance along its X-axis in local space. 9668 * 9669 * @param {number} distance - The distance in world units. 9670 * @return {Object3D} A reference to this instance. 9671 */ 9672 translateX(e) { 9673 return this.translateOnAxis(ed, e); 9674 } 9675 /** 9676 * Translate the 3D object by a distance along its Y-axis in local space. 9677 * 9678 * @param {number} distance - The distance in world units. 9679 * @return {Object3D} A reference to this instance. 9680 */ 9681 translateY(e) { 9682 return this.translateOnAxis(td, e); 9683 } 9684 /** 9685 * Translate the 3D object by a distance along its Z-axis in local space. 9686 * 9687 * @param {number} distance - The distance in world units. 9688 * @return {Object3D} A reference to this instance. 9689 */ 9690 translateZ(e) { 9691 return this.translateOnAxis(nd, e); 9692 } 9693 /** 9694 * Converts the given vector from this 3D object's local space to world space. 9695 * 9696 * @param {Vector3} vector - The vector to convert. 9697 * @return {Vector3} The converted vector. 9698 */ 9699 localToWorld(e) { 9700 return this.updateWorldMatrix(!0, !1), e.applyMatrix4(this.matrixWorld); 9701 } 9702 /** 9703 * Converts the given vector from this 3D object's world space to local space. 9704 * 9705 * @param {Vector3} vector - The vector to convert. 9706 * @return {Vector3} The converted vector. 9707 */ 9708 worldToLocal(e) { 9709 return this.updateWorldMatrix(!0, !1), e.applyMatrix4(wi.copy(this.matrixWorld).invert()); 9710 } 9711 /** 9712 * Rotates the object to face a point in world space. 9713 * 9714 * This method does not support objects having non-uniformly-scaled parent(s). 9715 * 9716 * @param {number|Vector3} x - The x coordinate in world space. Alternatively, a vector representing a position in world space 9717 * @param {number} [y] - The y coordinate in world space. 9718 * @param {number} [z] - The z coordinate in world space. 9719 */ 9720 lookAt(e, t, i) {
vendor: 4,918 bytes, lines 9721-9836
9721 e.isVector3 ? Da.copy(e) : Da.set(e, t, i); 9722 const r = this.parent; 9723 this.updateWorldMatrix(!0, !1), Ds.setFromMatrixPosition(this.matrixWorld), this.isCamera || this.isLight ? wi.lookAt(Ds, Da, this.up) : wi.lookAt(Da, Ds, this.up), this.quaternion.setFromRotationMatrix(wi), r && (wi.extractRotation(r.matrixWorld), zr.setFromRotationMatrix(wi), this.quaternion.premultiply(zr.invert())); 9724 } 9725 /** 9726 * Adds the given 3D object as a child to this 3D object. An arbitrary number of 9727 * objects may be added. Any current parent on an object passed in here will be 9728 * removed, since an object can have at most one parent. 9729 * 9730 * @fires Object3D#added 9731 * @fires Object3D#childadded 9732 * @param {Object3D} object - The 3D object to add. 9733 * @return {Object3D} A reference to this instance. 9734 */ 9735 add(e) { 9736 if (arguments.length > 1) { 9737 for (let t = 0; t < arguments.length; t++) 9738 this.add(arguments[t]); 9739 return this; 9740 } 9741 return e === this ? (xt("Object3D.add: object can't be added as a child of itself.", e), this) : (e && e.isObject3D ? (e.removeFromParent(), e.parent = this, this.children.push(e), e.dispatchEvent(id), Hr.child = e, this.dispatchEvent(Hr), Hr.child = null) : xt("Object3D.add: object not an instance of THREE.Object3D.", e), this); 9742 } 9743 /** 9744 * Removes the given 3D object as child from this 3D object. 9745 * An arbitrary number of objects may be removed. 9746 * 9747 * @fires Object3D#removed 9748 * @fires Object3D#childremoved 9749 * @param {Object3D} object - The 3D object to remove. 9750 * @return {Object3D} A reference to this instance. 9751 */ 9752 remove(e) { 9753 if (arguments.length > 1) { 9754 for (let i = 0; i < arguments.length; i++) 9755 this.remove(arguments[i]); 9756 return this; 9757 } 9758 const t = this.children.indexOf(e); 9759 return t !== -1 && (e.parent = null, this.children.splice(t, 1), e.dispatchEvent(F_), yl.child = e, this.dispatchEvent(yl), yl.child = null), this; 9760 } 9761 /** 9762 * Removes this 3D object from its current parent. 9763 * 9764 * @fires Object3D#removed 9765 * @fires Object3D#childremoved 9766 * @return {Object3D} A reference to this instance. 9767 */ 9768 removeFromParent() { 9769 const e = this.parent; 9770 return e !== null && e.remove(this), this; 9771 } 9772 /** 9773 * Removes all child objects. 9774 * 9775 * @fires Object3D#removed 9776 * @fires Object3D#childremoved 9777 * @return {Object3D} A reference to this instance. 9778 */ 9779 clear() { 9780 return this.remove(...this.children); 9781 } 9782 /** 9783 * Adds the given 3D object as a child of this 3D object, while maintaining the object's world 9784 * transform. This method does not support scene graphs having non-uniformly-scaled nodes(s). 9785 * 9786 * @fires Object3D#added 9787 * @fires Object3D#childadded 9788 * @param {Object3D} object - The 3D object to attach. 9789 * @return {Object3D} A reference to this instance. 9790 */ 9791 attach(e) { 9792 return this.updateWorldMatrix(!0, !1), wi.copy(this.matrixWorld).invert(), e.parent !== null && (e.parent.updateWorldMatrix(!0, !1), wi.multiply(e.parent.matrixWorld)), e.applyMatrix4(wi), e.removeFromParent(), e.parent = this, this.children.push(e), e.updateWorldMatrix(!1, !0), e.dispatchEvent(id), Hr.child = e, this.dispatchEvent(Hr), Hr.child = null, this; 9793 } 9794 /** 9795 * Searches through the 3D object and its children, starting with the 3D object 9796 * itself, and returns the first with a matching ID. 9797 * 9798 * @param {number} id - The id. 9799 * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found. 9800 */ 9801 getObjectById(e) { 9802 return this.getObjectByProperty("id", e); 9803 } 9804 /** 9805 * Searches through the 3D object and its children, starting with the 3D object 9806 * itself, and returns the first with a matching name. 9807 * 9808 * @param {string} name - The name. 9809 * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found. 9810 */ 9811 getObjectByName(e) { 9812 return this.getObjectByProperty("name", e); 9813 } 9814 /** 9815 * Searches through the 3D object and its children, starting with the 3D object 9816 * itself, and returns the first with a matching property value. 9817 * 9818 * @param {string} name - The name of the property. 9819 * @param {any} value - The value. 9820 * @return {Object3D|undefined} The found 3D object. Returns `undefined` if no 3D object has been found. 9821 */ 9822 getObjectByProperty(e, t) { 9823 if (this[e] === t) return this; 9824 for (let i = 0, r = this.children.length; i < r; i++) { 9825 const a = this.children[i].getObjectByProperty(e, t); 9826 if (a !== void 0) 9827 return a; 9828 } 9829 } 9830 /** 9831 * Searches through the 3D object and its children, starting with the 3D object 9832 * itself, and returns all 3D objects with a matching property value. 9833 * 9834 * @param {string} name - The name of the property. 9835 * @param {any} value - The value. 9836 * @param {Array<Object3D>} result - The method stores the result in this array.
9837 * @return {Array<Object3D>} The found 3D objects. 9838 */ 9839 getObjectsByProperty(e, t, i = []) { 9840 this[e] === t && i.push(this); 9841 const r = this.children; 9842 for (let s = 0, a = r.length; s < a; s++) 9843 r[s].getObjectsByProperty(e, t, i); 9844 return i; 9845 } 9846 /** 9847 * Returns a vector representing the position of the 3D object in world space. 9848 * 9849 * @param {Vector3} target - The target vector the result is stored to. 9850 * @return {Vector3} The 3D object's position in world space. 9851 */ 9852 getWorldPosition(e) { 9853 return this.updateWorldMatrix(!0, !1), e.setFromMatrixPosition(this.matrixWorld); 9854 } 9855 /** 9856 * Returns a Quaternion representing the position of the 3D object in world space. 9857 * 9858 * @param {Quaternion} target - The target Quaternion the result is stored to. 9859 * @return {Quaternion} The 3D object's rotation in world space. 9860 */ 9861 getWorldQuaternion(e) { 9862 return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(Ds, e, O_), e; 9863 } 9864 /** 9865 * Returns a vector representing the scale of the 3D object in world space. 9866 * 9867 * @param {Vector3} target - The target vector the result is stored to. 9868 * @return {Vector3} The 3D object's scale in world space. 9869 */ 9870 getWorldScale(e) { 9871 return this.updateWorldMatrix(!0, !1), this.matrixWorld.decompose(Ds, k_, e), e; 9872 } 9873 /** 9874 * Returns a vector representing the ("look") direction of the 3D object in world space. 9875 * 9876 * @param {Vector3} target - The target vector the result is stored to. 9877 * @return {Vector3} The 3D object's direction in world space. 9878 */ 9879 getWorldDirection(e) { 9880 this.updateWorldMatrix(!0, !1); 9881 const t = this.matrixWorld.elements; 9882 return e.set(t[8], t[9], t[10]).normalize(); 9883 } 9884 /** 9885 * Abstract method to get intersections between a casted ray and this 9886 * 3D object. Renderable 3D objects such as {@link Mesh}, {@link Line} or {@link Points} 9887 * implement this method in order to use raycasting. 9888 * 9889 * @abstract 9890 * @param {Raycaster} raycaster - The raycaster. 9891 * @param {Array<Object>} intersects - An array holding the result of the method. 9892 */ 9893 raycast() { 9894 } 9895 /** 9896 * Executes the callback on this 3D object and all descendants. 9897 * 9898 * Note: Modifying the scene graph inside the callback is discouraged. 9899 * 9900 * @param {Function} callback - A callback function that allows to process the current 3D object. 9901 */ 9902 traverse(e) { 9903 e(this); 9904 const t = this.children; 9905 for (let i = 0, r = t.length; i < r; i++) 9906 t[i].traverse(e); 9907 } 9908 /** 9909 * Like {@link Object3D#traverse}, but the callback will only be executed for visible 3D objects. 9910 * Descendants of invisible 3D objects are not traversed. 9911 * 9912 * Note: Modifying the scene graph inside the callback is discouraged. 9913 * 9914 * @param {Function} callback - A callback function that allows to process the current 3D object. 9915 */ 9916 traverseVisible(e) { 9917 if (this.visible === !1) return; 9918 e(this); 9919 const t = this.children; 9920 for (let i = 0, r = t.length; i < r; i++) 9921 t[i].traverseVisible(e); 9922 } 9923 /** 9924 * Like {@link Object3D#traverse}, but the callback will only be executed for all ancestors. 9925 * 9926 * Note: Modifying the scene graph inside the callback is discouraged. 9927 * 9928 * @param {Function} callback - A callback function that allows to process the current 3D object. 9929 */ 9930 traverseAncestors(e) { 9931 const t = this.parent; 9932 t !== null && (e(t), t.traverseAncestors(e)); 9933 } 9934 /** 9935 * Updates the transformation matrix in local space by computing it from the current 9936 * position, rotation and scale values. 9937 */ 9938 updateMatrix() { 9939 this.matrix.compose(this.position, this.quaternion, this.scale); 9940 const e = this.pivot; 9941 if (e !== null) { 9942 const t = e.x, i = e.y, r = e.z, s = this.matrix.elements; 9943 s[12] += t - s[0] * t - s[4] * i - s[8] * r, s[13] += i - s[1] * t - s[5] * i - s[9] * r, s[14] += r - s[2] * t - s[6] * i - s[10] * r; 9944 } 9945 this.matrixWorldNeedsUpdate = !0; 9946 } 9947 /** 9948 * Updates the transformation matrix in world space of this 3D objects and its descendants. 9949 * 9950 * To ensure correct results, this method also recomputes the 3D object's transformation matrix in 9951 * local space. The computation of the local and world matrix can be controlled with the 9952 * {@link Object3D#matrixAutoUpdate} and {@link Object3D#matrixWorldAutoUpdate} flags which are both 9953 * `true` by default. Set these flags to `false` if you need more control over the update matrix process. 9954 * 9955 * @param {boolean} [force=false] - When set to `true`, a recomputation of world matrices is forced even 9956 * when {@link Object3D#matrixWorldNeedsUpdate} is `false`. 9957 */ 9958 updateMatrixWorld(e) { 9959 this.matrixAutoUpdate && this.updateMatrix(), (this.matrixWorldNeedsUpdate || e) && (this.matrixWorldAutoUpdate === !0 && (this.parent === null ? this.matrixWorld.copy(this.matrix
vendor: 79,993 bytes, lines 9959-11949
9959) : this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix)), this.matrixWorldNeedsUpdate = !1, e = !0); 9960 const t = this.children; 9961 for (let i = 0, r = t.length; i < r; i++) 9962 t[i].updateMatrixWorld(e); 9963 } 9964 /** 9965 * An alternative version of {@link Object3D#updateMatrixWorld} with more control over the 9966 * update of ancestor and descendant nodes. 9967 * 9968 * @param {boolean} [updateParents=false] Whether ancestor nodes should be updated or not. 9969 * @param {boolean} [updateChildren=false] Whether descendant nodes should be updated or not. 9970 */ 9971 updateWorldMatrix(e, t) { 9972 const i = this.parent; 9973 if (e === !0 && i !== null && i.updateWorldMatrix(!0, !1), this.matrixAutoUpdate && this.updateMatrix(), this.matrixWorldAutoUpdate === !0 && (this.parent === null ? this.matrixWorld.copy(this.matrix) : this.matrixWorld.multiplyMatrices(this.parent.matrixWorld, this.matrix)), t === !0) { 9974 const r = this.children; 9975 for (let s = 0, a = r.length; s < a; s++) 9976 r[s].updateWorldMatrix(!1, !0); 9977 } 9978 } 9979 /** 9980 * Serializes the 3D object into JSON. 9981 * 9982 * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. 9983 * @return {Object} A JSON object representing the serialized 3D object. 9984 * @see {@link ObjectLoader#parse} 9985 */ 9986 toJSON(e) { 9987 const t = e === void 0 || typeof e == "string", i = {}; 9988 t && (e = { 9989 geometries: {}, 9990 materials: {}, 9991 textures: {}, 9992 images: {}, 9993 shapes: {}, 9994 skeletons: {}, 9995 animations: {}, 9996 nodes: {} 9997 }, i.metadata = { 9998 version: 4.7, 9999 type: "Object", 10000 generator: "Object3D.toJSON" 10001 }); 10002 const r = {}; 10003 r.uuid = this.uuid, r.type = this.type, this.name !== "" && (r.name = this.name), this.castShadow === !0 && (r.castShadow = !0), this.receiveShadow === !0 && (r.receiveShadow = !0), this.visible === !1 && (r.visible = !1), this.frustumCulled === !1 && (r.frustumCulled = !1), this.renderOrder !== 0 && (r.renderOrder = this.renderOrder), this.static !== !1 && (r.static = this.static), Object.keys(this.userData).length > 0 && (r.userData = this.userData), r.layers = this.layers.mask, r.matrix = this.matrix.toArray(), r.up = this.up.toArray(), this.pivot !== null && (r.pivot = this.pivot.toArray()), this.matrixAutoUpdate === !1 && (r.matrixAutoUpdate = !1), this.morphTargetDictionary !== void 0 && (r.morphTargetDictionary = Object.assign({}, this.morphTargetDictionary)), this.morphTargetInfluences !== void 0 && (r.morphTargetInfluences = this.morphTargetInfluences.slice()), this.isInstancedMesh && (r.type = "InstancedMesh", r.count = this.count, r.instanceMatrix = this.instanceMatrix.toJSON(), this.instanceColor !== null && (r.instanceColor = this.instanceColor.toJSON())), this.isBatchedMesh && (r.type = "BatchedMesh", r.perObjectFrustumCulled = this.perObjectFrustumCulled, r.sortObjects = this.sortObjects, r.drawRanges = this._drawRanges, r.reservedRanges = this._reservedRanges, r.geometryInfo = this._geometryInfo.map((l) => ({ 10004 ...l, 10005 boundingBox: l.boundingBox ? l.boundingBox.toJSON() : void 0, 10006 boundingSphere: l.boundingSphere ? l.boundingSphere.toJSON() : void 0 10007 })), r.instanceInfo = this._instanceInfo.map((l) => ({ ...l })), r.availableInstanceIds = this._availableInstanceIds.slice(), r.availableGeometryIds = this._availableGeometryIds.slice(), r.nextIndexStart = this._nextIndexStart, r.nextVertexStart = this._nextVertexStart, r.geometryCount = this._geometryCount, r.maxInstanceCount = this._maxInstanceCount, r.maxVertexCount = this._maxVertexCount, r.maxIndexCount = this._maxIndexCount, r.geometryInitialized = this._geometryInitialized, r.matricesTexture = this._matricesTexture.toJSON(e), r.indirectTexture = this._indirectTexture.toJSON(e), this._colorsTexture !== null && (r.colorsTexture = this._colorsTexture.toJSON(e)), this.boundingSphere !== null && (r.boundingSphere = this.boundingSphere.toJSON()), this.boundingBox !== null && (r.boundingBox = this.boundingBox.toJSON())); 10008 function s(l, o) { 10009 return l[o.uuid] === void 0 && (l[o.uuid] = o.toJSON(e)), o.uuid; 10010 } 10011 if (this.isScene) 10012 this.background && (this.background.isColor ? r.background = this.background.toJSON() : this.background.isTexture && (r.background = this.background.toJSON(e).uuid)), this.environment && this.environment.isTexture && this.environment.isRenderTargetTexture !== !0 && (r.environment = this.environment.toJSON(e).uuid); 10013 else if (this.isMesh || this.isLine || this.isPoints) { 10014 r.geometry = s(e.geometries, this.geometry); 10015 const l = this.geometry.parameters; 10016 if (l !== void 0 && l.shapes !== void 0) { 10017 const o = l.shapes; 10018 if (Array.isArray(o)) 10019 for (let c = 0, u = o.length; c < u; c++) { 10020 const h = o[c]; 10021 s(e.shapes, h); 10022 } 10023 else 10024 s(e.shapes, o); 10025 } 10026 } 10027 if (this.isSkinnedMesh && (r.bindMode = this.bindMode, r.bindMatrix = this.bindMatrix.toArray(), this.skeleton !== void 0 && (s(e.skeletons, this.skeleton), r.skeleton = this.skeleton.uuid)), this.material !== void 0) 10028 if (Array.isArray(this.material)) { 10029 const l = []; 10030 for (let o = 0, c = this.material.length; o < c; o++) 10031 l.push(s(e.materials, this.material[o])); 10032 r.material = l; 10033 } else 10034 r.material = s(e.materials, this.material); 10035 if (this.children.length > 0) { 10036 r.children = []; 10037 for (let l = 0; l < this.children.length; l++) 10038 r.children.push(this.children[l].toJSON(e).object); 10039 } 10040 if (this.animations.length > 0) { 10041 r.animations = []; 10042 for (let l = 0; l < this.animations.length; l++) { 10043 const o = this.animations[l]; 10044 r.animations.push(s(e.animations, o)); 10045 } 10046 } 10047 if (t) { 10048 const l = a(e.geometries), o = a(e.materials), c = a(e.textures), u = a(e.images), h = a(e.shapes), d = a(e.skeletons), f = a(e.animations), p = a(e.nodes); 10049 l.length > 0 && (i.geometries = l), o.length > 0 && (i.materials = o), c.length > 0 && (i.textures = c), u.length > 0 && (i.images = u), h.length > 0 && (i.shapes = h), d.length > 0 && (i.skeletons = d), f.length > 0 && (i.animations = f), p.length > 0 && (i.nodes = p); 10050 } 10051 return i.object = r, i; 10052 function a(l) { 10053 const o = []; 10054 for (const c in l) { 10055 const u = l[c]; 10056 delete u.metadata, o.push(u); 10057 } 10058 return o; 10059 } 10060 } 10061 /** 10062 * Returns a new 3D object with copied values from this instance. 10063 * 10064 * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are also cloned. 10065 * @return {Object3D} A clone of this instance. 10066 */ 10067 clone(e) { 10068 return new this.constructor().copy(this, e); 10069 } 10070 /** 10071 * Copies the values of the given 3D object to this instance. 10072 * 10073 * @param {Object3D} source - The 3D object to copy. 10074 * @param {boolean} [recursive=true] - When set to `true`, descendants of the 3D object are cloned. 10075 * @return {Object3D} A reference to this instance. 10076 */ 10077 copy(e, t = !0) { 10078 if (this.name = e.name, this.up.copy(e.up), this.position.copy(e.position), this.rotation.order = e.rotation.order, this.quaternion.copy(e.quaternion), this.scale.copy(e.scale), this.pivot = e.pivot !== null ? e.pivot.clone() : null, this.matrix.copy(e.matrix), this.matrixWorld.copy(e.matrixWorld), this.matrixAutoUpdate = e.matrixAutoUpdate, this.matrixWorldAutoUpdate = e.matrixWorldAutoUpdate, this.matrixWorldNeedsUpdate = e.matrixWorldNeedsUpdate, this.layers.mask = e.layers.mask, this.visible = e.visible, this.castShadow = e.castShadow, this.receiveShadow = e.receiveShadow, this.frustumCulled = e.frustumCulled, this.renderOrder = e.renderOrder, this.static = e.static, this.animations = e.animations.slice(), this.userData = JSON.parse(JSON.stringify(e.userData)), t === !0) 10079 for (let i = 0; i < e.children.length; i++) { 10080 const r = e.children[i]; 10081 this.add(r.clone()); 10082 } 10083 return this; 10084 } 10085} 10086Zt.DEFAULT_UP = /* @__PURE__ */ new W(0, 1, 0); 10087Zt.DEFAULT_MATRIX_AUTO_UPDATE = !0; 10088Zt.DEFAULT_MATRIX_WORLD_AUTO_UPDATE = !0; 10089class Ar extends Zt { 10090 constructor() { 10091 super(), this.isGroup = !0, this.type = "Group"; 10092 } 10093} 10094const B_ = { type: "move" }; 10095class xl { 10096 /** 10097 * Constructs a new XR controller. 10098 */ 10099 constructor() { 10100 this._targetRay = null, this._grip = null, this._hand = null; 10101 } 10102 /** 10103 * Returns a group representing the hand space of the XR controller. 10104 * 10105 * @return {Group} A group representing the hand space of the XR controller. 10106 */ 10107 getHandSpace() { 10108 return this._hand === null && (this._hand = new Ar(), this._hand.matrixAutoUpdate = !1, this._hand.visible = !1, this._hand.joints = {}, this._hand.inputState = { pinching: !1 }), this._hand; 10109 } 10110 /** 10111 * Returns a group representing the target ray space of the XR controller. 10112 * 10113 * @return {Group} A group representing the target ray space of the XR controller. 10114 */ 10115 getTargetRaySpace() { 10116 return this._targetRay === null && (this._targetRay = new Ar(), this._targetRay.matrixAutoUpdate = !1, this._targetRay.visible = !1, this._targetRay.hasLinearVelocity = !1, this._targetRay.linearVelocity = new W(), this._targetRay.hasAngularVelocity = !1, this._targetRay.angularVelocity = new W()), this._targetRay; 10117 } 10118 /** 10119 * Returns a group representing the grip space of the XR controller. 10120 * 10121 * @return {Group} A group representing the grip space of the XR controller. 10122 */ 10123 getGripSpace() { 10124 return this._grip === null && (this._grip = new Ar(), this._grip.matrixAutoUpdate = !1, this._grip.visible = !1, this._grip.hasLinearVelocity = !1, this._grip.linearVelocity = new W(), this._grip.hasAngularVelocity = !1, this._grip.angularVelocity = new W(), this._grip.eventsEnabled = !1), this._grip; 10125 } 10126 /** 10127 * Dispatches the given event to the groups representing 10128 * the different coordinate spaces of the XR controller. 10129 * 10130 * @param {Object} event - The event to dispatch. 10131 * @return {WebXRController} A reference to this instance. 10132 */ 10133 dispatchEvent(e) { 10134 return this._targetRay !== null && this._targetRay.dispatchEvent(e), this._grip !== null && this._grip.dispatchEvent(e), this._hand !== null && this._hand.dispatchEvent(e), this; 10135 } 10136 /** 10137 * Connects the controller with the given XR input source. 10138 * 10139 * @param {XRInputSource} inputSource - The input source. 10140 * @return {WebXRController} A reference to this instance. 10141 */ 10142 connect(e) { 10143 if (e && e.hand) { 10144 const t = this._hand; 10145 if (t) 10146 for (const i of e.hand.values()) 10147 this._getHandJoint(t, i); 10148 } 10149 return this.dispatchEvent({ type: "connected", data: e }), this; 10150 } 10151 /** 10152 * Disconnects the controller from the given XR input source. 10153 * 10154 * @param {XRInputSource} inputSource - The input source. 10155 * @return {WebXRController} A reference to this instance. 10156 */ 10157 disconnect(e) { 10158 return this.dispatchEvent({ type: "disconnected", data: e }), this._targetRay !== null && (this._targetRay.visible = !1), this._grip !== null && (this._grip.visible = !1), this._hand !== null && (this._hand.visible = !1), this; 10159 } 10160 /** 10161 * Updates the controller with the given input source, XR frame and reference space. 10162 * This updates the transformations of the groups that represent the different 10163 * coordinate systems of the controller. 10164 * 10165 * @param {XRInputSource} inputSource - The input source. 10166 * @param {XRFrame} frame - The XR frame. 10167 * @param {XRReferenceSpace} referenceSpace - The reference space. 10168 * @return {WebXRController} A reference to this instance. 10169 */ 10170 update(e, t, i) { 10171 let r = null, s = null, a = null; 10172 const l = this._targetRay, o = this._grip, c = this._hand; 10173 if (e && t.session.visibilityState !== "visible-blurred") { 10174 if (c && e.hand) { 10175 a = !0; 10176 for (const v of e.hand.values()) { 10177 const m = t.getJointPose(v, i), g = this._getHandJoint(c, v); 10178 m !== null && (g.matrix.fromArray(m.transform.matrix), g.matrix.decompose(g.position, g.rotation, g.scale), g.matrixWorldNeedsUpdate = !0, g.jointRadius = m.radius), g.visible = m !== null; 10179 } 10180 const u = c.joints["index-finger-tip"], h = c.joints["thumb-tip"], d = u.position.distanceTo(h.position), f = 0.02, p = 5e-3; 10181 c.inputState.pinching && d > f + p ? (c.inputState.pinching = !1, this.dispatchEvent({ 10182 type: "pinchend", 10183 handedness: e.handedness, 10184 target: this 10185 })) : !c.inputState.pinching && d <= f - p && (c.inputState.pinching = !0, this.dispatchEvent({ 10186 type: "pinchstart", 10187 handedness: e.handedness, 10188 target: this 10189 })); 10190 } else 10191 o !== null && e.gripSpace && (s = t.getPose(e.gripSpace, i), s !== null && (o.matrix.fromArray(s.transform.matrix), o.matrix.decompose(o.position, o.rotation, o.scale), o.matrixWorldNeedsUpdate = !0, s.linearVelocity ? (o.hasLinearVelocity = !0, o.linearVelocity.copy(s.linearVelocity)) : o.hasLinearVelocity = !1, s.angularVelocity ? (o.hasAngularVelocity = !0, o.angularVelocity.copy(s.angularVelocity)) : o.hasAngularVelocity = !1, o.eventsEnabled && o.dispatchEvent({ 10192 type: "gripUpdated", 10193 data: e, 10194 target: this 10195 }))); 10196 l !== null && (r = t.getPose(e.targetRaySpace, i), r === null && s !== null && (r = s), r !== null && (l.matrix.fromArray(r.transform.matrix), l.matrix.decompose(l.position, l.rotation, l.scale), l.matrixWorldNeedsUpdate = !0, r.linearVelocity ? (l.hasLinearVelocity = !0, l.linearVelocity.copy(r.linearVelocity)) : l.hasLinearVelocity = !1, r.angularVelocity ? (l.hasAngularVelocity = !0, l.angularVelocity.copy(r.angularVelocity)) : l.hasAngularVelocity = !1, this.dispatchEvent(B_))); 10197 } 10198 return l !== null && (l.visible = r !== null), o !== null && (o.visible = s !== null), c !== null && (c.visible = a !== null), this; 10199 } 10200 /** 10201 * Returns a group representing the hand joint for the given input joint. 10202 * 10203 * @private 10204 * @param {Group} hand - The group representing the hand space. 10205 * @param {XRJointSpace} inputjoint - The hand joint data. 10206 * @return {Group} A group representing the hand joint for the given input joint. 10207 */ 10208 _getHandJoint(e, t) { 10209 if (e.joints[t.jointName] === void 0) { 10210 const i = new Ar(); 10211 i.matrixAutoUpdate = !1, i.visible = !1, e.joints[t.jointName] = i, e.add(i); 10212 } 10213 return e.joints[t.jointName]; 10214 } 10215} 10216const kp = { 10217 aliceblue: 15792383, 10218 antiquewhite: 16444375, 10219 aqua: 65535, 10220 aquamarine: 8388564, 10221 azure: 15794175, 10222 beige: 16119260, 10223 bisque: 16770244, 10224 black: 0, 10225 blanchedalmond: 16772045, 10226 blue: 255, 10227 blueviolet: 9055202, 10228 brown: 10824234, 10229 burlywood: 14596231, 10230 cadetblue: 6266528, 10231 chartreuse: 8388352, 10232 chocolate: 13789470, 10233 coral: 16744272, 10234 cornflowerblue: 6591981, 10235 cornsilk: 16775388, 10236 crimson: 14423100, 10237 cyan: 65535, 10238 darkblue: 139, 10239 darkcyan: 35723, 10240 darkgoldenrod: 12092939, 10241 darkgray: 11119017, 10242 darkgreen: 25600, 10243 darkgrey: 11119017, 10244 darkkhaki: 12433259, 10245 darkmagenta: 9109643, 10246 darkolivegreen: 5597999, 10247 darkorange: 16747520, 10248 darkorchid: 10040012, 10249 darkred: 9109504, 10250 darksalmon: 15308410, 10251 darkseagreen: 9419919, 10252 darkslateblue: 4734347, 10253 darkslategray: 3100495, 10254 darkslategrey: 3100495, 10255 darkturquoise: 52945, 10256 darkviolet: 9699539, 10257 deeppink: 16716947, 10258 deepskyblue: 49151, 10259 dimgray: 6908265, 10260 dimgrey: 6908265, 10261 dodgerblue: 2003199, 10262 firebrick: 11674146, 10263 floralwhite: 16775920, 10264 forestgreen: 2263842, 10265 fuchsia: 16711935, 10266 gainsboro: 14474460, 10267 ghostwhite: 16316671, 10268 gold: 16766720, 10269 goldenrod: 14329120, 10270 gray: 8421504, 10271 green: 32768, 10272 greenyellow: 11403055, 10273 grey: 8421504, 10274 honeydew: 15794160, 10275 hotpink: 16738740, 10276 indianred: 13458524, 10277 indigo: 4915330, 10278 ivory: 16777200, 10279 khaki: 15787660, 10280 lavender: 15132410, 10281 lavenderblush: 16773365, 10282 lawngreen: 8190976, 10283 lemonchiffon: 16775885, 10284 lightblue: 11393254, 10285 lightcoral: 15761536, 10286 lightcyan: 14745599, 10287 lightgoldenrodyellow: 16448210, 10288 lightgray: 13882323, 10289 lightgreen: 9498256, 10290 lightgrey: 13882323, 10291 lightpink: 16758465, 10292 lightsalmon: 16752762, 10293 lightseagreen: 2142890, 10294 lightskyblue: 8900346, 10295 lightslategray: 7833753, 10296 lightslategrey: 7833753, 10297 lightsteelblue: 11584734, 10298 lightyellow: 16777184, 10299 lime: 65280, 10300 limegreen: 3329330, 10301 linen: 16445670, 10302 magenta: 16711935, 10303 maroon: 8388608, 10304 mediumaquamarine: 6737322, 10305 mediumblue: 205, 10306 mediumorchid: 12211667, 10307 mediumpurple: 9662683, 10308 mediumseagreen: 3978097, 10309 mediumslateblue: 8087790, 10310 mediumspringgreen: 64154, 10311 mediumturquoise: 4772300, 10312 mediumvioletred: 13047173, 10313 midnightblue: 1644912, 10314 mintcream: 16121850, 10315 mistyrose: 16770273, 10316 moccasin: 16770229, 10317 navajowhite: 16768685, 10318 navy: 128, 10319 oldlace: 16643558, 10320 olive: 8421376, 10321 olivedrab: 7048739, 10322 orange: 16753920, 10323 orangered: 16729344, 10324 orchid: 14315734, 10325 palegoldenrod: 15657130, 10326 palegreen: 10025880, 10327 paleturquoise: 11529966, 10328 palevioletred: 14381203, 10329 papayawhip: 16773077, 10330 peachpuff: 16767673, 10331 peru: 13468991, 10332 pink: 16761035, 10333 plum: 14524637, 10334 powderblue: 11591910, 10335 purple: 8388736, 10336 rebeccapurple: 6697881, 10337 red: 16711680, 10338 rosybrown: 12357519, 10339 royalblue: 4286945, 10340 saddlebrown: 9127187, 10341 salmon: 16416882, 10342 sandybrown: 16032864, 10343 seagreen: 3050327, 10344 seashell: 16774638, 10345 sienna: 10506797, 10346 silver: 12632256, 10347 skyblue: 8900331, 10348 slateblue: 6970061, 10349 slategray: 7372944, 10350 slategrey: 7372944, 10351 snow: 16775930, 10352 springgreen: 65407, 10353 steelblue: 4620980, 10354 tan: 13808780, 10355 teal: 32896, 10356 thistle: 14204888, 10357 tomato: 16737095, 10358 turquoise: 4251856, 10359 violet: 15631086, 10360 wheat: 16113331, 10361 white: 16777215, 10362 whitesmoke: 16119285, 10363 yellow: 16776960, 10364 yellowgreen: 10145074 10365}, Vi = { h: 0, s: 0, l: 0 }, Ua = { h: 0, s: 0, l: 0 }; 10366function bl(n, e, t) { 10367 return t < 0 && (t += 1), t > 1 && (t -= 1), t < 1 / 6 ? n + (e - n) * 6 * t : t < 1 / 2 ? e : t < 2 / 3 ? n + (e - n) * 6 * (2 / 3 - t) : n; 10368} 10369class Et { 10370 /** 10371 * Constructs a new color. 10372 * 10373 * Note that standard method of specifying color in three.js is with a hexadecimal triplet, 10374 * and that method is used throughout the rest of the documentation. 10375 * 10376 * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are 10377 * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance. 10378 * @param {number} [g] - The green component. 10379 * @param {number} [b] - The blue component. 10380 */ 10381 constructor(e, t, i) { 10382 return this.isColor = !0, this.r = 1, this.g = 1, this.b = 1, this.set(e, t, i); 10383 } 10384 /** 10385 * Sets the colors's components from the given values. 10386 * 10387 * @param {(number|string|Color)} [r] - The red component of the color. If `g` and `b` are 10388 * not provided, it can be hexadecimal triplet, a CSS-style string or another `Color` instance. 10389 * @param {number} [g] - The green component. 10390 * @param {number} [b] - The blue component. 10391 * @return {Color} A reference to this color. 10392 */ 10393 set(e, t, i) { 10394 if (t === void 0 && i === void 0) { 10395 const r = e; 10396 r && r.isColor ? this.copy(r) : typeof r == "number" ? this.setHex(r) : typeof r == "string" && this.setStyle(r); 10397 } else 10398 this.setRGB(e, t, i); 10399 return this; 10400 } 10401 /** 10402 * Sets the colors's components to the given scalar value. 10403 * 10404 * @param {number} scalar - The scalar value. 10405 * @return {Color} A reference to this color. 10406 */ 10407 setScalar(e) { 10408 return this.r = e, this.g = e, this.b = e, this; 10409 } 10410 /** 10411 * Sets this color from a hexadecimal value. 10412 * 10413 * @param {number} hex - The hexadecimal value. 10414 * @param {string} [colorSpace=SRGBColorSpace] - The color space. 10415 * @return {Color} A reference to this color. 10416 */ 10417 setHex(e, t = Hn) { 10418 return e = Math.floor(e), this.r = (e >> 16 & 255) / 255, this.g = (e >> 8 & 255) / 255, this.b = (e & 255) / 255, _t.colorSpaceToWorking(this, t), this; 10419 } 10420 /** 10421 * Sets this color from RGB values. 10422 * 10423 * @param {number} r - Red channel value between `0.0` and `1.0`. 10424 * @param {number} g - Green channel value between `0.0` and `1.0`. 10425 * @param {number} b - Blue channel value between `0.0` and `1.0`. 10426 * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. 10427 * @return {Color} A reference to this color. 10428 */ 10429 setRGB(e, t, i, r = _t.workingColorSpace) { 10430 return this.r = e, this.g = t, this.b = i, _t.colorSpaceToWorking(this, r), this; 10431 } 10432 /** 10433 * Sets this color from RGB values. 10434 * 10435 * @param {number} h - Hue value between `0.0` and `1.0`. 10436 * @param {number} s - Saturation value between `0.0` and `1.0`. 10437 * @param {number} l - Lightness value between `0.0` and `1.0`. 10438 * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. 10439 * @return {Color} A reference to this color. 10440 */ 10441 setHSL(e, t, i, r = _t.workingColorSpace) { 10442 if (e = T_(e, 1), t = yt(t, 0, 1), i = yt(i, 0, 1), t === 0) 10443 this.r = this.g = this.b = i; 10444 else { 10445 const s = i <= 0.5 ? i * (1 + t) : i + t - i * t, a = 2 * i - s; 10446 this.r = bl(a, s, e + 1 / 3), this.g = bl(a, s, e), this.b = bl(a, s, e - 1 / 3); 10447 } 10448 return _t.colorSpaceToWorking(this, r), this; 10449 } 10450 /** 10451 * Sets this color from a CSS-style string. For example, `rgb(250, 0,0)`, 10452 * `rgb(100%, 0%, 0%)`, `hsl(0, 100%, 50%)`, `#ff0000`, `#f00`, or `red` ( or 10453 * any [X11 color name](https://en.wikipedia.org/wiki/X11_color_names#Color_name_chart) - 10454 * all 140 color names are supported). 10455 * 10456 * @param {string} style - Color as a CSS-style string. 10457 * @param {string} [colorSpace=SRGBColorSpace] - The color space. 10458 * @return {Color} A reference to this color. 10459 */ 10460 setStyle(e, t = Hn) { 10461 function i(s) { 10462 s !== void 0 && parseFloat(s) < 1 && tt("Color: Alpha component of " + e + " will be ignored."); 10463 } 10464 let r; 10465 if (r = /^(\w+)\(([^\)]*)\)/.exec(e)) { 10466 let s; 10467 const a = r[1], l = r[2]; 10468 switch (a) { 10469 case "rgb": 10470 case "rgba": 10471 if (s = /^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(l)) 10472 return i(s[4]), this.setRGB( 10473 Math.min(255, parseInt(s[1], 10)) / 255, 10474 Math.min(255, parseInt(s[2], 10)) / 255, 10475 Math.min(255, parseInt(s[3], 10)) / 255, 10476 t 10477 ); 10478 if (s = /^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(l)) 10479 return i(s[4]), this.setRGB( 10480 Math.min(100, parseInt(s[1], 10)) / 100, 10481 Math.min(100, parseInt(s[2], 10)) / 100, 10482 Math.min(100, parseInt(s[3], 10)) / 100, 10483 t 10484 ); 10485 break; 10486 case "hsl": 10487 case "hsla": 10488 if (s = /^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(l)) 10489 return i(s[4]), this.setHSL( 10490 parseFloat(s[1]) / 360, 10491 parseFloat(s[2]) / 100, 10492 parseFloat(s[3]) / 100, 10493 t 10494 ); 10495 break; 10496 default: 10497 tt("Color: Unknown color model " + e); 10498 } 10499 } else if (r = /^\#([A-Fa-f\d]+)$/.exec(e)) { 10500 const s = r[1], a = s.length; 10501 if (a === 3) 10502 return this.setRGB( 10503 parseInt(s.charAt(0), 16) / 15, 10504 parseInt(s.charAt(1), 16) / 15, 10505 parseInt(s.charAt(2), 16) / 15, 10506 t 10507 ); 10508 if (a === 6) 10509 return this.setHex(parseInt(s, 16), t); 10510 tt("Color: Invalid hex color " + e); 10511 } else if (e && e.length > 0) 10512 return this.setColorName(e, t); 10513 return this; 10514 } 10515 /** 10516 * Sets this color from a color name. Faster than {@link Color#setStyle} if 10517 * you don't need the other CSS-style formats. 10518 * 10519 * For convenience, the list of names is exposed in `Color.NAMES` as a hash. 10520 * ```js 10521 * Color.NAMES.aliceblue // returns 0xF0F8FF 10522 * ``` 10523 * 10524 * @param {string} style - The color name. 10525 * @param {string} [colorSpace=SRGBColorSpace] - The color space. 10526 * @return {Color} A reference to this color. 10527 */ 10528 setColorName(e, t = Hn) { 10529 const i = kp[e.toLowerCase()]; 10530 return i !== void 0 ? this.setHex(i, t) : tt("Color: Unknown color " + e), this; 10531 } 10532 /** 10533 * Returns a new color with copied values from this instance. 10534 * 10535 * @return {Color} A clone of this instance. 10536 */ 10537 clone() { 10538 return new this.constructor(this.r, this.g, this.b); 10539 } 10540 /** 10541 * Copies the values of the given color to this instance. 10542 * 10543 * @param {Color} color - The color to copy. 10544 * @return {Color} A reference to this color. 10545 */ 10546 copy(e) { 10547 return this.r = e.r, this.g = e.g, this.b = e.b, this; 10548 } 10549 /** 10550 * Copies the given color into this color, and then converts this color from 10551 * `SRGBColorSpace` to `LinearSRGBColorSpace`. 10552 * 10553 * @param {Color} color - The color to copy/convert. 10554 * @return {Color} A reference to this color. 10555 */ 10556 copySRGBToLinear(e) { 10557 return this.r = Oi(e.r), this.g = Oi(e.g), this.b = Oi(e.b), this; 10558 } 10559 /** 10560 * Copies the given color into this color, and then converts this color from 10561 * `LinearSRGBColorSpace` to `SRGBColorSpace`. 10562 * 10563 * @param {Color} color - The color to copy/convert. 10564 * @return {Color} A reference to this color. 10565 */ 10566 copyLinearToSRGB(e) { 10567 return this.r = ds(e.r), this.g = ds(e.g), this.b = ds(e.b), this; 10568 } 10569 /** 10570 * Converts this color from `SRGBColorSpace` to `LinearSRGBColorSpace`. 10571 * 10572 * @return {Color} A reference to this color. 10573 */ 10574 convertSRGBToLinear() { 10575 return this.copySRGBToLinear(this), this; 10576 } 10577 /** 10578 * Converts this color from `LinearSRGBColorSpace` to `SRGBColorSpace`. 10579 * 10580 * @return {Color} A reference to this color. 10581 */ 10582 convertLinearToSRGB() { 10583 return this.copyLinearToSRGB(this), this; 10584 } 10585 /** 10586 * Returns the hexadecimal value of this color. 10587 * 10588 * @param {string} [colorSpace=SRGBColorSpace] - The color space. 10589 * @return {number} The hexadecimal value. 10590 */ 10591 getHex(e = Hn) { 10592 return _t.workingToColorSpace(un.copy(this), e), Math.round(yt(un.r * 255, 0, 255)) * 65536 + Math.round(yt(un.g * 255, 0, 255)) * 256 + Math.round(yt(un.b * 255, 0, 255)); 10593 } 10594 /** 10595 * Returns the hexadecimal value of this color as a string (for example, 'FFFFFF'). 10596 * 10597 * @param {string} [colorSpace=SRGBColorSpace] - The color space. 10598 * @return {string} The hexadecimal value as a string. 10599 */ 10600 getHexString(e = Hn) { 10601 return ("000000" + this.getHex(e).toString(16)).slice(-6); 10602 } 10603 /** 10604 * Converts the colors RGB values into the HSL format and stores them into the 10605 * given target object. 10606 * 10607 * @param {{h:number,s:number,l:number}} target - The target object that is used to store the method's result. 10608 * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. 10609 * @return {{h:number,s:number,l:number}} The HSL representation of this color. 10610 */ 10611 getHSL(e, t = _t.workingColorSpace) { 10612 _t.workingToColorSpace(un.copy(this), t); 10613 const i = un.r, r = un.g, s = un.b, a = Math.max(i, r, s), l = Math.min(i, r, s); 10614 let o, c; 10615 const u = (l + a) / 2; 10616 if (l === a) 10617 o = 0, c = 0; 10618 else { 10619 const h = a - l; 10620 switch (c = u <= 0.5 ? h / (a + l) : h / (2 - a - l), a) { 10621 case i: 10622 o = (r - s) / h + (r < s ? 6 : 0); 10623 break; 10624 case r: 10625 o = (s - i) / h + 2; 10626 break; 10627 case s: 10628 o = (i - r) / h + 4; 10629 break; 10630 } 10631 o /= 6; 10632 } 10633 return e.h = o, e.s = c, e.l = u, e; 10634 } 10635 /** 10636 * Returns the RGB values of this color and stores them into the given target object. 10637 * 10638 * @param {Color} target - The target color that is used to store the method's result. 10639 * @param {string} [colorSpace=ColorManagement.workingColorSpace] - The color space. 10640 * @return {Color} The RGB representation of this color. 10641 */ 10642 getRGB(e, t = _t.workingColorSpace) { 10643 return _t.workingToColorSpace(un.copy(this), t), e.r = un.r, e.g = un.g, e.b = un.b, e; 10644 } 10645 /** 10646 * Returns the value of this color as a CSS style string. Example: `rgb(255,0,0)`. 10647 * 10648 * @param {string} [colorSpace=SRGBColorSpace] - The color space. 10649 * @return {string} The CSS representation of this color. 10650 */ 10651 getStyle(e = Hn) { 10652 _t.workingToColorSpace(un.copy(this), e); 10653 const t = un.r, i = un.g, r = un.b; 10654 return e !== Hn ? `color(${e} ${t.toFixed(3)} ${i.toFixed(3)} ${r.toFixed(3)})` : `rgb(${Math.round(t * 255)},${Math.round(i * 255)},${Math.round(r * 255)})`; 10655 } 10656 /** 10657 * Adds the given HSL values to this color's values. 10658 * Internally, this converts the color's RGB values to HSL, adds HSL 10659 * and then converts the color back to RGB. 10660 * 10661 * @param {number} h - Hue value between `0.0` and `1.0`. 10662 * @param {number} s - Saturation value between `0.0` and `1.0`. 10663 * @param {number} l - Lightness value between `0.0` and `1.0`. 10664 * @return {Color} A reference to this color. 10665 */ 10666 offsetHSL(e, t, i) { 10667 return this.getHSL(Vi), this.setHSL(Vi.h + e, Vi.s + t, Vi.l + i); 10668 } 10669 /** 10670 * Adds the RGB values of the given color to the RGB values of this color. 10671 * 10672 * @param {Color} color - The color to add. 10673 * @return {Color} A reference to this color. 10674 */ 10675 add(e) { 10676 return this.r += e.r, this.g += e.g, this.b += e.b, this; 10677 } 10678 /** 10679 * Adds the RGB values of the given colors and stores the result in this instance. 10680 * 10681 * @param {Color} color1 - The first color. 10682 * @param {Color} color2 - The second color. 10683 * @return {Color} A reference to this color. 10684 */ 10685 addColors(e, t) { 10686 return this.r = e.r + t.r, this.g = e.g + t.g, this.b = e.b + t.b, this; 10687 } 10688 /** 10689 * Adds the given scalar value to the RGB values of this color. 10690 * 10691 * @param {number} s - The scalar to add. 10692 * @return {Color} A reference to this color. 10693 */ 10694 addScalar(e) { 10695 return this.r += e, this.g += e, this.b += e, this; 10696 } 10697 /** 10698 * Subtracts the RGB values of the given color from the RGB values of this color. 10699 * 10700 * @param {Color} color - The color to subtract. 10701 * @return {Color} A reference to this color. 10702 */ 10703 sub(e) { 10704 return this.r = Math.max(0, this.r - e.r), this.g = Math.max(0, this.g - e.g), this.b = Math.max(0, this.b - e.b), this; 10705 } 10706 /** 10707 * Multiplies the RGB values of the given color with the RGB values of this color. 10708 * 10709 * @param {Color} color - The color to multiply. 10710 * @return {Color} A reference to this color. 10711 */ 10712 multiply(e) { 10713 return this.r *= e.r, this.g *= e.g, this.b *= e.b, this; 10714 } 10715 /** 10716 * Multiplies the given scalar value with the RGB values of this color. 10717 * 10718 * @param {number} s - The scalar to multiply. 10719 * @return {Color} A reference to this color. 10720 */ 10721 multiplyScalar(e) { 10722 return this.r *= e, this.g *= e, this.b *= e, this; 10723 } 10724 /** 10725 * Linearly interpolates this color's RGB values toward the RGB values of the 10726 * given color. The alpha argument can be thought of as the ratio between 10727 * the two colors, where `0.0` is this color and `1.0` is the first argument. 10728 * 10729 * @param {Color} color - The color to converge on. 10730 * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`. 10731 * @return {Color} A reference to this color. 10732 */ 10733 lerp(e, t) { 10734 return this.r += (e.r - this.r) * t, this.g += (e.g - this.g) * t, this.b += (e.b - this.b) * t, this; 10735 } 10736 /** 10737 * Linearly interpolates between the given colors and stores the result in this instance. 10738 * The alpha argument can be thought of as the ratio between the two colors, where `0.0` 10739 * is the first and `1.0` is the second color. 10740 * 10741 * @param {Color} color1 - The first color. 10742 * @param {Color} color2 - The second color. 10743 * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`. 10744 * @return {Color} A reference to this color. 10745 */ 10746 lerpColors(e, t, i) { 10747 return this.r = e.r + (t.r - e.r) * i, this.g = e.g + (t.g - e.g) * i, this.b = e.b + (t.b - e.b) * i, this; 10748 } 10749 /** 10750 * Linearly interpolates this color's HSL values toward the HSL values of the 10751 * given color. It differs from {@link Color#lerp} by not interpolating straight 10752 * from one color to the other, but instead going through all the hues in between 10753 * those two colors. The alpha argument can be thought of as the ratio between 10754 * the two colors, where 0.0 is this color and 1.0 is the first argument. 10755 * 10756 * @param {Color} color - The color to converge on. 10757 * @param {number} alpha - The interpolation factor in the closed interval `[0,1]`. 10758 * @return {Color} A reference to this color. 10759 */ 10760 lerpHSL(e, t) { 10761 this.getHSL(Vi), e.getHSL(Ua); 10762 const i = pl(Vi.h, Ua.h, t), r = pl(Vi.s, Ua.s, t), s = pl(Vi.l, Ua.l, t); 10763 return this.setHSL(i, r, s), this; 10764 } 10765 /** 10766 * Sets the color's RGB components from the given 3D vector. 10767 * 10768 * @param {Vector3} v - The vector to set. 10769 * @return {Color} A reference to this color. 10770 */ 10771 setFromVector3(e) { 10772 return this.r = e.x, this.g = e.y, this.b = e.z, this; 10773 } 10774 /** 10775 * Transforms this color with the given 3x3 matrix. 10776 * 10777 * @param {Matrix3} m - The matrix. 10778 * @return {Color} A reference to this color. 10779 */ 10780 applyMatrix3(e) { 10781 const t = this.r, i = this.g, r = this.b, s = e.elements; 10782 return this.r = s[0] * t + s[3] * i + s[6] * r, this.g = s[1] * t + s[4] * i + s[7] * r, this.b = s[2] * t + s[5] * i + s[8] * r, this; 10783 } 10784 /** 10785 * Returns `true` if this color is equal with the given one. 10786 * 10787 * @param {Color} c - The color to test for equality. 10788 * @return {boolean} Whether this bounding color is equal with the given one. 10789 */ 10790 equals(e) { 10791 return e.r === this.r && e.g === this.g && e.b === this.b; 10792 } 10793 /** 10794 * Sets this color's RGB components from the given array. 10795 * 10796 * @param {Array<number>} array - An array holding the RGB values. 10797 * @param {number} [offset=0] - The offset into the array. 10798 * @return {Color} A reference to this color. 10799 */ 10800 fromArray(e, t = 0) { 10801 return this.r = e[t], this.g = e[t + 1], this.b = e[t + 2], this; 10802 } 10803 /** 10804 * Writes the RGB components of this color to the given array. If no array is provided, 10805 * the method returns a new instance. 10806 * 10807 * @param {Array<number>} [array=[]] - The target array holding the color components. 10808 * @param {number} [offset=0] - Index of the first element in the array. 10809 * @return {Array<number>} The color components. 10810 */ 10811 toArray(e = [], t = 0) { 10812 return e[t] = this.r, e[t + 1] = this.g, e[t + 2] = this.b, e; 10813 } 10814 /** 10815 * Sets the components of this color from the given buffer attribute. 10816 * 10817 * @param {BufferAttribute} attribute - The buffer attribute holding color data. 10818 * @param {number} index - The index into the attribute. 10819 * @return {Color} A reference to this color. 10820 */ 10821 fromBufferAttribute(e, t) { 10822 return this.r = e.getX(t), this.g = e.getY(t), this.b = e.getZ(t), this; 10823 } 10824 /** 10825 * This methods defines the serialization result of this class. Returns the color 10826 * as a hexadecimal value. 10827 * 10828 * @return {number} The hexadecimal value. 10829 */ 10830 toJSON() { 10831 return this.getHex(); 10832 } 10833 *[Symbol.iterator]() { 10834 yield this.r, yield this.g, yield this.b; 10835 } 10836} 10837const un = /* @__PURE__ */ new Et(); 10838Et.NAMES = kp; 10839class jo extends Zt { 10840 /** 10841 * Constructs a new scene. 10842 */ 10843 constructor() { 10844 super(), this.isScene = !0, this.type = "Scene", this.background = null, this.environment = null, this.fog = null, this.backgroundBlurriness = 0, this.backgroundIntensity = 1, this.backgroundRotation = new ar(), this.environmentIntensity = 1, this.environmentRotation = new ar(), this.overrideMaterial = null, typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); 10845 } 10846 copy(e, t) { 10847 return super.copy(e, t), e.background !== null && (this.background = e.background.clone()), e.environment !== null && (this.environment = e.environment.clone()), e.fog !== null && (this.fog = e.fog.clone()), this.backgroundBlurriness = e.backgroundBlurriness, this.backgroundIntensity = e.backgroundIntensity, this.backgroundRotation.copy(e.backgroundRotation), this.environmentIntensity = e.environmentIntensity, this.environmentRotation.copy(e.environmentRotation), e.overrideMaterial !== null && (this.overrideMaterial = e.overrideMaterial.clone()), this.matrixAutoUpdate = e.matrixAutoUpdate, this; 10848 } 10849 toJSON(e) { 10850 const t = super.toJSON(e); 10851 return this.fog !== null && (t.object.fog = this.fog.toJSON()), this.backgroundBlurriness > 0 && (t.object.backgroundBlurriness = this.backgroundBlurriness), this.backgroundIntensity !== 1 && (t.object.backgroundIntensity = this.backgroundIntensity), t.object.backgroundRotation = this.backgroundRotation.toArray(), this.environmentIntensity !== 1 && (t.object.environmentIntensity = this.environmentIntensity), t.object.environmentRotation = this.environmentRotation.toArray(), t; 10852 } 10853} 10854const qn = /* @__PURE__ */ new W(), Si = /* @__PURE__ */ new W(), wl = /* @__PURE__ */ new W(), Ei = /* @__PURE__ */ new W(), Gr = /* @__PURE__ */ new W(), Vr = /* @__PURE__ */ new W(), rd = /* @__PURE__ */ new W(), Sl = /* @__PURE__ */ new W(), El = /* @__PURE__ */ new W(), Ml = /* @__PURE__ */ new W(), Tl = /* @__PURE__ */ new Gt(), Al = /* @__PURE__ */ new Gt(), Rl = /* @__PURE__ */ new Gt(); 10855class Zn { 10856 /** 10857 * Constructs a new triangle. 10858 * 10859 * @param {Vector3} [a=(0,0,0)] - The first corner of the triangle. 10860 * @param {Vector3} [b=(0,0,0)] - The second corner of the triangle. 10861 * @param {Vector3} [c=(0,0,0)] - The third corner of the triangle. 10862 */ 10863 constructor(e = new W(), t = new W(), i = new W()) { 10864 this.a = e, this.b = t, this.c = i; 10865 } 10866 /** 10867 * Computes the normal vector of a triangle. 10868 * 10869 * @param {Vector3} a - The first corner of the triangle. 10870 * @param {Vector3} b - The second corner of the triangle. 10871 * @param {Vector3} c - The third corner of the triangle. 10872 * @param {Vector3} target - The target vector that is used to store the method's result. 10873 * @return {Vector3} The triangle's normal. 10874 */ 10875 static getNormal(e, t, i, r) { 10876 r.subVectors(i, t), qn.subVectors(e, t), r.cross(qn); 10877 const s = r.lengthSq(); 10878 return s > 0 ? r.multiplyScalar(1 / Math.sqrt(s)) : r.set(0, 0, 0); 10879 } 10880 /** 10881 * Computes a barycentric coordinates from the given vector. 10882 * Returns `null` if the triangle is degenerate. 10883 * 10884 * @param {Vector3} point - A point in 3D space. 10885 * @param {Vector3} a - The first corner of the triangle. 10886 * @param {Vector3} b - The second corner of the triangle. 10887 * @param {Vector3} c - The third corner of the triangle. 10888 * @param {Vector3} target - The target vector that is used to store the method's result. 10889 * @return {?Vector3} The barycentric coordinates for the given point 10890 */ 10891 static getBarycoord(e, t, i, r, s) { 10892 qn.subVectors(r, t), Si.subVectors(i, t), wl.subVectors(e, t); 10893 const a = qn.dot(qn), l = qn.dot(Si), o = qn.dot(wl), c = Si.dot(Si), u = Si.dot(wl), h = a * c - l * l; 10894 if (h === 0) 10895 return s.set(0, 0, 0), null; 10896 const d = 1 / h, f = (c * o - l * u) * d, p = (a * u - l * o) * d; 10897 return s.set(1 - f - p, p, f); 10898 } 10899 /** 10900 * Returns `true` if the given point, when projected onto the plane of the 10901 * triangle, lies within the triangle. 10902 * 10903 * @param {Vector3} point - The point in 3D space to test. 10904 * @param {Vector3} a - The first corner of the triangle. 10905 * @param {Vector3} b - The second corner of the triangle. 10906 * @param {Vector3} c - The third corner of the triangle. 10907 * @return {boolean} Whether the given point, when projected onto the plane of the 10908 * triangle, lies within the triangle or not. 10909 */ 10910 static containsPoint(e, t, i, r) { 10911 return this.getBarycoord(e, t, i, r, Ei) === null ? !1 : Ei.x >= 0 && Ei.y >= 0 && Ei.x + Ei.y <= 1; 10912 } 10913 /** 10914 * Computes the value barycentrically interpolated for the given point on the 10915 * triangle. Returns `null` if the triangle is degenerate. 10916 * 10917 * @param {Vector3} point - Position of interpolated point. 10918 * @param {Vector3} p1 - The first corner of the triangle. 10919 * @param {Vector3} p2 - The second corner of the triangle. 10920 * @param {Vector3} p3 - The third corner of the triangle. 10921 * @param {Vector3} v1 - Value to interpolate of first vertex. 10922 * @param {Vector3} v2 - Value to interpolate of second vertex. 10923 * @param {Vector3} v3 - Value to interpolate of third vertex. 10924 * @param {Vector3} target - The target vector that is used to store the method's result. 10925 * @return {?Vector3} The interpolated value. 10926 */ 10927 static getInterpolation(e, t, i, r, s, a, l, o) { 10928 return this.getBarycoord(e, t, i, r, Ei) === null ? (o.x = 0, o.y = 0, "z" in o && (o.z = 0), "w" in o && (o.w = 0), null) : (o.setScalar(0), o.addScaledVector(s, Ei.x), o.addScaledVector(a, Ei.y), o.addScaledVector(l, Ei.z), o); 10929 } 10930 /** 10931 * Computes the value barycentrically interpolated for the given attribute and indices. 10932 * 10933 * @param {BufferAttribute} attr - The attribute to interpolate. 10934 * @param {number} i1 - Index of first vertex. 10935 * @param {number} i2 - Index of second vertex. 10936 * @param {number} i3 - Index of third vertex. 10937 * @param {Vector3} barycoord - The barycoordinate value to use to interpolate. 10938 * @param {Vector3} target - The target vector that is used to store the method's result. 10939 * @return {Vector3} The interpolated attribute value. 10940 */ 10941 static getInterpolatedAttribute(e, t, i, r, s, a) { 10942 return Tl.setScalar(0), Al.setScalar(0), Rl.setScalar(0), Tl.fromBufferAttribute(e, t), Al.fromBufferAttribute(e, i), Rl.fromBufferAttribute(e, r), a.setScalar(0), a.addScaledVector(Tl, s.x), a.addScaledVector(Al, s.y), a.addScaledVector(Rl, s.z), a; 10943 } 10944 /** 10945 * Returns `true` if the triangle is oriented towards the given direction. 10946 * 10947 * @param {Vector3} a - The first corner of the triangle. 10948 * @param {Vector3} b - The second corner of the triangle. 10949 * @param {Vector3} c - The third corner of the triangle. 10950 * @param {Vector3} direction - The (normalized) direction vector. 10951 * @return {boolean} Whether the triangle is oriented towards the given direction or not. 10952 */ 10953 static isFrontFacing(e, t, i, r) { 10954 return qn.subVectors(i, t), Si.subVectors(e, t), qn.cross(Si).dot(r) < 0; 10955 } 10956 /** 10957 * Sets the triangle's vertices by copying the given values. 10958 * 10959 * @param {Vector3} a - The first corner of the triangle. 10960 * @param {Vector3} b - The second corner of the triangle. 10961 * @param {Vector3} c - The third corner of the triangle. 10962 * @return {Triangle} A reference to this triangle. 10963 */ 10964 set(e, t, i) { 10965 return this.a.copy(e), this.b.copy(t), this.c.copy(i), this; 10966 } 10967 /** 10968 * Sets the triangle's vertices by copying the given array values. 10969 * 10970 * @param {Array<Vector3>} points - An array with 3D points. 10971 * @param {number} i0 - The array index representing the first corner of the triangle. 10972 * @param {number} i1 - The array index representing the second corner of the triangle. 10973 * @param {number} i2 - The array index representing the third corner of the triangle. 10974 * @return {Triangle} A reference to this triangle. 10975 */ 10976 setFromPointsAndIndices(e, t, i, r) { 10977 return this.a.copy(e[t]), this.b.copy(e[i]), this.c.copy(e[r]), this; 10978 } 10979 /** 10980 * Sets the triangle's vertices by copying the given attribute values. 10981 * 10982 * @param {BufferAttribute} attribute - A buffer attribute with 3D points data. 10983 * @param {number} i0 - The attribute index representing the first corner of the triangle. 10984 * @param {number} i1 - The attribute index representing the second corner of the triangle. 10985 * @param {number} i2 - The attribute index representing the third corner of the triangle. 10986 * @return {Triangle} A reference to this triangle. 10987 */ 10988 setFromAttributeAndIndices(e, t, i, r) { 10989 return this.a.fromBufferAttribute(e, t), this.b.fromBufferAttribute(e, i), this.c.fromBufferAttribute(e, r), this; 10990 } 10991 /** 10992 * Returns a new triangle with copied values from this instance. 10993 * 10994 * @return {Triangle} A clone of this instance. 10995 */ 10996 clone() { 10997 return new this.constructor().copy(this); 10998 } 10999 /** 11000 * Copies the values of the given triangle to this instance. 11001 * 11002 * @param {Triangle} triangle - The triangle to copy. 11003 * @return {Triangle} A reference to this triangle. 11004 */ 11005 copy(e) { 11006 return this.a.copy(e.a), this.b.copy(e.b), this.c.copy(e.c), this; 11007 } 11008 /** 11009 * Computes the area of the triangle. 11010 * 11011 * @return {number} The triangle's area. 11012 */ 11013 getArea() { 11014 return qn.subVectors(this.c, this.b), Si.subVectors(this.a, this.b), qn.cross(Si).length() * 0.5; 11015 } 11016 /** 11017 * Computes the midpoint of the triangle. 11018 * 11019 * @param {Vector3} target - The target vector that is used to store the method's result. 11020 * @return {Vector3} The triangle's midpoint. 11021 */ 11022 getMidpoint(e) { 11023 return e.addVectors(this.a, this.b).add(this.c).multiplyScalar(1 / 3); 11024 } 11025 /** 11026 * Computes the normal of the triangle. 11027 * 11028 * @param {Vector3} target - The target vector that is used to store the method's result. 11029 * @return {Vector3} The triangle's normal. 11030 */ 11031 getNormal(e) { 11032 return Zn.getNormal(this.a, this.b, this.c, e); 11033 } 11034 /** 11035 * Computes a plane the triangle lies within. 11036 * 11037 * @param {Plane} target - The target vector that is used to store the method's result. 11038 * @return {Plane} The plane the triangle lies within. 11039 */ 11040 getPlane(e) { 11041 return e.setFromCoplanarPoints(this.a, this.b, this.c); 11042 } 11043 /** 11044 * Computes a barycentric coordinates from the given vector. 11045 * Returns `null` if the triangle is degenerate. 11046 * 11047 * @param {Vector3} point - A point in 3D space. 11048 * @param {Vector3} target - The target vector that is used to store the method's result. 11049 * @return {?Vector3} The barycentric coordinates for the given point 11050 */ 11051 getBarycoord(e, t) { 11052 return Zn.getBarycoord(e, this.a, this.b, this.c, t); 11053 } 11054 /** 11055 * Computes the value barycentrically interpolated for the given point on the 11056 * triangle. Returns `null` if the triangle is degenerate. 11057 * 11058 * @param {Vector3} point - Position of interpolated point. 11059 * @param {Vector3} v1 - Value to interpolate of first vertex. 11060 * @param {Vector3} v2 - Value to interpolate of second vertex. 11061 * @param {Vector3} v3 - Value to interpolate of third vertex. 11062 * @param {Vector3} target - The target vector that is used to store the method's result. 11063 * @return {?Vector3} The interpolated value. 11064 */ 11065 getInterpolation(e, t, i, r, s) { 11066 return Zn.getInterpolation(e, this.a, this.b, this.c, t, i, r, s); 11067 } 11068 /** 11069 * Returns `true` if the given point, when projected onto the plane of the 11070 * triangle, lies within the triangle. 11071 * 11072 * @param {Vector3} point - The point in 3D space to test. 11073 * @return {boolean} Whether the given point, when projected onto the plane of the 11074 * triangle, lies within the triangle or not. 11075 */ 11076 containsPoint(e) { 11077 return Zn.containsPoint(e, this.a, this.b, this.c); 11078 } 11079 /** 11080 * Returns `true` if the triangle is oriented towards the given direction. 11081 * 11082 * @param {Vector3} direction - The (normalized) direction vector. 11083 * @return {boolean} Whether the triangle is oriented towards the given direction or not. 11084 */ 11085 isFrontFacing(e) { 11086 return Zn.isFrontFacing(this.a, this.b, this.c, e); 11087 } 11088 /** 11089 * Returns `true` if this triangle intersects with the given box. 11090 * 11091 * @param {Box3} box - The box to intersect. 11092 * @return {boolean} Whether this triangle intersects with the given box or not. 11093 */ 11094 intersectsBox(e) { 11095 return e.intersectsTriangle(this); 11096 } 11097 /** 11098 * Returns the closest point on the triangle to the given point. 11099 * 11100 * @param {Vector3} p - The point to compute the closest point for. 11101 * @param {Vector3} target - The target vector that is used to store the method's result. 11102 * @return {Vector3} The closest point on the triangle. 11103 */ 11104 closestPointToPoint(e, t) { 11105 const i = this.a, r = this.b, s = this.c; 11106 let a, l; 11107 Gr.subVectors(r, i), Vr.subVectors(s, i), Sl.subVectors(e, i); 11108 const o = Gr.dot(Sl), c = Vr.dot(Sl); 11109 if (o <= 0 && c <= 0) 11110 return t.copy(i); 11111 El.subVectors(e, r); 11112 const u = Gr.dot(El), h = Vr.dot(El); 11113 if (u >= 0 && h <= u) 11114 return t.copy(r); 11115 const d = o * h - u * c; 11116 if (d <= 0 && o >= 0 && u <= 0) 11117 return a = o / (o - u), t.copy(i).addScaledVector(Gr, a); 11118 Ml.subVectors(e, s); 11119 const f = Gr.dot(Ml), p = Vr.dot(Ml); 11120 if (p >= 0 && f <= p) 11121 return t.copy(s); 11122 const v = f * c - o * p; 11123 if (v <= 0 && c >= 0 && p <= 0) 11124 return l = c / (c - p), t.copy(i).addScaledVector(Vr, l); 11125 const m = u * p - f * h; 11126 if (m <= 0 && h - u >= 0 && f - p >= 0) 11127 return rd.subVectors(s, r), l = (h - u) / (h - u + (f - p)), t.copy(r).addScaledVector(rd, l); 11128 const g = 1 / (m + v + d); 11129 return a = v * g, l = d * g, t.copy(i).addScaledVector(Gr, a).addScaledVector(Vr, l); 11130 } 11131 /** 11132 * Returns `true` if this triangle is equal with the given one. 11133 * 11134 * @param {Triangle} triangle - The triangle to test for equality. 11135 * @return {boolean} Whether this triangle is equal with the given one. 11136 */ 11137 equals(e) { 11138 return e.a.equals(this.a) && e.b.equals(this.b) && e.c.equals(this.c); 11139 } 11140} 11141class Dr { 11142 /** 11143 * Constructs a new bounding box. 11144 * 11145 * @param {Vector3} [min=(Infinity,Infinity,Infinity)] - A vector representing the lower boundary of the box. 11146 * @param {Vector3} [max=(-Infinity,-Infinity,-Infinity)] - A vector representing the upper boundary of the box. 11147 */ 11148 constructor(e = new W(1 / 0, 1 / 0, 1 / 0), t = new W(-1 / 0, -1 / 0, -1 / 0)) { 11149 this.isBox3 = !0, this.min = e, this.max = t; 11150 } 11151 /** 11152 * Sets the lower and upper boundaries of this box. 11153 * Please note that this method only copies the values from the given objects. 11154 * 11155 * @param {Vector3} min - The lower boundary of the box. 11156 * @param {Vector3} max - The upper boundary of the box. 11157 * @return {Box3} A reference to this bounding box. 11158 */ 11159 set(e, t) { 11160 return this.min.copy(e), this.max.copy(t), this; 11161 } 11162 /** 11163 * Sets the upper and lower bounds of this box so it encloses the position data 11164 * in the given array. 11165 * 11166 * @param {Array<number>} array - An array holding 3D position data. 11167 * @return {Box3} A reference to this bounding box. 11168 */ 11169 setFromArray(e) { 11170 this.makeEmpty(); 11171 for (let t = 0, i = e.length; t < i; t += 3) 11172 this.expandByPoint(Yn.fromArray(e, t)); 11173 return this; 11174 } 11175 /** 11176 * Sets the upper and lower bounds of this box so it encloses the position data 11177 * in the given buffer attribute. 11178 * 11179 * @param {BufferAttribute} attribute - A buffer attribute holding 3D position data. 11180 * @return {Box3} A reference to this bounding box. 11181 */ 11182 setFromBufferAttribute(e) { 11183 this.makeEmpty(); 11184 for (let t = 0, i = e.count; t < i; t++) 11185 this.expandByPoint(Yn.fromBufferAttribute(e, t)); 11186 return this; 11187 } 11188 /** 11189 * Sets the upper and lower bounds of this box so it encloses the position data 11190 * in the given array. 11191 * 11192 * @param {Array<Vector3>} points - An array holding 3D position data as instances of {@link Vector3}. 11193 * @return {Box3} A reference to this bounding box. 11194 */ 11195 setFromPoints(e) { 11196 this.makeEmpty(); 11197 for (let t = 0, i = e.length; t < i; t++) 11198 this.expandByPoint(e[t]); 11199 return this; 11200 } 11201 /** 11202 * Centers this box on the given center vector and sets this box's width, height and 11203 * depth to the given size values. 11204 * 11205 * @param {Vector3} center - The center of the box. 11206 * @param {Vector3} size - The x, y and z dimensions of the box. 11207 * @return {Box3} A reference to this bounding box. 11208 */ 11209 setFromCenterAndSize(e, t) { 11210 const i = Yn.copy(t).multiplyScalar(0.5); 11211 return this.min.copy(e).sub(i), this.max.copy(e).add(i), this; 11212 } 11213 /** 11214 * Computes the world-axis-aligned bounding box for the given 3D object 11215 * (including its children), accounting for the object's, and children's, 11216 * world transforms. The function may result in a larger box than strictly necessary. 11217 * 11218 * @param {Object3D} object - The 3D object to compute the bounding box for. 11219 * @param {boolean} [precise=false] - If set to `true`, the method computes the smallest 11220 * world-axis-aligned bounding box at the expense of more computation. 11221 * @return {Box3} A reference to this bounding box. 11222 */ 11223 setFromObject(e, t = !1) { 11224 return this.makeEmpty(), this.expandByObject(e, t); 11225 } 11226 /** 11227 * Returns a new box with copied values from this instance. 11228 * 11229 * @return {Box3} A clone of this instance. 11230 */ 11231 clone() { 11232 return new this.constructor().copy(this); 11233 } 11234 /** 11235 * Copies the values of the given box to this instance. 11236 * 11237 * @param {Box3} box - The box to copy. 11238 * @return {Box3} A reference to this bounding box. 11239 */ 11240 copy(e) { 11241 return this.min.copy(e.min), this.max.copy(e.max), this; 11242 } 11243 /** 11244 * Makes this box empty which means in encloses a zero space in 3D. 11245 * 11246 * @return {Box3} A reference to this bounding box. 11247 */ 11248 makeEmpty() { 11249 return this.min.x = this.min.y = this.min.z = 1 / 0, this.max.x = this.max.y = this.max.z = -1 / 0, this; 11250 } 11251 /** 11252 * Returns true if this box includes zero points within its bounds. 11253 * Note that a box with equal lower and upper bounds still includes one 11254 * point, the one both bounds share. 11255 * 11256 * @return {boolean} Whether this box is empty or not. 11257 */ 11258 isEmpty() { 11259 return this.max.x < this.min.x || this.max.y < this.min.y || this.max.z < this.min.z; 11260 } 11261 /** 11262 * Returns the center point of this box. 11263 * 11264 * @param {Vector3} target - The target vector that is used to store the method's result. 11265 * @return {Vector3} The center point. 11266 */ 11267 getCenter(e) { 11268 return this.isEmpty() ? e.set(0, 0, 0) : e.addVectors(this.min, this.max).multiplyScalar(0.5); 11269 } 11270 /** 11271 * Returns the dimensions of this box. 11272 * 11273 * @param {Vector3} target - The target vector that is used to store the method's result. 11274 * @return {Vector3} The size. 11275 */ 11276 getSize(e) { 11277 return this.isEmpty() ? e.set(0, 0, 0) : e.subVectors(this.max, this.min); 11278 } 11279 /** 11280 * Expands the boundaries of this box to include the given point. 11281 * 11282 * @param {Vector3} point - The point that should be included by the bounding box. 11283 * @return {Box3} A reference to this bounding box. 11284 */ 11285 expandByPoint(e) { 11286 return this.min.min(e), this.max.max(e), this; 11287 } 11288 /** 11289 * Expands this box equilaterally by the given vector. The width of this 11290 * box will be expanded by the x component of the vector in both 11291 * directions. The height of this box will be expanded by the y component of 11292 * the vector in both directions. The depth of this box will be 11293 * expanded by the z component of the vector in both directions. 11294 * 11295 * @param {Vector3} vector - The vector that should expand the bounding box. 11296 * @return {Box3} A reference to this bounding box. 11297 */ 11298 expandByVector(e) { 11299 return this.min.sub(e), this.max.add(e), this; 11300 } 11301 /** 11302 * Expands each dimension of the box by the given scalar. If negative, the 11303 * dimensions of the box will be contracted. 11304 * 11305 * @param {number} scalar - The scalar value that should expand the bounding box. 11306 * @return {Box3} A reference to this bounding box. 11307 */ 11308 expandByScalar(e) { 11309 return this.min.addScalar(-e), this.max.addScalar(e), this; 11310 } 11311 /** 11312 * Expands the boundaries of this box to include the given 3D object and 11313 * its children, accounting for the object's, and children's, world 11314 * transforms. The function may result in a larger box than strictly 11315 * necessary (unless the precise parameter is set to true). 11316 * 11317 * @param {Object3D} object - The 3D object that should expand the bounding box. 11318 * @param {boolean} precise - If set to `true`, the method expands the bounding box 11319 * as little as necessary at the expense of more computation. 11320 * @return {Box3} A reference to this bounding box. 11321 */ 11322 expandByObject(e, t = !1) { 11323 e.updateWorldMatrix(!1, !1); 11324 const i = e.geometry; 11325 if (i !== void 0) { 11326 const s = i.getAttribute("position"); 11327 if (t === !0 && s !== void 0 && e.isInstancedMesh !== !0) 11328 for (let a = 0, l = s.count; a < l; a++) 11329 e.isMesh === !0 ? e.getVertexPosition(a, Yn) : Yn.fromBufferAttribute(s, a), Yn.applyMatrix4(e.matrixWorld), this.expandByPoint(Yn); 11330 else 11331 e.boundingBox !== void 0 ? (e.boundingBox === null && e.computeBoundingBox(), Oa.copy(e.boundingBox)) : (i.boundingBox === null && i.computeBoundingBox(), Oa.copy(i.boundingBox)), Oa.applyMatrix4(e.matrixWorld), this.union(Oa); 11332 } 11333 const r = e.children; 11334 for (let s = 0, a = r.length; s < a; s++) 11335 this.expandByObject(r[s], t); 11336 return this; 11337 } 11338 /** 11339 * Returns `true` if the given point lies within or on the boundaries of this box. 11340 * 11341 * @param {Vector3} point - The point to test. 11342 * @return {boolean} Whether the bounding box contains the given point or not. 11343 */ 11344 containsPoint(e) { 11345 return e.x >= this.min.x && e.x <= this.max.x && e.y >= this.min.y && e.y <= this.max.y && e.z >= this.min.z && e.z <= this.max.z; 11346 } 11347 /** 11348 * Returns `true` if this bounding box includes the entirety of the given bounding box. 11349 * If this box and the given one are identical, this function also returns `true`. 11350 * 11351 * @param {Box3} box - The bounding box to test. 11352 * @return {boolean} Whether the bounding box contains the given bounding box or not. 11353 */ 11354 containsBox(e) { 11355 return this.min.x <= e.min.x && e.max.x <= this.max.x && this.min.y <= e.min.y && e.max.y <= this.max.y && this.min.z <= e.min.z && e.max.z <= this.max.z; 11356 } 11357 /** 11358 * Returns a point as a proportion of this box's width, height and depth. 11359 * 11360 * @param {Vector3} point - A point in 3D space. 11361 * @param {Vector3} target - The target vector that is used to store the method's result. 11362 * @return {Vector3} A point as a proportion of this box's width, height and depth. 11363 */ 11364 getParameter(e, t) { 11365 return t.set( 11366 (e.x - this.min.x) / (this.max.x - this.min.x), 11367 (e.y - this.min.y) / (this.max.y - this.min.y), 11368 (e.z - this.min.z) / (this.max.z - this.min.z) 11369 ); 11370 } 11371 /** 11372 * Returns `true` if the given bounding box intersects with this bounding box. 11373 * 11374 * @param {Box3} box - The bounding box to test. 11375 * @return {boolean} Whether the given bounding box intersects with this bounding box. 11376 */ 11377 intersectsBox(e) { 11378 return e.max.x >= this.min.x && e.min.x <= this.max.x && e.max.y >= this.min.y && e.min.y <= this.max.y && e.max.z >= this.min.z && e.min.z <= this.max.z; 11379 } 11380 /** 11381 * Returns `true` if the given bounding sphere intersects with this bounding box. 11382 * 11383 * @param {Sphere} sphere - The bounding sphere to test. 11384 * @return {boolean} Whether the given bounding sphere intersects with this bounding box. 11385 */ 11386 intersectsSphere(e) { 11387 return this.clampPoint(e.center, Yn), Yn.distanceToSquared(e.center) <= e.radius * e.radius; 11388 } 11389 /** 11390 * Returns `true` if the given plane intersects with this bounding box. 11391 * 11392 * @param {Plane} plane - The plane to test. 11393 * @return {boolean} Whether the given plane intersects with this bounding box. 11394 */ 11395 intersectsPlane(e) { 11396 let t, i; 11397 return e.normal.x > 0 ? (t = e.normal.x * this.min.x, i = e.normal.x * this.max.x) : (t = e.normal.x * this.max.x, i = e.normal.x * this.min.x), e.normal.y > 0 ? (t += e.normal.y * this.min.y, i += e.normal.y * this.max.y) : (t += e.normal.y * this.max.y, i += e.normal.y * this.min.y), e.normal.z > 0 ? (t += e.normal.z * this.min.z, i += e.normal.z * this.max.z) : (t += e.normal.z * this.max.z, i += e.normal.z * this.min.z), t <= -e.constant && i >= -e.constant; 11398 } 11399 /** 11400 * Returns `true` if the given triangle intersects with this bounding box. 11401 * 11402 * @param {Triangle} triangle - The triangle to test. 11403 * @return {boolean} Whether the given triangle intersects with this bounding box. 11404 */ 11405 intersectsTriangle(e) { 11406 if (this.isEmpty()) 11407 return !1; 11408 this.getCenter(Us), ka.subVectors(this.max, Us), Wr.subVectors(e.a, Us), $r.subVectors(e.b, Us), jr.subVectors(e.c, Us), Wi.subVectors($r, Wr), $i.subVectors(jr, $r), fr.subVectors(Wr, jr); 11409 let t = [ 11410 0, 11411 -Wi.z, 11412 Wi.y, 11413 0, 11414 -$i.z, 11415 $i.y, 11416 0, 11417 -fr.z, 11418 fr.y, 11419 Wi.z, 11420 0, 11421 -Wi.x, 11422 $i.z, 11423 0, 11424 -$i.x, 11425 fr.z, 11426 0, 11427 -fr.x, 11428 -Wi.y, 11429 Wi.x, 11430 0, 11431 -$i.y, 11432 $i.x, 11433 0, 11434 -fr.y, 11435 fr.x, 11436 0 11437 ]; 11438 return !Cl(t, Wr, $r, jr, ka) || (t = [1, 0, 0, 0, 1, 0, 0, 0, 1], !Cl(t, Wr, $r, jr, ka)) ? !1 : (Fa.crossVectors(Wi, $i), t = [Fa.x, Fa.y, Fa.z], Cl(t, Wr, $r, jr, ka)); 11439 } 11440 /** 11441 * Clamps the given point within the bounds of this box. 11442 * 11443 * @param {Vector3} point - The point to clamp. 11444 * @param {Vector3} target - The target vector that is used to store the method's result. 11445 * @return {Vector3} The clamped point. 11446 */ 11447 clampPoint(e, t) { 11448 return t.copy(e).clamp(this.min, this.max); 11449 } 11450 /** 11451 * Returns the euclidean distance from any edge of this box to the specified point. If 11452 * the given point lies inside of this box, the distance will be `0`. 11453 * 11454 * @param {Vector3} point - The point to compute the distance to. 11455 * @return {number} The euclidean distance. 11456 */ 11457 distanceToPoint(e) { 11458 return this.clampPoint(e, Yn).distanceTo(e); 11459 } 11460 /** 11461 * Returns a bounding sphere that encloses this bounding box. 11462 * 11463 * @param {Sphere} target - The target sphere that is used to store the method's result. 11464 * @return {Sphere} The bounding sphere that encloses this bounding box. 11465 */ 11466 getBoundingSphere(e) { 11467 return this.isEmpty() ? e.makeEmpty() : (this.getCenter(e.center), e.radius = this.getSize(Yn).length() * 0.5), e; 11468 } 11469 /** 11470 * Computes the intersection of this bounding box and the given one, setting the upper 11471 * bound of this box to the lesser of the two boxes' upper bounds and the 11472 * lower bound of this box to the greater of the two boxes' lower bounds. If 11473 * there's no overlap, makes this box empty. 11474 * 11475 * @param {Box3} box - The bounding box to intersect with. 11476 * @return {Box3} A reference to this bounding box. 11477 */ 11478 intersect(e) { 11479 return this.min.max(e.min), this.max.min(e.max), this.isEmpty() && this.makeEmpty(), this; 11480 } 11481 /** 11482 * Computes the union of this box and another and the given one, setting the upper 11483 * bound of this box to the greater of the two boxes' upper bounds and the 11484 * lower bound of this box to the lesser of the two boxes' lower bounds. 11485 * 11486 * @param {Box3} box - The bounding box that will be unioned with this instance. 11487 * @return {Box3} A reference to this bounding box. 11488 */ 11489 union(e) { 11490 return this.min.min(e.min), this.max.max(e.max), this; 11491 } 11492 /** 11493 * Transforms this bounding box by the given 4x4 transformation matrix. 11494 * 11495 * @param {Matrix4} matrix - The transformation matrix. 11496 * @return {Box3} A reference to this bounding box. 11497 */ 11498 applyMatrix4(e) { 11499 return this.isEmpty() ? this : (Mi[0].set(this.min.x, this.min.y, this.min.z).applyMatrix4(e), Mi[1].set(this.min.x, this.min.y, this.max.z).applyMatrix4(e), Mi[2].set(this.min.x, this.max.y, this.min.z).applyMatrix4(e), Mi[3].set(this.min.x, this.max.y, this.max.z).applyMatrix4(e), Mi[4].set(this.max.x, this.min.y, this.min.z).applyMatrix4(e), Mi[5].set(this.max.x, this.min.y, this.max.z).applyMatrix4(e), Mi[6].set(this.max.x, this.max.y, this.min.z).applyMatrix4(e), Mi[7].set(this.max.x, this.max.y, this.max.z).applyMatrix4(e), this.setFromPoints(Mi), this); 11500 } 11501 /** 11502 * Adds the given offset to both the upper and lower bounds of this bounding box, 11503 * effectively moving it in 3D space. 11504 * 11505 * @param {Vector3} offset - The offset that should be used to translate the bounding box. 11506 * @return {Box3} A reference to this bounding box. 11507 */ 11508 translate(e) { 11509 return this.min.add(e), this.max.add(e), this; 11510 } 11511 /** 11512 * Returns `true` if this bounding box is equal with the given one. 11513 * 11514 * @param {Box3} box - The box to test for equality. 11515 * @return {boolean} Whether this bounding box is equal with the given one. 11516 */ 11517 equals(e) { 11518 return e.min.equals(this.min) && e.max.equals(this.max); 11519 } 11520 /** 11521 * Returns a serialized structure of the bounding box. 11522 * 11523 * @return {Object} Serialized structure with fields representing the object state. 11524 */ 11525 toJSON() { 11526 return { 11527 min: this.min.toArray(), 11528 max: this.max.toArray() 11529 }; 11530 } 11531 /** 11532 * Returns a serialized structure of the bounding box. 11533 * 11534 * @param {Object} json - The serialized json to set the box from. 11535 * @return {Box3} A reference to this bounding box. 11536 */ 11537 fromJSON(e) { 11538 return this.min.fromArray(e.min), this.max.fromArray(e.max), this; 11539 } 11540} 11541const Mi = [ 11542 /* @__PURE__ */ new W(), 11543 /* @__PURE__ */ new W(), 11544 /* @__PURE__ */ new W(), 11545 /* @__PURE__ */ new W(), 11546 /* @__PURE__ */ new W(), 11547 /* @__PURE__ */ new W(), 11548 /* @__PURE__ */ new W(), 11549 /* @__PURE__ */ new W() 11550], Yn = /* @__PURE__ */ new W(), Oa = /* @__PURE__ */ new Dr(), Wr = /* @__PURE__ */ new W(), $r = /* @__PURE__ */ new W(), jr = /* @__PURE__ */ new W(), Wi = /* @__PURE__ */ new W(), $i = /* @__PURE__ */ new W(), fr = /* @__PURE__ */ new W(), Us = /* @__PURE__ */ new W(), ka = /* @__PURE__ */ new W(), Fa = /* @__PURE__ */ new W(), pr = /* @__PURE__ */ new W(); 11551function Cl(n, e, t, i, r) { 11552 for (let s = 0, a = n.length - 3; s <= a; s += 3) { 11553 pr.fromArray(n, s); 11554 const l = r.x * Math.abs(pr.x) + r.y * Math.abs(pr.y) + r.z * Math.abs(pr.z), o = e.dot(pr), c = t.dot(pr), u = i.dot(pr); 11555 if (Math.max(-Math.max(o, c, u), Math.min(o, c, u)) > l) 11556 return !1; 11557 } 11558 return !0; 11559} 11560const Yt = /* @__PURE__ */ new W(), Ba = /* @__PURE__ */ new wt(); 11561let z_ = 0; 11562class on extends Ir { 11563 /** 11564 * Constructs a new buffer attribute. 11565 * 11566 * @param {TypedArray} array - The array holding the attribute data. 11567 * @param {number} itemSize - The item size. 11568 * @param {boolean} [normalized=false] - Whether the data are normalized or not. 11569 */ 11570 constructor(e, t, i = !1) { 11571 if (super(), Array.isArray(e)) 11572 throw new TypeError("THREE.BufferAttribute: array should be a Typed Array."); 11573 this.isBufferAttribute = !0, Object.defineProperty(this, "id", { value: z_++ }), this.name = "", this.array = e, this.itemSize = t, this.count = e !== void 0 ? e.length / t : 0, this.normalized = i, this.usage = Wh, this.updateRanges = [], this.gpuType = ti, this.version = 0; 11574 } 11575 /** 11576 * A callback function that is executed after the renderer has transferred the attribute 11577 * array data to the GPU. 11578 */ 11579 onUploadCallback() { 11580 } 11581 /** 11582 * Flag to indicate that this attribute has changed and should be re-sent to 11583 * the GPU. Set this to `true` when you modify the value of the array. 11584 * 11585 * @type {number} 11586 * @default false 11587 * @param {boolean} value 11588 */ 11589 set needsUpdate(e) { 11590 e === !0 && this.version++; 11591 } 11592 /** 11593 * Sets the usage of this buffer attribute. 11594 * 11595 * @param {(StaticDrawUsage|DynamicDrawUsage|StreamDrawUsage|StaticReadUsage|DynamicReadUsage|StreamReadUsage|StaticCopyUsage|DynamicCopyUsage|StreamCopyUsage)} value - The usage to set. 11596 * @return {BufferAttribute} A reference to this buffer attribute. 11597 */ 11598 setUsage(e) { 11599 return this.usage = e, this; 11600 } 11601 /** 11602 * Adds a range of data in the data array to be updated on the GPU. 11603 * 11604 * @param {number} start - Position at which to start update. 11605 * @param {number} count - The number of components to update. 11606 */ 11607 addUpdateRange(e, t) { 11608 this.updateRanges.push({ start: e, count: t }); 11609 } 11610 /** 11611 * Clears the update ranges. 11612 */ 11613 clearUpdateRanges() { 11614 this.updateRanges.length = 0; 11615 } 11616 /** 11617 * Copies the values of the given buffer attribute to this instance. 11618 * 11619 * @param {BufferAttribute} source - The buffer attribute to copy. 11620 * @return {BufferAttribute} A reference to this instance. 11621 */ 11622 copy(e) { 11623 return this.name = e.name, this.array = new e.array.constructor(e.array), this.itemSize = e.itemSize, this.count = e.count, this.normalized = e.normalized, this.usage = e.usage, this.gpuType = e.gpuType, this; 11624 } 11625 /** 11626 * Copies a vector from the given buffer attribute to this one. The start 11627 * and destination position in the attribute buffers are represented by the 11628 * given indices. 11629 * 11630 * @param {number} index1 - The destination index into this buffer attribute. 11631 * @param {BufferAttribute} attribute - The buffer attribute to copy from. 11632 * @param {number} index2 - The source index into the given buffer attribute. 11633 * @return {BufferAttribute} A reference to this instance. 11634 */ 11635 copyAt(e, t, i) { 11636 e *= this.itemSize, i *= t.itemSize; 11637 for (let r = 0, s = this.itemSize; r < s; r++) 11638 this.array[e + r] = t.array[i + r]; 11639 return this; 11640 } 11641 /** 11642 * Copies the given array data into this buffer attribute. 11643 * 11644 * @param {(TypedArray|Array)} array - The array to copy. 11645 * @return {BufferAttribute} A reference to this instance. 11646 */ 11647 copyArray(e) { 11648 return this.array.set(e), this; 11649 } 11650 /** 11651 * Applies the given 3x3 matrix to the given attribute. Works with 11652 * item size `2` and `3`. 11653 * 11654 * @param {Matrix3} m - The matrix to apply. 11655 * @return {BufferAttribute} A reference to this instance. 11656 */ 11657 applyMatrix3(e) { 11658 if (this.itemSize === 2) 11659 for (let t = 0, i = this.count; t < i; t++) 11660 Ba.fromBufferAttribute(this, t), Ba.applyMatrix3(e), this.setXY(t, Ba.x, Ba.y); 11661 else if (this.itemSize === 3) 11662 for (let t = 0, i = this.count; t < i; t++) 11663 Yt.fromBufferAttribute(this, t), Yt.applyMatrix3(e), this.setXYZ(t, Yt.x, Yt.y, Yt.z); 11664 return this; 11665 } 11666 /** 11667 * Applies the given 4x4 matrix to the given attribute. Only works with 11668 * item size `3`. 11669 * 11670 * @param {Matrix4} m - The matrix to apply. 11671 * @return {BufferAttribute} A reference to this instance. 11672 */ 11673 applyMatrix4(e) { 11674 for (let t = 0, i = this.count; t < i; t++) 11675 Yt.fromBufferAttribute(this, t), Yt.applyMatrix4(e), this.setXYZ(t, Yt.x, Yt.y, Yt.z); 11676 return this; 11677 } 11678 /** 11679 * Applies the given 3x3 normal matrix to the given attribute. Only works with 11680 * item size `3`. 11681 * 11682 * @param {Matrix3} m - The normal matrix to apply. 11683 * @return {BufferAttribute} A reference to this instance. 11684 */ 11685 applyNormalMatrix(e) { 11686 for (let t = 0, i = this.count; t < i; t++) 11687 Yt.fromBufferAttribute(this, t), Yt.applyNormalMatrix(e), this.setXYZ(t, Yt.x, Yt.y, Yt.z); 11688 return this; 11689 } 11690 /** 11691 * Applies the given 4x4 matrix to the given attribute. Only works with 11692 * item size `3` and with direction vectors. 11693 * 11694 * @param {Matrix4} m - The matrix to apply. 11695 * @return {BufferAttribute} A reference to this instance. 11696 */ 11697 transformDirection(e) { 11698 for (let t = 0, i = this.count; t < i; t++) 11699 Yt.fromBufferAttribute(this, t), Yt.transformDirection(e), this.setXYZ(t, Yt.x, Yt.y, Yt.z); 11700 return this; 11701 } 11702 /** 11703 * Sets the given array data in the buffer attribute. 11704 * 11705 * @param {(TypedArray|Array)} value - The array data to set. 11706 * @param {number} [offset=0] - The offset in this buffer attribute's array. 11707 * @return {BufferAttribute} A reference to this instance. 11708 */ 11709 set(e, t = 0) { 11710 return this.array.set(e, t), this; 11711 } 11712 /** 11713 * Returns the given component of the vector at the given index. 11714 * 11715 * @param {number} index - The index into the buffer attribute. 11716 * @param {number} component - The component index. 11717 * @return {number} The returned value. 11718 */ 11719 getComponent(e, t) { 11720 let i = this.array[e * this.itemSize + t]; 11721 return this.normalized && (i = Is(i, this.array)), i; 11722 } 11723 /** 11724 * Sets the given value to the given component of the vector at the given index. 11725 * 11726 * @param {number} index - The index into the buffer attribute. 11727 * @param {number} component - The component index. 11728 * @param {number} value - The value to set. 11729 * @return {BufferAttribute} A reference to this instance. 11730 */ 11731 setComponent(e, t, i) { 11732 return this.normalized && (i = wn(i, this.array)), this.array[e * this.itemSize + t] = i, this; 11733 } 11734 /** 11735 * Returns the x component of the vector at the given index. 11736 * 11737 * @param {number} index - The index into the buffer attribute. 11738 * @return {number} The x component. 11739 */ 11740 getX(e) { 11741 let t = this.array[e * this.itemSize]; 11742 return this.normalized && (t = Is(t, this.array)), t; 11743 } 11744 /** 11745 * Sets the x component of the vector at the given index. 11746 * 11747 * @param {number} index - The index into the buffer attribute. 11748 * @param {number} x - The value to set. 11749 * @return {BufferAttribute} A reference to this instance. 11750 */ 11751 setX(e, t) { 11752 return this.normalized && (t = wn(t, this.array)), this.array[e * this.itemSize] = t, this; 11753 } 11754 /** 11755 * Returns the y component of the vector at the given index. 11756 * 11757 * @param {number} index - The index into the buffer attribute. 11758 * @return {number} The y component. 11759 */ 11760 getY(e) { 11761 let t = this.array[e * this.itemSize + 1]; 11762 return this.normalized && (t = Is(t, this.array)), t; 11763 } 11764 /** 11765 * Sets the y component of the vector at the given index. 11766 * 11767 * @param {number} index - The index into the buffer attribute. 11768 * @param {number} y - The value to set. 11769 * @return {BufferAttribute} A reference to this instance. 11770 */ 11771 setY(e, t) { 11772 return this.normalized && (t = wn(t, this.array)), this.array[e * this.itemSize + 1] = t, this; 11773 } 11774 /** 11775 * Returns the z component of the vector at the given index. 11776 * 11777 * @param {number} index - The index into the buffer attribute. 11778 * @return {number} The z component. 11779 */ 11780 getZ(e) { 11781 let t = this.array[e * this.itemSize + 2]; 11782 return this.normalized && (t = Is(t, this.array)), t; 11783 } 11784 /** 11785 * Sets the z component of the vector at the given index. 11786 * 11787 * @param {number} index - The index into the buffer attribute. 11788 * @param {number} z - The value to set. 11789 * @return {BufferAttribute} A reference to this instance. 11790 */ 11791 setZ(e, t) { 11792 return this.normalized && (t = wn(t, this.array)), this.array[e * this.itemSize + 2] = t, this; 11793 } 11794 /** 11795 * Returns the w component of the vector at the given index. 11796 * 11797 * @param {number} index - The index into the buffer attribute. 11798 * @return {number} The w component. 11799 */ 11800 getW(e) { 11801 let t = this.array[e * this.itemSize + 3]; 11802 return this.normalized && (t = Is(t, this.array)), t; 11803 } 11804 /** 11805 * Sets the w component of the vector at the given index. 11806 * 11807 * @param {number} index - The index into the buffer attribute. 11808 * @param {number} w - The value to set. 11809 * @return {BufferAttribute} A reference to this instance. 11810 */ 11811 setW(e, t) { 11812 return this.normalized && (t = wn(t, this.array)), this.array[e * this.itemSize + 3] = t, this; 11813 } 11814 /** 11815 * Sets the x and y component of the vector at the given index. 11816 * 11817 * @param {number} index - The index into the buffer attribute. 11818 * @param {number} x - The value for the x component to set. 11819 * @param {number} y - The value for the y component to set. 11820 * @return {BufferAttribute} A reference to this instance. 11821 */ 11822 setXY(e, t, i) { 11823 return e *= this.itemSize, this.normalized && (t = wn(t, this.array), i = wn(i, this.array)), this.array[e + 0] = t, this.array[e + 1] = i, this; 11824 } 11825 /** 11826 * Sets the x, y and z component of the vector at the given index. 11827 * 11828 * @param {number} index - The index into the buffer attribute. 11829 * @param {number} x - The value for the x component to set. 11830 * @param {number} y - The value for the y component to set. 11831 * @param {number} z - The value for the z component to set. 11832 * @return {BufferAttribute} A reference to this instance. 11833 */ 11834 setXYZ(e, t, i, r) { 11835 return e *= this.itemSize, this.normalized && (t = wn(t, this.array), i = wn(i, this.array), r = wn(r, this.array)), this.array[e + 0] = t, this.array[e + 1] = i, this.array[e + 2] = r, this; 11836 } 11837 /** 11838 * Sets the x, y, z and w component of the vector at the given index. 11839 * 11840 * @param {number} index - The index into the buffer attribute. 11841 * @param {number} x - The value for the x component to set. 11842 * @param {number} y - The value for the y component to set. 11843 * @param {number} z - The value for the z component to set. 11844 * @param {number} w - The value for the w component to set. 11845 * @return {BufferAttribute} A reference to this instance. 11846 */ 11847 setXYZW(e, t, i, r, s) { 11848 return e *= this.itemSize, this.normalized && (t = wn(t, this.array), i = wn(i, this.array), r = wn(r, this.array), s = wn(s, this.array)), this.array[e + 0] = t, this.array[e + 1] = i, this.array[e + 2] = r, this.array[e + 3] = s, this; 11849 } 11850 /** 11851 * Sets the given callback function that is executed after the Renderer has transferred 11852 * the attribute array data to the GPU. Can be used to perform clean-up operations after 11853 * the upload when attribute data are not needed anymore on the CPU side. 11854 * 11855 * @param {Function} callback - The `onUpload()` callback. 11856 * @return {BufferAttribute} A reference to this instance. 11857 */ 11858 onUpload(e) { 11859 return this.onUploadCallback = e, this; 11860 } 11861 /** 11862 * Returns a new buffer attribute with copied values from this instance. 11863 * 11864 * @return {BufferAttribute} A clone of this instance. 11865 */ 11866 clone() { 11867 return new this.constructor(this.array, this.itemSize).copy(this); 11868 } 11869 /** 11870 * Serializes the buffer attribute into JSON. 11871 * 11872 * @return {Object} A JSON object representing the serialized buffer attribute. 11873 */ 11874 toJSON() { 11875 const e = { 11876 itemSize: this.itemSize, 11877 type: this.array.constructor.name, 11878 array: Array.from(this.array), 11879 normalized: this.normalized 11880 }; 11881 return this.name !== "" && (e.name = this.name), this.usage !== Wh && (e.usage = this.usage), e; 11882 } 11883 /** 11884 * Disposes of the buffer attribute. Available only in {@link WebGPURenderer}. 11885 */ 11886 dispose() { 11887 this.dispatchEvent({ type: "dispose" }); 11888 } 11889} 11890class Fp extends on { 11891 /** 11892 * Constructs a new buffer attribute. 11893 * 11894 * @param {(Array<number>|Uint16Array)} array - The array holding the attribute data. 11895 * @param {number} itemSize - The item size. 11896 * @param {boolean} [normalized=false] - Whether the data are normalized or not. 11897 */ 11898 constructor(e, t, i) { 11899 super(new Uint16Array(e), t, i); 11900 } 11901} 11902class Bp extends on { 11903 /** 11904 * Constructs a new buffer attribute. 11905 * 11906 * @param {(Array<number>|Uint32Array)} array - The array holding the attribute data. 11907 * @param {number} itemSize - The item size. 11908 * @param {boolean} [normalized=false] - Whether the data are normalized or not. 11909 */ 11910 constructor(e, t, i) { 11911 super(new Uint32Array(e), t, i); 11912 } 11913} 11914class vn extends on { 11915 /** 11916 * Constructs a new buffer attribute. 11917 * 11918 * @param {(Array<number>|Float32Array)} array - The array holding the attribute data. 11919 * @param {number} itemSize - The item size. 11920 * @param {boolean} [normalized=false] - Whether the data are normalized or not. 11921 */ 11922 constructor(e, t, i) { 11923 super(new Float32Array(e), t, i); 11924 } 11925} 11926const H_ = /* @__PURE__ */ new Dr(), Os = /* @__PURE__ */ new W(), Pl = /* @__PURE__ */ new W(); 11927class Ss { 11928 /** 11929 * Constructs a new sphere. 11930 * 11931 * @param {Vector3} [center=(0,0,0)] - The center of the sphere 11932 * @param {number} [radius=-1] - The radius of the sphere. 11933 */ 11934 constructor(e = new W(), t = -1) { 11935 this.isSphere = !0, this.center = e, this.radius = t; 11936 } 11937 /** 11938 * Sets the sphere's components by copying the given values. 11939 * 11940 * @param {Vector3} center - The center. 11941 * @param {number} radius - The radius. 11942 * @return {Sphere} A reference to this sphere. 11943 */ 11944 set(e, t) { 11945 return this.center.copy(e), this.radius = t, this; 11946 } 11947 /** 11948 * Computes the minimum bounding sphere for list of points. 11949 * If the optional center point is given, it is used as the sphere's
11950 * center. Otherwise, the center of the axis-aligned bounding box 11951 * encompassing the points is calculated. 11952 * 11953 * @param {Array<Vector3>} points - A list of points in 3D space. 11954 * @param {Vector3} [optionalCenter] - The center of the sphere. 11955 * @return {Sphere} A reference to this sphere. 11956 */ 11957 setFromPoints(e, t) { 11958 const i = this.center; 11959 t !== void 0 ? i.copy(t) : H_.setFromPoints(e).getCenter(i); 11960 let r = 0; 11961 for (let s = 0, a = e.length; s < a; s++) 11962 r = Math.max(r, i.distanceToSquared(e[s])); 11963 return this.radius = Math.sqrt(r), this; 11964 } 11965 /** 11966 * Copies the values of the given sphere to this instance. 11967 * 11968 * @param {Sphere} sphere - The sphere to copy. 11969 * @return {Sphere} A reference to this sphere. 11970 */ 11971 copy(e) { 11972 return this.center.copy(e.center), this.radius = e.radius, this; 11973 } 11974 /** 11975 * Returns `true` if the sphere is empty (the radius set to a negative number). 11976 * 11977 * Spheres with a radius of `0` contain only their center point and are not 11978 * considered to be empty. 11979 * 11980 * @return {boolean} Whether this sphere is empty or not. 11981 */ 11982 isEmpty() { 11983 return this.radius < 0; 11984 } 11985 /** 11986 * Makes this sphere empty which means in encloses a zero space in 3D. 11987 * 11988 * @return {Sphere} A reference to this sphere. 11989 */ 11990 makeEmpty() { 11991 return this.center.set(0, 0, 0), this.radius = -1, this; 11992 } 11993 /** 11994 * Returns `true` if this sphere contains the given point inclusive of 11995 * the surface of the sphere. 11996 * 11997 * @param {Vector3} point - The point to check. 11998 * @return {boolean} Whether this sphere contains the given point or not. 11999 */ 12000 containsPoint(e) { 12001 return e.distanceToSquared(this.center) <= this.radius * this.radius; 12002 } 12003 /** 12004 * Returns the closest distance from the boundary of the sphere to the 12005 * given point. If the sphere contains the point, the distance will 12006 * be negative. 12007 * 12008 * @param {Vector3} point - The point to compute the distance to. 12009 * @return {number} The distance to the point. 12010 */ 12011 distanceToPoint(e) { 12012 return e.distanceTo(this.center) - this.radius; 12013 } 12014 /** 12015 * Returns `true` if this sphere intersects with the given one. 12016 * 12017 * @param {Sphere} sphere - The sphere to test. 12018 * @return {boolean} Whether this sphere intersects with the given one or not. 12019 */ 12020 intersectsSphere(e) { 12021 const t = this.radius + e.radius; 12022 return e.center.distanceToSquared(this.center) <= t * t; 12023 } 12024 /** 12025 * Returns `true` if this sphere intersects with the given box. 12026 * 12027 * @param {Box3} box - The box to test. 12028 * @return {boolean} Whether this sphere intersects with the given box or not. 12029 */ 12030 intersectsBox(e) { 12031 return e.intersectsSphere(this); 12032 } 12033 /** 12034 * Returns `true` if this sphere intersects with the given plane. 12035 * 12036 * @param {Plane} plane - The plane to test. 12037 * @return {boolean} Whether this sphere intersects with the given plane or not. 12038 */ 12039 intersectsPlane(e) { 12040 return Math.abs(e.distanceToPoint(this.center)) <= this.radius; 12041 } 12042 /** 12043 * Clamps a point within the sphere. If the point is outside the sphere, it 12044 * will clamp it to the closest point on the edge of the sphere. Points 12045 * already inside the sphere will not be affected. 12046 * 12047 * @param {Vector3} point - The plane to clamp. 12048 * @param {Vector3} target - The target vector that is used to store the method's result. 12049 * @return {Vector3} The clamped point. 12050 */ 12051 clampPoint(e, t) { 12052 const i = this.center.distanceToSquared(e); 12053 return t.copy(e), i > this.radius * this.radius && (t.sub(this.center).normalize(), t.multiplyScalar(this.radius).add(this.center)), t; 12054 } 12055 /** 12056 * Returns a bounding box that encloses this sphere. 12057 * 12058 * @param {Box3} target - The target box that is used to store the method's result. 12059 * @return {Box3} The bounding box that encloses this sphere. 12060 */ 12061 getBoundingBox(e) { 12062 return this.isEmpty() ? (e.makeEmpty(), e) : (e.set(this.center, this.center), e.expandByScalar(this.radius), e); 12063 } 12064 /** 12065 * Transforms this sphere with the given 4x4 transformation matrix. 12066 * 12067 * @param {Matrix4} matrix - The transformation matrix. 12068 * @return {Sphere} A reference to this sphere. 12069 */ 12070 applyMatrix4(e) {
vendor: 86,028 bytes, lines 12071-13878
12071 return this.center.applyMatrix4(e), this.radius = this.radius * e.getMaxScaleOnAxis(), this; 12072 } 12073 /** 12074 * Translates the sphere's center by the given offset. 12075 * 12076 * @param {Vector3} offset - The offset. 12077 * @return {Sphere} A reference to this sphere. 12078 */ 12079 translate(e) { 12080 return this.center.add(e), this; 12081 } 12082 /** 12083 * Expands the boundaries of this sphere to include the given point. 12084 * 12085 * @param {Vector3} point - The point to include. 12086 * @return {Sphere} A reference to this sphere. 12087 */ 12088 expandByPoint(e) { 12089 if (this.isEmpty()) 12090 return this.center.copy(e), this.radius = 0, this; 12091 Os.subVectors(e, this.center); 12092 const t = Os.lengthSq(); 12093 if (t > this.radius * this.radius) { 12094 const i = Math.sqrt(t), r = (i - this.radius) * 0.5; 12095 this.center.addScaledVector(Os, r / i), this.radius += r; 12096 } 12097 return this; 12098 } 12099 /** 12100 * Expands this sphere to enclose both the original sphere and the given sphere. 12101 * 12102 * @param {Sphere} sphere - The sphere to include. 12103 * @return {Sphere} A reference to this sphere. 12104 */ 12105 union(e) { 12106 return e.isEmpty() ? this : this.isEmpty() ? (this.copy(e), this) : (this.center.equals(e.center) === !0 ? this.radius = Math.max(this.radius, e.radius) : (Pl.subVectors(e.center, this.center).setLength(e.radius), this.expandByPoint(Os.copy(e.center).add(Pl)), this.expandByPoint(Os.copy(e.center).sub(Pl))), this); 12107 } 12108 /** 12109 * Returns `true` if this sphere is equal with the given one. 12110 * 12111 * @param {Sphere} sphere - The sphere to test for equality. 12112 * @return {boolean} Whether this bounding sphere is equal with the given one. 12113 */ 12114 equals(e) { 12115 return e.center.equals(this.center) && e.radius === this.radius; 12116 } 12117 /** 12118 * Returns a new sphere with copied values from this instance. 12119 * 12120 * @return {Sphere} A clone of this instance. 12121 */ 12122 clone() { 12123 return new this.constructor().copy(this); 12124 } 12125 /** 12126 * Returns a serialized structure of the bounding sphere. 12127 * 12128 * @return {Object} Serialized structure with fields representing the object state. 12129 */ 12130 toJSON() { 12131 return { 12132 radius: this.radius, 12133 center: this.center.toArray() 12134 }; 12135 } 12136 /** 12137 * Returns a serialized structure of the bounding sphere. 12138 * 12139 * @param {Object} json - The serialized json to set the sphere from. 12140 * @return {Sphere} A reference to this bounding sphere. 12141 */ 12142 fromJSON(e) { 12143 return this.radius = e.radius, this.center.fromArray(e.center), this; 12144 } 12145} 12146let G_ = 0; 12147const kn = /* @__PURE__ */ new kt(), Ll = /* @__PURE__ */ new Zt(), Xr = /* @__PURE__ */ new W(), Rn = /* @__PURE__ */ new Dr(), ks = /* @__PURE__ */ new Dr(), tn = /* @__PURE__ */ new W(); 12148class xn extends Ir { 12149 /** 12150 * Constructs a new geometry. 12151 */ 12152 constructor() { 12153 super(), this.isBufferGeometry = !0, Object.defineProperty(this, "id", { value: G_++ }), this.uuid = wa(), this.name = "", this.type = "BufferGeometry", this.index = null, this.indirect = null, this.indirectOffset = 0, this.attributes = {}, this.morphAttributes = {}, this.morphTargetsRelative = !1, this.groups = [], this.boundingBox = null, this.boundingSphere = null, this.drawRange = { start: 0, count: 1 / 0 }, this.userData = {}; 12154 } 12155 /** 12156 * Returns the index of this geometry. 12157 * 12158 * @return {?BufferAttribute} The index. Returns `null` if no index is defined. 12159 */ 12160 getIndex() { 12161 return this.index; 12162 } 12163 /** 12164 * Sets the given index to this geometry. 12165 * 12166 * @param {Array<number>|BufferAttribute} index - The index to set. 12167 * @return {BufferGeometry} A reference to this instance. 12168 */ 12169 setIndex(e) { 12170 return Array.isArray(e) ? this.index = new (w_(e) ? Bp : Fp)(e, 1) : this.index = e, this; 12171 } 12172 /** 12173 * Sets the given indirect attribute to this geometry. 12174 * 12175 * @param {BufferAttribute} indirect - The attribute holding indirect draw calls. 12176 * @param {number|Array<number>} [indirectOffset=0] - The offset, in bytes, into the indirect drawing buffer where the value data begins. If an array is provided, multiple indirect draw calls will be made for each offset. 12177 * @return {BufferGeometry} A reference to this instance. 12178 */ 12179 setIndirect(e, t = 0) { 12180 return this.indirect = e, this.indirectOffset = t, this; 12181 } 12182 /** 12183 * Returns the indirect attribute of this geometry. 12184 * 12185 * @return {?BufferAttribute} The indirect attribute. Returns `null` if no indirect attribute is defined. 12186 */ 12187 getIndirect() { 12188 return this.indirect; 12189 } 12190 /** 12191 * Returns the buffer attribute for the given name. 12192 * 12193 * @param {string} name - The attribute name. 12194 * @return {BufferAttribute|InterleavedBufferAttribute|undefined} The buffer attribute. 12195 * Returns `undefined` if not attribute has been found. 12196 */ 12197 getAttribute(e) { 12198 return this.attributes[e]; 12199 } 12200 /** 12201 * Sets the given attribute for the given name. 12202 * 12203 * @param {string} name - The attribute name. 12204 * @param {BufferAttribute|InterleavedBufferAttribute} attribute - The attribute to set. 12205 * @return {BufferGeometry} A reference to this instance. 12206 */ 12207 setAttribute(e, t) { 12208 return this.attributes[e] = t, this; 12209 } 12210 /** 12211 * Deletes the attribute for the given name. 12212 * 12213 * @param {string} name - The attribute name to delete. 12214 * @return {BufferGeometry} A reference to this instance. 12215 */ 12216 deleteAttribute(e) { 12217 return delete this.attributes[e], this; 12218 } 12219 /** 12220 * Returns `true` if this geometry has an attribute for the given name. 12221 * 12222 * @param {string} name - The attribute name. 12223 * @return {boolean} Whether this geometry has an attribute for the given name or not. 12224 */ 12225 hasAttribute(e) { 12226 return this.attributes[e] !== void 0; 12227 } 12228 /** 12229 * Adds a group to this geometry. 12230 * 12231 * @param {number} start - The first element in this draw call. That is the first 12232 * vertex for non-indexed geometry, otherwise the first triangle index. 12233 * @param {number} count - Specifies how many vertices (or indices) are part of this group. 12234 * @param {number} [materialIndex=0] - The material array index to use. 12235 */ 12236 addGroup(e, t, i = 0) { 12237 this.groups.push({ 12238 start: e, 12239 count: t, 12240 materialIndex: i 12241 }); 12242 } 12243 /** 12244 * Clears all groups. 12245 */ 12246 clearGroups() { 12247 this.groups = []; 12248 } 12249 /** 12250 * Sets the draw range for this geometry. 12251 * 12252 * @param {number} start - The first vertex for non-indexed geometry, otherwise the first triangle index. 12253 * @param {number} count - For non-indexed BufferGeometry, `count` is the number of vertices to render. 12254 * For indexed BufferGeometry, `count` is the number of indices to render. 12255 */ 12256 setDrawRange(e, t) { 12257 this.drawRange.start = e, this.drawRange.count = t; 12258 } 12259 /** 12260 * Applies the given 4x4 transformation matrix to the geometry. 12261 * 12262 * @param {Matrix4} matrix - The matrix to apply. 12263 * @return {BufferGeometry} A reference to this instance. 12264 */ 12265 applyMatrix4(e) { 12266 const t = this.attributes.position; 12267 t !== void 0 && (t.applyMatrix4(e), t.needsUpdate = !0); 12268 const i = this.attributes.normal; 12269 if (i !== void 0) { 12270 const s = new ot().getNormalMatrix(e); 12271 i.applyNormalMatrix(s), i.needsUpdate = !0; 12272 } 12273 const r = this.attributes.tangent; 12274 return r !== void 0 && (r.transformDirection(e), r.needsUpdate = !0), this.boundingBox !== null && this.computeBoundingBox(), this.boundingSphere !== null && this.computeBoundingSphere(), this; 12275 } 12276 /** 12277 * Applies the rotation represented by the Quaternion to the geometry. 12278 * 12279 * @param {Quaternion} q - The Quaternion to apply. 12280 * @return {BufferGeometry} A reference to this instance. 12281 */ 12282 applyQuaternion(e) { 12283 return kn.makeRotationFromQuaternion(e), this.applyMatrix4(kn), this; 12284 } 12285 /** 12286 * Rotates the geometry about the X axis. This is typically done as a one time 12287 * operation, and not during a loop. Use {@link Object3D#rotation} for typical 12288 * real-time mesh rotation. 12289 * 12290 * @param {number} angle - The angle in radians. 12291 * @return {BufferGeometry} A reference to this instance. 12292 */ 12293 rotateX(e) { 12294 return kn.makeRotationX(e), this.applyMatrix4(kn), this; 12295 } 12296 /** 12297 * Rotates the geometry about the Y axis. This is typically done as a one time 12298 * operation, and not during a loop. Use {@link Object3D#rotation} for typical 12299 * real-time mesh rotation. 12300 * 12301 * @param {number} angle - The angle in radians. 12302 * @return {BufferGeometry} A reference to this instance. 12303 */ 12304 rotateY(e) { 12305 return kn.makeRotationY(e), this.applyMatrix4(kn), this; 12306 } 12307 /** 12308 * Rotates the geometry about the Z axis. This is typically done as a one time 12309 * operation, and not during a loop. Use {@link Object3D#rotation} for typical 12310 * real-time mesh rotation. 12311 * 12312 * @param {number} angle - The angle in radians. 12313 * @return {BufferGeometry} A reference to this instance. 12314 */ 12315 rotateZ(e) { 12316 return kn.makeRotationZ(e), this.applyMatrix4(kn), this; 12317 } 12318 /** 12319 * Translates the geometry. This is typically done as a one time 12320 * operation, and not during a loop. Use {@link Object3D#position} for typical 12321 * real-time mesh rotation. 12322 * 12323 * @param {number} x - The x offset. 12324 * @param {number} y - The y offset. 12325 * @param {number} z - The z offset. 12326 * @return {BufferGeometry} A reference to this instance. 12327 */ 12328 translate(e, t, i) { 12329 return kn.makeTranslation(e, t, i), this.applyMatrix4(kn), this; 12330 } 12331 /** 12332 * Scales the geometry. This is typically done as a one time 12333 * operation, and not during a loop. Use {@link Object3D#scale} for typical 12334 * real-time mesh rotation. 12335 * 12336 * @param {number} x - The x scale. 12337 * @param {number} y - The y scale. 12338 * @param {number} z - The z scale. 12339 * @return {BufferGeometry} A reference to this instance. 12340 */ 12341 scale(e, t, i) { 12342 return kn.makeScale(e, t, i), this.applyMatrix4(kn), this; 12343 } 12344 /** 12345 * Rotates the geometry to face a point in 3D space. This is typically done as a one time 12346 * operation, and not during a loop. Use {@link Object3D#lookAt} for typical 12347 * real-time mesh rotation. 12348 * 12349 * @param {Vector3} vector - The target point. 12350 * @return {BufferGeometry} A reference to this instance. 12351 */ 12352 lookAt(e) { 12353 return Ll.lookAt(e), Ll.updateMatrix(), this.applyMatrix4(Ll.matrix), this; 12354 } 12355 /** 12356 * Center the geometry based on its bounding box. 12357 * 12358 * @return {BufferGeometry} A reference to this instance. 12359 */ 12360 center() { 12361 return this.computeBoundingBox(), this.boundingBox.getCenter(Xr).negate(), this.translate(Xr.x, Xr.y, Xr.z), this; 12362 } 12363 /** 12364 * Defines a geometry by creating a `position` attribute based on the given array of points. The array 12365 * can hold 2D or 3D vectors. When using two-dimensional data, the `z` coordinate for all vertices is 12366 * set to `0`. 12367 * 12368 * If the method is used with an existing `position` attribute, the vertex data are overwritten with the 12369 * data from the array. The length of the array must match the vertex count. 12370 * 12371 * @param {Array<Vector2>|Array<Vector3>} points - The points. 12372 * @return {BufferGeometry} A reference to this instance. 12373 */ 12374 setFromPoints(e) { 12375 const t = this.getAttribute("position"); 12376 if (t === void 0) { 12377 const i = []; 12378 for (let r = 0, s = e.length; r < s; r++) { 12379 const a = e[r]; 12380 i.push(a.x, a.y, a.z || 0); 12381 } 12382 this.setAttribute("position", new vn(i, 3)); 12383 } else { 12384 const i = Math.min(e.length, t.count); 12385 for (let r = 0; r < i; r++) { 12386 const s = e[r]; 12387 t.setXYZ(r, s.x, s.y, s.z || 0); 12388 } 12389 e.length > t.count && tt("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."), t.needsUpdate = !0; 12390 } 12391 return this; 12392 } 12393 /** 12394 * Computes the bounding box of the geometry, and updates the `boundingBox` member. 12395 * The bounding box is not computed by the engine; it must be computed by your app. 12396 * You may need to recompute the bounding box if the geometry vertices are modified. 12397 */ 12398 computeBoundingBox() { 12399 this.boundingBox === null && (this.boundingBox = new Dr()); 12400 const e = this.attributes.position, t = this.morphAttributes.position; 12401 if (e && e.isGLBufferAttribute) { 12402 xt("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.", this), this.boundingBox.set( 12403 new W(-1 / 0, -1 / 0, -1 / 0), 12404 new W(1 / 0, 1 / 0, 1 / 0) 12405 ); 12406 return; 12407 } 12408 if (e !== void 0) { 12409 if (this.boundingBox.setFromBufferAttribute(e), t) 12410 for (let i = 0, r = t.length; i < r; i++) { 12411 const s = t[i]; 12412 Rn.setFromBufferAttribute(s), this.morphTargetsRelative ? (tn.addVectors(this.boundingBox.min, Rn.min), this.boundingBox.expandByPoint(tn), tn.addVectors(this.boundingBox.max, Rn.max), this.boundingBox.expandByPoint(tn)) : (this.boundingBox.expandByPoint(Rn.min), this.boundingBox.expandByPoint(Rn.max)); 12413 } 12414 } else 12415 this.boundingBox.makeEmpty(); 12416 (isNaN(this.boundingBox.min.x) || isNaN(this.boundingBox.min.y) || isNaN(this.boundingBox.min.z)) && xt('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.', this); 12417 } 12418 /** 12419 * Computes the bounding sphere of the geometry, and updates the `boundingSphere` member. 12420 * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling. 12421 * You may need to recompute the bounding sphere if the geometry vertices are modified. 12422 */ 12423 computeBoundingSphere() { 12424 this.boundingSphere === null && (this.boundingSphere = new Ss()); 12425 const e = this.attributes.position, t = this.morphAttributes.position; 12426 if (e && e.isGLBufferAttribute) { 12427 xt("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.", this), this.boundingSphere.set(new W(), 1 / 0); 12428 return; 12429 } 12430 if (e) { 12431 const i = this.boundingSphere.center; 12432 if (Rn.setFromBufferAttribute(e), t) 12433 for (let s = 0, a = t.length; s < a; s++) { 12434 const l = t[s]; 12435 ks.setFromBufferAttribute(l), this.morphTargetsRelative ? (tn.addVectors(Rn.min, ks.min), Rn.expandByPoint(tn), tn.addVectors(Rn.max, ks.max), Rn.expandByPoint(tn)) : (Rn.expandByPoint(ks.min), Rn.expandByPoint(ks.max)); 12436 } 12437 Rn.getCenter(i); 12438 let r = 0; 12439 for (let s = 0, a = e.count; s < a; s++) 12440 tn.fromBufferAttribute(e, s), r = Math.max(r, i.distanceToSquared(tn)); 12441 if (t) 12442 for (let s = 0, a = t.length; s < a; s++) { 12443 const l = t[s], o = this.morphTargetsRelative; 12444 for (let c = 0, u = l.count; c < u; c++) 12445 tn.fromBufferAttribute(l, c), o && (Xr.fromBufferAttribute(e, c), tn.add(Xr)), r = Math.max(r, i.distanceToSquared(tn)); 12446 } 12447 this.boundingSphere.radius = Math.sqrt(r), isNaN(this.boundingSphere.radius) && xt('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.', this); 12448 } 12449 } 12450 /** 12451 * Calculates and adds a tangent attribute to this geometry. 12452 * 12453 * The computation is only supported for indexed geometries and if position, normal, and uv attributes 12454 * are defined. When using a tangent space normal map, prefer the MikkTSpace algorithm provided by 12455 * {@link BufferGeometryUtils#computeMikkTSpaceTangents} instead. 12456 */ 12457 computeTangents() { 12458 const e = this.index, t = this.attributes; 12459 if (e === null || t.position === void 0 || t.normal === void 0 || t.uv === void 0) { 12460 xt("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)"); 12461 return; 12462 } 12463 const i = t.position, r = t.normal, s = t.uv; 12464 this.hasAttribute("tangent") === !1 && this.setAttribute("tangent", new on(new Float32Array(4 * i.count), 4)); 12465 const a = this.getAttribute("tangent"), l = [], o = []; 12466 for (let y = 0; y < i.count; y++) 12467 l[y] = new W(), o[y] = new W(); 12468 const c = new W(), u = new W(), h = new W(), d = new wt(), f = new wt(), p = new wt(), v = new W(), m = new W(); 12469 function g(y, M, L) { 12470 c.fromBufferAttribute(i, y), u.fromBufferAttribute(i, M), h.fromBufferAttribute(i, L), d.fromBufferAttribute(s, y), f.fromBufferAttribute(s, M), p.fromBufferAttribute(s, L), u.sub(c), h.sub(c), f.sub(d), p.sub(d); 12471 const C = 1 / (f.x * p.y - p.x * f.y); 12472 isFinite(C) && (v.copy(u).multiplyScalar(p.y).addScaledVector(h, -f.y).multiplyScalar(C), m.copy(h).multiplyScalar(f.x).addScaledVector(u, -p.x).multiplyScalar(C), l[y].add(v), l[M].add(v), l[L].add(v), o[y].add(m), o[M].add(m), o[L].add(m)); 12473 } 12474 let _ = this.groups; 12475 _.length === 0 && (_ = [{ 12476 start: 0, 12477 count: e.count 12478 }]); 12479 for (let y = 0, M = _.length; y < M; ++y) { 12480 const L = _[y], C = L.start, U = L.count; 12481 for (let V = C, F = C + U; V < F; V += 3) 12482 g( 12483 e.getX(V + 0), 12484 e.getX(V + 1), 12485 e.getX(V + 2) 12486 ); 12487 } 12488 const x = new W(), E = new W(), R = new W(), T = new W(); 12489 function w(y) { 12490 R.fromBufferAttribute(r, y), T.copy(R); 12491 const M = l[y]; 12492 x.copy(M), x.sub(R.multiplyScalar(R.dot(M))).normalize(), E.crossVectors(T, M); 12493 const C = E.dot(o[y]) < 0 ? -1 : 1; 12494 a.setXYZW(y, x.x, x.y, x.z, C); 12495 } 12496 for (let y = 0, M = _.length; y < M; ++y) { 12497 const L = _[y], C = L.start, U = L.count; 12498 for (let V = C, F = C + U; V < F; V += 3) 12499 w(e.getX(V + 0)), w(e.getX(V + 1)), w(e.getX(V + 2)); 12500 } 12501 } 12502 /** 12503 * Computes vertex normals for the given vertex data. For indexed geometries, the method sets 12504 * each vertex normal to be the average of the face normals of the faces that share that vertex. 12505 * For non-indexed geometries, vertices are not shared, and the method sets each vertex normal 12506 * to be the same as the face normal. 12507 */ 12508 computeVertexNormals() { 12509 const e = this.index, t = this.getAttribute("position"); 12510 if (t !== void 0) { 12511 let i = this.getAttribute("normal"); 12512 if (i === void 0) 12513 i = new on(new Float32Array(t.count * 3), 3), this.setAttribute("normal", i); 12514 else 12515 for (let d = 0, f = i.count; d < f; d++) 12516 i.setXYZ(d, 0, 0, 0); 12517 const r = new W(), s = new W(), a = new W(), l = new W(), o = new W(), c = new W(), u = new W(), h = new W(); 12518 if (e) 12519 for (let d = 0, f = e.count; d < f; d += 3) { 12520 const p = e.getX(d + 0), v = e.getX(d + 1), m = e.getX(d + 2); 12521 r.fromBufferAttribute(t, p), s.fromBufferAttribute(t, v), a.fromBufferAttribute(t, m), u.subVectors(a, s), h.subVectors(r, s), u.cross(h), l.fromBufferAttribute(i, p), o.fromBufferAttribute(i, v), c.fromBufferAttribute(i, m), l.add(u), o.add(u), c.add(u), i.setXYZ(p, l.x, l.y, l.z), i.setXYZ(v, o.x, o.y, o.z), i.setXYZ(m, c.x, c.y, c.z); 12522 } 12523 else 12524 for (let d = 0, f = t.count; d < f; d += 3) 12525 r.fromBufferAttribute(t, d + 0), s.fromBufferAttribute(t, d + 1), a.fromBufferAttribute(t, d + 2), u.subVectors(a, s), h.subVectors(r, s), u.cross(h), i.setXYZ(d + 0, u.x, u.y, u.z), i.setXYZ(d + 1, u.x, u.y, u.z), i.setXYZ(d + 2, u.x, u.y, u.z); 12526 this.normalizeNormals(), i.needsUpdate = !0; 12527 } 12528 } 12529 /** 12530 * Ensures every normal vector in a geometry will have a magnitude of `1`. This will 12531 * correct lighting on the geometry surfaces. 12532 */ 12533 normalizeNormals() { 12534 const e = this.attributes.normal; 12535 for (let t = 0, i = e.count; t < i; t++) 12536 tn.fromBufferAttribute(e, t), tn.normalize(), e.setXYZ(t, tn.x, tn.y, tn.z); 12537 } 12538 /** 12539 * Return a new non-index version of this indexed geometry. If the geometry 12540 * is already non-indexed, the method is a NOOP. 12541 * 12542 * @return {BufferGeometry} The non-indexed version of this indexed geometry. 12543 */ 12544 toNonIndexed() { 12545 function e(l, o) { 12546 const c = l.array, u = l.itemSize, h = l.normalized, d = new c.constructor(o.length * u); 12547 let f = 0, p = 0; 12548 for (let v = 0, m = o.length; v < m; v++) { 12549 l.isInterleavedBufferAttribute ? f = o[v] * l.data.stride + l.offset : f = o[v] * u; 12550 for (let g = 0; g < u; g++) 12551 d[p++] = c[f++]; 12552 } 12553 return new on(d, u, h); 12554 } 12555 if (this.index === null) 12556 return tt("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."), this; 12557 const t = new xn(), i = this.index.array, r = this.attributes; 12558 for (const l in r) { 12559 const o = r[l], c = e(o, i); 12560 t.setAttribute(l, c); 12561 } 12562 const s = this.morphAttributes; 12563 for (const l in s) { 12564 const o = [], c = s[l]; 12565 for (let u = 0, h = c.length; u < h; u++) { 12566 const d = c[u], f = e(d, i); 12567 o.push(f); 12568 } 12569 t.morphAttributes[l] = o; 12570 } 12571 t.morphTargetsRelative = this.morphTargetsRelative; 12572 const a = this.groups; 12573 for (let l = 0, o = a.length; l < o; l++) { 12574 const c = a[l]; 12575 t.addGroup(c.start, c.count, c.materialIndex); 12576 } 12577 return t; 12578 } 12579 /** 12580 * Serializes the geometry into JSON. 12581 * 12582 * @return {Object} A JSON object representing the serialized geometry. 12583 */ 12584 toJSON() { 12585 const e = { 12586 metadata: { 12587 version: 4.7, 12588 type: "BufferGeometry", 12589 generator: "BufferGeometry.toJSON" 12590 } 12591 }; 12592 if (e.uuid = this.uuid, e.type = this.type, this.name !== "" && (e.name = this.name), Object.keys(this.userData).length > 0 && (e.userData = this.userData), this.parameters !== void 0) { 12593 const o = this.parameters; 12594 for (const c in o) 12595 o[c] !== void 0 && (e[c] = o[c]); 12596 return e; 12597 } 12598 e.data = { attributes: {} }; 12599 const t = this.index; 12600 t !== null && (e.data.index = { 12601 type: t.array.constructor.name, 12602 array: Array.prototype.slice.call(t.array) 12603 }); 12604 const i = this.attributes; 12605 for (const o in i) { 12606 const c = i[o]; 12607 e.data.attributes[o] = c.toJSON(e.data); 12608 } 12609 const r = {}; 12610 let s = !1; 12611 for (const o in this.morphAttributes) { 12612 const c = this.morphAttributes[o], u = []; 12613 for (let h = 0, d = c.length; h < d; h++) { 12614 const f = c[h]; 12615 u.push(f.toJSON(e.data)); 12616 } 12617 u.length > 0 && (r[o] = u, s = !0); 12618 } 12619 s && (e.data.morphAttributes = r, e.data.morphTargetsRelative = this.morphTargetsRelative); 12620 const a = this.groups; 12621 a.length > 0 && (e.data.groups = JSON.parse(JSON.stringify(a))); 12622 const l = this.boundingSphere; 12623 return l !== null && (e.data.boundingSphere = l.toJSON()), e; 12624 } 12625 /** 12626 * Returns a new geometry with copied values from this instance. 12627 * 12628 * @return {BufferGeometry} A clone of this instance. 12629 */ 12630 clone() { 12631 return new this.constructor().copy(this); 12632 } 12633 /** 12634 * Copies the values of the given geometry to this instance. 12635 * 12636 * @param {BufferGeometry} source - The geometry to copy. 12637 * @return {BufferGeometry} A reference to this instance. 12638 */ 12639 copy(e) { 12640 this.index = null, this.attributes = {}, this.morphAttributes = {}, this.groups = [], this.boundingBox = null, this.boundingSphere = null; 12641 const t = {}; 12642 this.name = e.name; 12643 const i = e.index; 12644 i !== null && this.setIndex(i.clone()); 12645 const r = e.attributes; 12646 for (const c in r) { 12647 const u = r[c]; 12648 this.setAttribute(c, u.clone(t)); 12649 } 12650 const s = e.morphAttributes; 12651 for (const c in s) { 12652 const u = [], h = s[c]; 12653 for (let d = 0, f = h.length; d < f; d++) 12654 u.push(h[d].clone(t)); 12655 this.morphAttributes[c] = u; 12656 } 12657 this.morphTargetsRelative = e.morphTargetsRelative; 12658 const a = e.groups; 12659 for (let c = 0, u = a.length; c < u; c++) { 12660 const h = a[c]; 12661 this.addGroup(h.start, h.count, h.materialIndex); 12662 } 12663 const l = e.boundingBox; 12664 l !== null && (this.boundingBox = l.clone()); 12665 const o = e.boundingSphere; 12666 return o !== null && (this.boundingSphere = o.clone()), this.drawRange.start = e.drawRange.start, this.drawRange.count = e.drawRange.count, this.userData = e.userData, this; 12667 } 12668 /** 12669 * Frees the GPU-related resources allocated by this instance. Call this 12670 * method whenever this instance is no longer used in your app. 12671 * 12672 * @fires BufferGeometry#dispose 12673 */ 12674 dispose() { 12675 this.dispatchEvent({ type: "dispose" }); 12676 } 12677} 12678let V_ = 0; 12679class Es extends Ir { 12680 /** 12681 * Constructs a new material. 12682 */ 12683 constructor() { 12684 super(), this.isMaterial = !0, Object.defineProperty(this, "id", { value: V_++ }), this.uuid = wa(), this.name = "", this.type = "Material", this.blending = hs, this.side = sr, this.vertexColors = !1, this.opacity = 1, this.transparent = !1, this.alphaHash = !1, this.blendSrc = lc, this.blendDst = cc, this.blendEquation = wr, this.blendSrcAlpha = null, this.blendDstAlpha = null, this.blendEquationAlpha = null, this.blendColor = new Et(0, 0, 0), this.blendAlpha = 0, this.depthFunc = ms, this.depthTest = !0, this.depthWrite = !0, this.stencilWriteMask = 255, this.stencilFunc = Vh, this.stencilRef = 0, this.stencilFuncMask = 255, this.stencilFail = kr, this.stencilZFail = kr, this.stencilZPass = kr, this.stencilWrite = !1, this.clippingPlanes = null, this.clipIntersection = !1, this.clipShadows = !1, this.shadowSide = null, this.colorWrite = !0, this.precision = null, this.polygonOffset = !1, this.polygonOffsetFactor = 0, this.polygonOffsetUnits = 0, this.dithering = !1, this.alphaToCoverage = !1, this.premultipliedAlpha = !1, this.forceSinglePass = !1, this.allowOverride = !0, this.visible = !0, this.toneMapped = !0, this.userData = {}, this.version = 0, this._alphaTest = 0; 12685 } 12686 /** 12687 * Sets the alpha value to be used when running an alpha test. The material 12688 * will not be rendered if the opacity is lower than this value. 12689 * 12690 * @type {number} 12691 * @readonly 12692 * @default 0 12693 */ 12694 get alphaTest() { 12695 return this._alphaTest; 12696 } 12697 set alphaTest(e) { 12698 this._alphaTest > 0 != e > 0 && this.version++, this._alphaTest = e; 12699 } 12700 /** 12701 * An optional callback that is executed immediately before the material is used to render a 3D object. 12702 * 12703 * This method can only be used when rendering with {@link WebGLRenderer}. 12704 * 12705 * @param {WebGLRenderer} renderer - The renderer. 12706 * @param {Scene} scene - The scene. 12707 * @param {Camera} camera - The camera that is used to render the scene. 12708 * @param {BufferGeometry} geometry - The 3D object's geometry. 12709 * @param {Object3D} object - The 3D object. 12710 * @param {Object} group - The geometry group data. 12711 */ 12712 onBeforeRender() { 12713 } 12714 /** 12715 * An optional callback that is executed immediately before the shader 12716 * program is compiled. This function is called with the shader source code 12717 * as a parameter. Useful for the modification of built-in materials. 12718 * 12719 * This method can only be used when rendering with {@link WebGLRenderer}. The 12720 * recommended approach when customizing materials is to use `WebGPURenderer` with the new 12721 * Node Material system and [TSL](https://github.com/mrdoob/three.js/wiki/Three.js-Shading-Language). 12722 * 12723 * @param {{vertexShader:string,fragmentShader:string,uniforms:Object}} shaderobject - The object holds the uniforms and the vertex and fragment shader source. 12724 * @param {WebGLRenderer} renderer - A reference to the renderer. 12725 */ 12726 onBeforeCompile() { 12727 } 12728 /** 12729 * In case {@link Material#onBeforeCompile} is used, this callback can be used to identify 12730 * values of settings used in `onBeforeCompile()`, so three.js can reuse a cached 12731 * shader or recompile the shader for this material as needed. 12732 * 12733 * This method can only be used when rendering with {@link WebGLRenderer}. 12734 * 12735 * @return {string} The custom program cache key. 12736 */ 12737 customProgramCacheKey() { 12738 return this.onBeforeCompile.toString(); 12739 } 12740 /** 12741 * This method can be used to set default values from parameter objects. 12742 * It is a generic implementation so it can be used with different types 12743 * of materials. 12744 * 12745 * @param {Object} [values] - The material values to set. 12746 */ 12747 setValues(e) { 12748 if (e !== void 0) 12749 for (const t in e) { 12750 const i = e[t]; 12751 if (i === void 0) { 12752 tt(`Material: parameter '${t}' has value of undefined.`); 12753 continue; 12754 } 12755 const r = this[t]; 12756 if (r === void 0) { 12757 tt(`Material: '${t}' is not a property of THREE.${this.type}.`); 12758 continue; 12759 } 12760 r && r.isColor ? r.set(i) : r && r.isVector3 && i && i.isVector3 ? r.copy(i) : this[t] = i; 12761 } 12762 } 12763 /** 12764 * Serializes the material into JSON. 12765 * 12766 * @param {?(Object|string)} meta - An optional value holding meta information about the serialization. 12767 * @return {Object} A JSON object representing the serialized material. 12768 * @see {@link ObjectLoader#parse} 12769 */ 12770 toJSON(e) { 12771 const t = e === void 0 || typeof e == "string"; 12772 t && (e = { 12773 textures: {}, 12774 images: {} 12775 }); 12776 const i = { 12777 metadata: { 12778 version: 4.7, 12779 type: "Material", 12780 generator: "Material.toJSON" 12781 } 12782 }; 12783 i.uuid = this.uuid, i.type = this.type, this.name !== "" && (i.name = this.name), this.color && this.color.isColor && (i.color = this.color.getHex()), this.roughness !== void 0 && (i.roughness = this.roughness), this.metalness !== void 0 && (i.metalness = this.metalness), this.sheen !== void 0 && (i.sheen = this.sheen), this.sheenColor && this.sheenColor.isColor && (i.sheenColor = this.sheenColor.getHex()), this.sheenRoughness !== void 0 && (i.sheenRoughness = this.sheenRoughness), this.emissive && this.emissive.isColor && (i.emissive = this.emissive.getHex()), this.emissiveIntensity !== void 0 && this.emissiveIntensity !== 1 && (i.emissiveIntensity = this.emissiveIntensity), this.specular && this.specular.isColor && (i.specular = this.specular.getHex()), this.specularIntensity !== void 0 && (i.specularIntensity = this.specularIntensity), this.specularColor && this.specularColor.isColor && (i.specularColor = this.specularColor.getHex()), this.shininess !== void 0 && (i.shininess = this.shininess), this.clearcoat !== void 0 && (i.clearcoat = this.clearcoat), this.clearcoatRoughness !== void 0 && (i.clearcoatRoughness = this.clearcoatRoughness), this.clearcoatMap && this.clearcoatMap.isTexture && (i.clearcoatMap = this.clearcoatMap.toJSON(e).uuid), this.clearcoatRoughnessMap && this.clearcoatRoughnessMap.isTexture && (i.clearcoatRoughnessMap = this.clearcoatRoughnessMap.toJSON(e).uuid), this.clearcoatNormalMap && this.clearcoatNormalMap.isTexture && (i.clearcoatNormalMap = this.clearcoatNormalMap.toJSON(e).uuid, i.clearcoatNormalScale = this.clearcoatNormalScale.toArray()), this.sheenColorMap && this.sheenColorMap.isTexture && (i.sheenColorMap = this.sheenColorMap.toJSON(e).uuid), this.sheenRoughnessMap && this.sheenRoughnessMap.isTexture && (i.sheenRoughnessMap = this.sheenRoughnessMap.toJSON(e).uuid), this.dispersion !== void 0 && (i.dispersion = this.dispersion), this.iridescence !== void 0 && (i.iridescence = this.iridescence), this.iridescenceIOR !== void 0 && (i.iridescenceIOR = this.iridescenceIOR), this.iridescenceThicknessRange !== void 0 && (i.iridescenceThicknessRange = this.iridescenceThicknessRange), this.iridescenceMap && this.iridescenceMap.isTexture && (i.iridescenceMap = this.iridescenceMap.toJSON(e).uuid), this.iridescenceThicknessMap && this.iridescenceThicknessMap.isTexture && (i.iridescenceThicknessMap = this.iridescenceThicknessMap.toJSON(e).uuid), this.anisotropy !== void 0 && (i.anisotropy = this.anisotropy), this.anisotropyRotation !== void 0 && (i.anisotropyRotation = this.anisotropyRotation), this.anisotropyMap && this.anisotropyMap.isTexture && (i.anisotropyMap = this.anisotropyMap.toJSON(e).uuid), this.map && this.map.isTexture && (i.map = this.map.toJSON(e).uuid), this.matcap && this.matcap.isTexture && (i.matcap = this.matcap.toJSON(e).uuid), this.alphaMap && this.alphaMap.isTexture && (i.alphaMap = this.alphaMap.toJSON(e).uuid), this.lightMap && this.lightMap.isTexture && (i.lightMap = this.lightMap.toJSON(e).uuid, i.lightMapIntensity = this.lightMapIntensity), this.aoMap && this.aoMap.isTexture && (i.aoMap = this.aoMap.toJSON(e).uuid, i.aoMapIntensity = this.aoMapIntensity), this.bumpMap && this.bumpMap.isTexture && (i.bumpMap = this.bumpMap.toJSON(e).uuid, i.bumpScale = this.bumpScale), this.normalMap && this.normalMap.isTexture && (i.normalMap = this.normalMap.toJSON(e).uuid, i.normalMapType = this.normalMapType, i.normalScale = this.normalScale.toArray()), this.displacementMap && this.displacementMap.isTexture && (i.displacementMap = this.displacementMap.toJSON(e).uuid, i.displacementScale = this.displacementScale, i.displacementBias = this.displacementBias), this.roughnessMap && this.roughnessMap.isTexture && (i.roughnessMap = this.roughnessMap.toJSON(e).uuid), this.metalnessMap && this.metalnessMap.isTexture && (i.metalnessMap = this.metalnessMap.toJSON(e).uuid), this.emissiveMap && this.emissiveMap.isTexture && (i.emissiveMap = this.emissiveMap.toJSON(e).uuid), this.specularMap && this.specularMap.isTexture && (i.specularMap = this.specularMap.toJSON(e).uuid), this.specularIntensityMap && this.specularIntensityMap.isTexture && (i.specularIntensityMap = this.specularIntensityMap.toJSON(e).uuid), this.specularColorMap && this.specularColorMap.isTexture && (i.specularColorMap = this.specularColorMap.toJSON(e).uuid), this.envMap && this.envMap.isTexture && (i.envMap = this.envMap.toJSON(e).uuid, this.combine !== void 0 && (i.combine = this.combine)), this.envMapRotation !== void 0 && (i.envMapRotation = this.envMapRotation.toArray()), this.envMapIntensity !== void 0 && (i.envMapIntensity = this.envMapIntensity), this.reflectivity !== void 0 && (i.reflectivity = this.reflectivity), this.refractionRatio !== void 0 && (i.refractionRatio = this.refractionRatio), this.gradientMap && this.gradientMap.isTexture && (i.gradientMap = this.gradientMap.toJSON(e).uuid), this.transmission !== void 0 && (i.transmission = this.transmission), this.transmissionMap && this.transmissionMap.isTexture && (i.transmissionMap = this.transmissionMap.toJSON(e).uuid), this.thickness !== void 0 && (i.thickness = this.thickness), this.thicknessMap && this.thicknessMap.isTexture && (i.thicknessMap = this.thicknessMap.toJSON(e).uuid), this.attenuationDistance !== void 0 && this.attenuationDistance !== 1 / 0 && (i.attenuationDistance = this.attenuationDistance), this.attenuationColor !== void 0 && (i.attenuationColor = this.attenuationColor.getHex()), this.size !== void 0 && (i.size = this.size), this.shadowSide !== null && (i.shadowSide = this.shadowSide), this.sizeAttenuation !== void 0 && (i.sizeAttenuation = this.sizeAttenuation), this.blending !== hs && (i.blending = this.blending), this.side !== sr && (i.side = this.side), this.vertexColors === !0 && (i.vertexColors = !0), this.opacity < 1 && (i.opacity = this.opacity), this.transparent === !0 && (i.transparent = !0), this.blendSrc !== lc && (i.blendSrc = this.blendSrc), this.blendDst !== cc && (i.blendDst = this.blendDst), this.blendEquation !== wr && (i.blendEquation = this.blendEquation), this.blendSrcAlpha !== null && (i.blendSrcAlpha = this.blendSrcAlpha), this.blendDstAlpha !== null && (i.blendDstAlpha = this.blendDstAlpha), this.blendEquationAlpha !== null && (i.blendEquationAlpha = this.blendEquationAlpha), this.blendColor && this.blendColor.isColor && (i.blendColor = this.blendColor.getHex()), this.blendAlpha !== 0 && (i.blendAlpha = this.blendAlpha), this.depthFunc !== ms && (i.depthFunc = this.depthFunc), this.depthTest === !1 && (i.depthTest = this.depthTest), this.depthWrite === !1 && (i.depthWrite = this.depthWrite), this.colorWrite === !1 && (i.colorWrite = this.colorWrite), this.stencilWriteMask !== 255 && (i.stencilWriteMask = this.stencilWriteMask), this.stencilFunc !== Vh && (i.stencilFunc = this.stencilFunc), this.stencilRef !== 0 && (i.stencilRef = this.stencilRef), this.stencilFuncMask !== 255 && (i.stencilFuncMask = this.stencilFuncMask), this.stencilFail !== kr && (i.stencilFail = this.stencilFail), this.stencilZFail !== kr && (i.stencilZFail = this.stencilZFail), this.stencilZPass !== kr && (i.stencilZPass = this.stencilZPass), this.stencilWrite === !0 && (i.stencilWrite = this.stencilWrite), this.rotation !== void 0 && this.rotation !== 0 && (i.rotation = this.rotation), this.polygonOffset === !0 && (i.polygonOffset = !0), this.polygonOffsetFactor !== 0 && (i.polygonOffsetFactor = this.polygonOffsetFactor), this.polygonOffsetUnits !== 0 && (i.polygonOffsetUnits = this.polygonOffsetUnits), this.linewidth !== void 0 && this.linewidth !== 1 && (i.linewidth = this.linewidth), this.dashSize !== void 0 && (i.dashSize = this.dashSize), this.gapSize !== void 0 && (i.gapSize = this.gapSize), this.scale !== void 0 && (i.scale = this.scale), this.dithering === !0 && (i.dithering = !0), this.alphaTest > 0 && (i.alphaTest = this.alphaTest), this.alphaHash === !0 && (i.alphaHash = !0), this.alphaToCoverage === !0 && (i.alphaToCoverage = !0), this.premultipliedAlpha === !0 && (i.premultipliedAlpha = !0), this.forceSinglePass === !0 && (i.forceSinglePass = !0), this.allowOverride === !1 && (i.allowOverride = !1), this.wireframe === !0 && (i.wireframe = !0), this.wireframeLinewidth > 1 && (i.wireframeLinewidth = this.wireframeLinewidth), this.wireframeLinecap !== "round" && (i.wireframeLinecap = this.wireframeLinecap), this.wireframeLinejoin !== "round" && (i.wireframeLinejoin = this.wireframeLinejoin), this.flatShading === !0 && (i.flatShading = !0), this.visible === !1 && (i.visible = !1), this.toneMapped === !1 && (i.toneMapped = !1), this.fog === !1 && (i.fog = !1), Object.keys(this.userData).length > 0 && (i.userData = this.userData); 12784 function r(s) { 12785 const a = []; 12786 for (const l in s) { 12787 const o = s[l]; 12788 delete o.metadata, a.push(o); 12789 } 12790 return a; 12791 } 12792 if (t) { 12793 const s = r(e.textures), a = r(e.images); 12794 s.length > 0 && (i.textures = s), a.length > 0 && (i.images = a); 12795 } 12796 return i; 12797 } 12798 /** 12799 * Returns a new material with copied values from this instance. 12800 * 12801 * @return {Material} A clone of this instance. 12802 */ 12803 clone() { 12804 return new this.constructor().copy(this); 12805 } 12806 /** 12807 * Copies the values of the given material to this instance. 12808 * 12809 * @param {Material} source - The material to copy. 12810 * @return {Material} A reference to this instance. 12811 */ 12812 copy(e) { 12813 this.name = e.name, this.blending = e.blending, this.side = e.side, this.vertexColors = e.vertexColors, this.opacity = e.opacity, this.transparent = e.transparent, this.blendSrc = e.blendSrc, this.blendDst = e.blendDst, this.blendEquation = e.blendEquation, this.blendSrcAlpha = e.blendSrcAlpha, this.blendDstAlpha = e.blendDstAlpha, this.blendEquationAlpha = e.blendEquationAlpha, this.blendColor.copy(e.blendColor), this.blendAlpha = e.blendAlpha, this.depthFunc = e.depthFunc, this.depthTest = e.depthTest, this.depthWrite = e.depthWrite, this.stencilWriteMask = e.stencilWriteMask, this.stencilFunc = e.stencilFunc, this.stencilRef = e.stencilRef, this.stencilFuncMask = e.stencilFuncMask, this.stencilFail = e.stencilFail, this.stencilZFail = e.stencilZFail, this.stencilZPass = e.stencilZPass, this.stencilWrite = e.stencilWrite; 12814 const t = e.clippingPlanes; 12815 let i = null; 12816 if (t !== null) { 12817 const r = t.length; 12818 i = new Array(r); 12819 for (let s = 0; s !== r; ++s) 12820 i[s] = t[s].clone(); 12821 } 12822 return this.clippingPlanes = i, this.clipIntersection = e.clipIntersection, this.clipShadows = e.clipShadows, this.shadowSide = e.shadowSide, this.colorWrite = e.colorWrite, this.precision = e.precision, this.polygonOffset = e.polygonOffset, this.polygonOffsetFactor = e.polygonOffsetFactor, this.polygonOffsetUnits = e.polygonOffsetUnits, this.dithering = e.dithering, this.alphaTest = e.alphaTest, this.alphaHash = e.alphaHash, this.alphaToCoverage = e.alphaToCoverage, this.premultipliedAlpha = e.premultipliedAlpha, this.forceSinglePass = e.forceSinglePass, this.allowOverride = e.allowOverride, this.visible = e.visible, this.toneMapped = e.toneMapped, this.userData = JSON.parse(JSON.stringify(e.userData)), this; 12823 } 12824 /** 12825 * Frees the GPU-related resources allocated by this instance. Call this 12826 * method whenever this instance is no longer used in your app. 12827 * 12828 * @fires Material#dispose 12829 */ 12830 dispose() { 12831 this.dispatchEvent({ type: "dispose" }); 12832 } 12833 /** 12834 * Setting this property to `true` indicates the engine the material 12835 * needs to be recompiled. 12836 * 12837 * @type {boolean} 12838 * @default false 12839 * @param {boolean} value 12840 */ 12841 set needsUpdate(e) { 12842 e === !0 && this.version++; 12843 } 12844} 12845const Ti = /* @__PURE__ */ new W(), Nl = /* @__PURE__ */ new W(), za = /* @__PURE__ */ new W(), ji = /* @__PURE__ */ new W(), Il = /* @__PURE__ */ new W(), Ha = /* @__PURE__ */ new W(), Dl = /* @__PURE__ */ new W(); 12846class Wu { 12847 /** 12848 * Constructs a new ray. 12849 * 12850 * @param {Vector3} [origin=(0,0,0)] - The origin of the ray. 12851 * @param {Vector3} [direction=(0,0,-1)] - The (normalized) direction of the ray. 12852 */ 12853 constructor(e = new W(), t = new W(0, 0, -1)) { 12854 this.origin = e, this.direction = t; 12855 } 12856 /** 12857 * Sets the ray's components by copying the given values. 12858 * 12859 * @param {Vector3} origin - The origin. 12860 * @param {Vector3} direction - The direction. 12861 * @return {Ray} A reference to this ray. 12862 */ 12863 set(e, t) { 12864 return this.origin.copy(e), this.direction.copy(t), this; 12865 } 12866 /** 12867 * Copies the values of the given ray to this instance. 12868 * 12869 * @param {Ray} ray - The ray to copy. 12870 * @return {Ray} A reference to this ray. 12871 */ 12872 copy(e) { 12873 return this.origin.copy(e.origin), this.direction.copy(e.direction), this; 12874 } 12875 /** 12876 * Returns a vector that is located at a given distance along this ray. 12877 * 12878 * @param {number} t - The distance along the ray to retrieve a position for. 12879 * @param {Vector3} target - The target vector that is used to store the method's result. 12880 * @return {Vector3} A position on the ray. 12881 */ 12882 at(e, t) { 12883 return t.copy(this.origin).addScaledVector(this.direction, e); 12884 } 12885 /** 12886 * Adjusts the direction of the ray to point at the given vector in world space. 12887 * 12888 * @param {Vector3} v - The target position. 12889 * @return {Ray} A reference to this ray. 12890 */ 12891 lookAt(e) { 12892 return this.direction.copy(e).sub(this.origin).normalize(), this; 12893 } 12894 /** 12895 * Shift the origin of this ray along its direction by the given distance. 12896 * 12897 * @param {number} t - The distance along the ray to interpolate. 12898 * @return {Ray} A reference to this ray. 12899 */ 12900 recast(e) { 12901 return this.origin.copy(this.at(e, Ti)), this; 12902 } 12903 /** 12904 * Returns the point along this ray that is closest to the given point. 12905 * 12906 * @param {Vector3} point - A point in 3D space to get the closet location on the ray for. 12907 * @param {Vector3} target - The target vector that is used to store the method's result. 12908 * @return {Vector3} The closest point on this ray. 12909 */ 12910 closestPointToPoint(e, t) { 12911 t.subVectors(e, this.origin); 12912 const i = t.dot(this.direction); 12913 return i < 0 ? t.copy(this.origin) : t.copy(this.origin).addScaledVector(this.direction, i); 12914 } 12915 /** 12916 * Returns the distance of the closest approach between this ray and the given point. 12917 * 12918 * @param {Vector3} point - A point in 3D space to compute the distance to. 12919 * @return {number} The distance. 12920 */ 12921 distanceToPoint(e) { 12922 return Math.sqrt(this.distanceSqToPoint(e)); 12923 } 12924 /** 12925 * Returns the squared distance of the closest approach between this ray and the given point. 12926 * 12927 * @param {Vector3} point - A point in 3D space to compute the distance to. 12928 * @return {number} The squared distance. 12929 */ 12930 distanceSqToPoint(e) { 12931 const t = Ti.subVectors(e, this.origin).dot(this.direction); 12932 return t < 0 ? this.origin.distanceToSquared(e) : (Ti.copy(this.origin).addScaledVector(this.direction, t), Ti.distanceToSquared(e)); 12933 } 12934 /** 12935 * Returns the squared distance between this ray and the given line segment. 12936 * 12937 * @param {Vector3} v0 - The start point of the line segment. 12938 * @param {Vector3} v1 - The end point of the line segment. 12939 * @param {Vector3} [optionalPointOnRay] - When provided, it receives the point on this ray that is closest to the segment. 12940 * @param {Vector3} [optionalPointOnSegment] - When provided, it receives the point on the line segment that is closest to this ray. 12941 * @return {number} The squared distance. 12942 */ 12943 distanceSqToSegment(e, t, i, r) { 12944 Nl.copy(e).add(t).multiplyScalar(0.5), za.copy(t).sub(e).normalize(), ji.copy(this.origin).sub(Nl); 12945 const s = e.distanceTo(t) * 0.5, a = -this.direction.dot(za), l = ji.dot(this.direction), o = -ji.dot(za), c = ji.lengthSq(), u = Math.abs(1 - a * a); 12946 let h, d, f, p; 12947 if (u > 0) 12948 if (h = a * o - l, d = a * l - o, p = s * u, h >= 0) 12949 if (d >= -p) 12950 if (d <= p) { 12951 const v = 1 / u; 12952 h *= v, d *= v, f = h * (h + a * d + 2 * l) + d * (a * h + d + 2 * o) + c; 12953 } else 12954 d = s, h = Math.max(0, -(a * d + l)), f = -h * h + d * (d + 2 * o) + c; 12955 else 12956 d = -s, h = Math.max(0, -(a * d + l)), f = -h * h + d * (d + 2 * o) + c; 12957 else 12958 d <= -p ? (h = Math.max(0, -(-a * s + l)), d = h > 0 ? -s : Math.min(Math.max(-s, -o), s), f = -h * h + d * (d + 2 * o) + c) : d <= p ? (h = 0, d = Math.min(Math.max(-s, -o), s), f = d * (d + 2 * o) + c) : (h = Math.max(0, -(a * s + l)), d = h > 0 ? s : Math.min(Math.max(-s, -o), s), f = -h * h + d * (d + 2 * o) + c); 12959 else 12960 d = a > 0 ? -s : s, h = Math.max(0, -(a * d + l)), f = -h * h + d * (d + 2 * o) + c; 12961 return i && i.copy(this.origin).addScaledVector(this.direction, h), r && r.copy(Nl).addScaledVector(za, d), f; 12962 } 12963 /** 12964 * Intersects this ray with the given sphere, returning the intersection 12965 * point or `null` if there is no intersection. 12966 * 12967 * @param {Sphere} sphere - The sphere to intersect. 12968 * @param {Vector3} target - The target vector that is used to store the method's result. 12969 * @return {?Vector3} The intersection point. 12970 */ 12971 intersectSphere(e, t) { 12972 Ti.subVectors(e.center, this.origin); 12973 const i = Ti.dot(this.direction), r = Ti.dot(Ti) - i * i, s = e.radius * e.radius; 12974 if (r > s) return null; 12975 const a = Math.sqrt(s - r), l = i - a, o = i + a; 12976 return o < 0 ? null : l < 0 ? this.at(o, t) : this.at(l, t); 12977 } 12978 /** 12979 * Returns `true` if this ray intersects with the given sphere. 12980 * 12981 * @param {Sphere} sphere - The sphere to intersect. 12982 * @return {boolean} Whether this ray intersects with the given sphere or not. 12983 */ 12984 intersectsSphere(e) { 12985 return e.radius < 0 ? !1 : this.distanceSqToPoint(e.center) <= e.radius * e.radius; 12986 } 12987 /** 12988 * Computes the distance from the ray's origin to the given plane. Returns `null` if the ray 12989 * does not intersect with the plane. 12990 * 12991 * @param {Plane} plane - The plane to compute the distance to. 12992 * @return {?number} Whether this ray intersects with the given sphere or not. 12993 */ 12994 distanceToPlane(e) { 12995 const t = e.normal.dot(this.direction); 12996 if (t === 0) 12997 return e.distanceToPoint(this.origin) === 0 ? 0 : null; 12998 const i = -(this.origin.dot(e.normal) + e.constant) / t; 12999 return i >= 0 ? i : null; 13000 } 13001 /** 13002 * Intersects this ray with the given plane, returning the intersection 13003 * point or `null` if there is no intersection. 13004 * 13005 * @param {Plane} plane - The plane to intersect. 13006 * @param {Vector3} target - The target vector that is used to store the method's result. 13007 * @return {?Vector3} The intersection point. 13008 */ 13009 intersectPlane(e, t) { 13010 const i = this.distanceToPlane(e); 13011 return i === null ? null : this.at(i, t); 13012 } 13013 /** 13014 * Returns `true` if this ray intersects with the given plane. 13015 * 13016 * @param {Plane} plane - The plane to intersect. 13017 * @return {boolean} Whether this ray intersects with the given plane or not. 13018 */ 13019 intersectsPlane(e) { 13020 const t = e.distanceToPoint(this.origin); 13021 return t === 0 || e.normal.dot(this.direction) * t < 0; 13022 } 13023 /** 13024 * Intersects this ray with the given bounding box, returning the intersection 13025 * point or `null` if there is no intersection. 13026 * 13027 * @param {Box3} box - The box to intersect. 13028 * @param {Vector3} target - The target vector that is used to store the method's result. 13029 * @return {?Vector3} The intersection point. 13030 */ 13031 intersectBox(e, t) { 13032 let i, r, s, a, l, o; 13033 const c = 1 / this.direction.x, u = 1 / this.direction.y, h = 1 / this.direction.z, d = this.origin; 13034 return c >= 0 ? (i = (e.min.x - d.x) * c, r = (e.max.x - d.x) * c) : (i = (e.max.x - d.x) * c, r = (e.min.x - d.x) * c), u >= 0 ? (s = (e.min.y - d.y) * u, a = (e.max.y - d.y) * u) : (s = (e.max.y - d.y) * u, a = (e.min.y - d.y) * u), i > a || s > r || ((s > i || isNaN(i)) && (i = s), (a < r || isNaN(r)) && (r = a), h >= 0 ? (l = (e.min.z - d.z) * h, o = (e.max.z - d.z) * h) : (l = (e.max.z - d.z) * h, o = (e.min.z - d.z) * h), i > o || l > r) || ((l > i || i !== i) && (i = l), (o < r || r !== r) && (r = o), r < 0) ? null : this.at(i >= 0 ? i : r, t); 13035 } 13036 /** 13037 * Returns `true` if this ray intersects with the given box. 13038 * 13039 * @param {Box3} box - The box to intersect. 13040 * @return {boolean} Whether this ray intersects with the given box or not. 13041 */ 13042 intersectsBox(e) { 13043 return this.intersectBox(e, Ti) !== null; 13044 } 13045 /** 13046 * Intersects this ray with the given triangle, returning the intersection 13047 * point or `null` if there is no intersection. 13048 * 13049 * @param {Vector3} a - The first vertex of the triangle. 13050 * @param {Vector3} b - The second vertex of the triangle. 13051 * @param {Vector3} c - The third vertex of the triangle. 13052 * @param {boolean} backfaceCulling - Whether to use backface culling or not. 13053 * @param {Vector3} target - The target vector that is used to store the method's result. 13054 * @return {?Vector3} The intersection point. 13055 */ 13056 intersectTriangle(e, t, i, r, s) { 13057 Il.subVectors(t, e), Ha.subVectors(i, e), Dl.crossVectors(Il, Ha); 13058 let a = this.direction.dot(Dl), l; 13059 if (a > 0) { 13060 if (r) return null; 13061 l = 1; 13062 } else if (a < 0) 13063 l = -1, a = -a; 13064 else 13065 return null; 13066 ji.subVectors(this.origin, e); 13067 const o = l * this.direction.dot(Ha.crossVectors(ji, Ha)); 13068 if (o < 0) 13069 return null; 13070 const c = l * this.direction.dot(Il.cross(ji)); 13071 if (c < 0 || o + c > a) 13072 return null; 13073 const u = -l * ji.dot(Dl); 13074 return u < 0 ? null : this.at(u / a, s); 13075 } 13076 /** 13077 * Transforms this ray with the given 4x4 transformation matrix. 13078 * 13079 * @param {Matrix4} matrix4 - The transformation matrix. 13080 * @return {Ray} A reference to this ray. 13081 */ 13082 applyMatrix4(e) { 13083 return this.origin.applyMatrix4(e), this.direction.transformDirection(e), this; 13084 } 13085 /** 13086 * Returns `true` if this ray is equal with the given one. 13087 * 13088 * @param {Ray} ray - The ray to test for equality. 13089 * @return {boolean} Whether this ray is equal with the given one. 13090 */ 13091 equals(e) { 13092 return e.origin.equals(this.origin) && e.direction.equals(this.direction); 13093 } 13094 /** 13095 * Returns a new ray with copied values from this instance. 13096 * 13097 * @return {Ray} A clone of this instance. 13098 */ 13099 clone() { 13100 return new this.constructor().copy(this); 13101 } 13102} 13103class zp extends Es { 13104 /** 13105 * Constructs a new mesh basic material. 13106 * 13107 * @param {Object} [parameters] - An object with one or more properties 13108 * defining the material's appearance. Any property of the material 13109 * (including any property from inherited materials) can be passed 13110 * in here. Color values can be passed any type of value accepted 13111 * by {@link Color#set}. 13112 */ 13113 constructor(e) { 13114 super(), this.isMeshBasicMaterial = !0, this.type = "MeshBasicMaterial", this.color = new Et(16777215), this.map = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.specularMap = null, this.alphaMap = null, this.envMap = null, this.envMapRotation = new ar(), this.combine = Nu, this.reflectivity = 1, this.refractionRatio = 0.98, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.fog = !0, this.setValues(e); 13115 } 13116 copy(e) { 13117 return super.copy(e), this.color.copy(e.color), this.map = e.map, this.lightMap = e.lightMap, this.lightMapIntensity = e.lightMapIntensity, this.aoMap = e.aoMap, this.aoMapIntensity = e.aoMapIntensity, this.specularMap = e.specularMap, this.alphaMap = e.alphaMap, this.envMap = e.envMap, this.envMapRotation.copy(e.envMapRotation), this.combine = e.combine, this.reflectivity = e.reflectivity, this.refractionRatio = e.refractionRatio, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.wireframeLinecap = e.wireframeLinecap, this.wireframeLinejoin = e.wireframeLinejoin, this.fog = e.fog, this; 13118 } 13119} 13120const sd = /* @__PURE__ */ new kt(), mr = /* @__PURE__ */ new Wu(), Ga = /* @__PURE__ */ new Ss(), ad = /* @__PURE__ */ new W(), Va = /* @__PURE__ */ new W(), Wa = /* @__PURE__ */ new W(), $a = /* @__PURE__ */ new W(), Ul = /* @__PURE__ */ new W(), ja = /* @__PURE__ */ new W(), od = /* @__PURE__ */ new W(), Xa = /* @__PURE__ */ new W(); 13121class _n extends Zt { 13122 /** 13123 * Constructs a new mesh. 13124 * 13125 * @param {BufferGeometry} [geometry] - The mesh geometry. 13126 * @param {Material|Array<Material>} [material] - The mesh material. 13127 */ 13128 constructor(e = new xn(), t = new zp()) { 13129 super(), this.isMesh = !0, this.type = "Mesh", this.geometry = e, this.material = t, this.morphTargetDictionary = void 0, this.morphTargetInfluences = void 0, this.count = 1, this.updateMorphTargets(); 13130 } 13131 copy(e, t) { 13132 return super.copy(e, t), e.morphTargetInfluences !== void 0 && (this.morphTargetInfluences = e.morphTargetInfluences.slice()), e.morphTargetDictionary !== void 0 && (this.morphTargetDictionary = Object.assign({}, e.morphTargetDictionary)), this.material = Array.isArray(e.material) ? e.material.slice() : e.material, this.geometry = e.geometry, this; 13133 } 13134 /** 13135 * Sets the values of {@link Mesh#morphTargetDictionary} and {@link Mesh#morphTargetInfluences} 13136 * to make sure existing morph targets can influence this 3D object. 13137 */ 13138 updateMorphTargets() { 13139 const t = this.geometry.morphAttributes, i = Object.keys(t); 13140 if (i.length > 0) { 13141 const r = t[i[0]]; 13142 if (r !== void 0) { 13143 this.morphTargetInfluences = [], this.morphTargetDictionary = {}; 13144 for (let s = 0, a = r.length; s < a; s++) { 13145 const l = r[s].name || String(s); 13146 this.morphTargetInfluences.push(0), this.morphTargetDictionary[l] = s; 13147 } 13148 } 13149 } 13150 } 13151 /** 13152 * Returns the local-space position of the vertex at the given index, taking into 13153 * account the current animation state of both morph targets and skinning. 13154 * 13155 * @param {number} index - The vertex index. 13156 * @param {Vector3} target - The target object that is used to store the method's result. 13157 * @return {Vector3} The vertex position in local space. 13158 */ 13159 getVertexPosition(e, t) { 13160 const i = this.geometry, r = i.attributes.position, s = i.morphAttributes.position, a = i.morphTargetsRelative; 13161 t.fromBufferAttribute(r, e); 13162 const l = this.morphTargetInfluences; 13163 if (s && l) { 13164 ja.set(0, 0, 0); 13165 for (let o = 0, c = s.length; o < c; o++) { 13166 const u = l[o], h = s[o]; 13167 u !== 0 && (Ul.fromBufferAttribute(h, e), a ? ja.addScaledVector(Ul, u) : ja.addScaledVector(Ul.sub(t), u)); 13168 } 13169 t.add(ja); 13170 } 13171 return t; 13172 } 13173 /** 13174 * Computes intersection points between a casted ray and this line. 13175 * 13176 * @param {Raycaster} raycaster - The raycaster. 13177 * @param {Array<Object>} intersects - The target array that holds the intersection points. 13178 */ 13179 raycast(e, t) { 13180 const i = this.geometry, r = this.material, s = this.matrixWorld; 13181 r !== void 0 && (i.boundingSphere === null && i.computeBoundingSphere(), Ga.copy(i.boundingSphere), Ga.applyMatrix4(s), mr.copy(e.ray).recast(e.near), !(Ga.containsPoint(mr.origin) === !1 && (mr.intersectSphere(Ga, ad) === null || mr.origin.distanceToSquared(ad) > (e.far - e.near) ** 2)) && (sd.copy(s).invert(), mr.copy(e.ray).applyMatrix4(sd), !(i.boundingBox !== null && mr.intersectsBox(i.boundingBox) === !1) && this._computeIntersections(e, t, mr))); 13182 } 13183 _computeIntersections(e, t, i) { 13184 let r; 13185 const s = this.geometry, a = this.material, l = s.index, o = s.attributes.position, c = s.attributes.uv, u = s.attributes.uv1, h = s.attributes.normal, d = s.groups, f = s.drawRange; 13186 if (l !== null) 13187 if (Array.isArray(a)) 13188 for (let p = 0, v = d.length; p < v; p++) { 13189 const m = d[p], g = a[m.materialIndex], _ = Math.max(m.start, f.start), x = Math.min(l.count, Math.min(m.start + m.count, f.start + f.count)); 13190 for (let E = _, R = x; E < R; E += 3) { 13191 const T = l.getX(E), w = l.getX(E + 1), y = l.getX(E + 2); 13192 r = qa(this, g, e, i, c, u, h, T, w, y), r && (r.faceIndex = Math.floor(E / 3), r.face.materialIndex = m.materialIndex, t.push(r)); 13193 } 13194 } 13195 else { 13196 const p = Math.max(0, f.start), v = Math.min(l.count, f.start + f.count); 13197 for (let m = p, g = v; m < g; m += 3) { 13198 const _ = l.getX(m), x = l.getX(m + 1), E = l.getX(m + 2); 13199 r = qa(this, a, e, i, c, u, h, _, x, E), r && (r.faceIndex = Math.floor(m / 3), t.push(r)); 13200 } 13201 } 13202 else if (o !== void 0) 13203 if (Array.isArray(a)) 13204 for (let p = 0, v = d.length; p < v; p++) { 13205 const m = d[p], g = a[m.materialIndex], _ = Math.max(m.start, f.start), x = Math.min(o.count, Math.min(m.start + m.count, f.start + f.count)); 13206 for (let E = _, R = x; E < R; E += 3) { 13207 const T = E, w = E + 1, y = E + 2; 13208 r = qa(this, g, e, i, c, u, h, T, w, y), r && (r.faceIndex = Math.floor(E / 3), r.face.materialIndex = m.materialIndex, t.push(r)); 13209 } 13210 } 13211 else { 13212 const p = Math.max(0, f.start), v = Math.min(o.count, f.start + f.count); 13213 for (let m = p, g = v; m < g; m += 3) { 13214 const _ = m, x = m + 1, E = m + 2; 13215 r = qa(this, a, e, i, c, u, h, _, x, E), r && (r.faceIndex = Math.floor(m / 3), t.push(r)); 13216 } 13217 } 13218 } 13219} 13220function W_(n, e, t, i, r, s, a, l) { 13221 let o; 13222 if (e.side === Mn ? o = i.intersectTriangle(a, s, r, !0, l) : o = i.intersectTriangle(r, s, a, e.side === sr, l), o === null) return null; 13223 Xa.copy(l), Xa.applyMatrix4(n.matrixWorld); 13224 const c = t.ray.origin.distanceTo(Xa); 13225 return c < t.near || c > t.far ? null : { 13226 distance: c, 13227 point: Xa.clone(), 13228 object: n 13229 }; 13230} 13231function qa(n, e, t, i, r, s, a, l, o, c) { 13232 n.getVertexPosition(l, Va), n.getVertexPosition(o, Wa), n.getVertexPosition(c, $a); 13233 const u = W_(n, e, t, i, Va, Wa, $a, od); 13234 if (u) { 13235 const h = new W(); 13236 Zn.getBarycoord(od, Va, Wa, $a, h), r && (u.uv = Zn.getInterpolatedAttribute(r, l, o, c, h, new wt())), s && (u.uv1 = Zn.getInterpolatedAttribute(s, l, o, c, h, new wt())), a && (u.normal = Zn.getInterpolatedAttribute(a, l, o, c, h, new W()), u.normal.dot(i.direction) > 0 && u.normal.multiplyScalar(-1)); 13237 const d = { 13238 a: l, 13239 b: o, 13240 c, 13241 normal: new W(), 13242 materialIndex: 0 13243 }; 13244 Zn.getNormal(Va, Wa, $a, d.normal), u.face = d, u.barycoord = h; 13245 } 13246 return u; 13247} 13248class Hp extends gn { 13249 /** 13250 * Constructs a new data texture. 13251 * 13252 * @param {?TypedArray} [data=null] - The buffer data. 13253 * @param {number} [width=1] - The width of the texture. 13254 * @param {number} [height=1] - The height of the texture. 13255 * @param {number} [format=RGBAFormat] - The texture format. 13256 * @param {number} [type=UnsignedByteType] - The texture type. 13257 * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. 13258 * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. 13259 * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. 13260 * @param {number} [magFilter=NearestFilter] - The mag filter value. 13261 * @param {number} [minFilter=NearestFilter] - The min filter value. 13262 * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. 13263 * @param {string} [colorSpace=NoColorSpace] - The color space. 13264 */ 13265 constructor(e = null, t = 1, i = 1, r, s, a, l, o, c = sn, u = sn, h, d) { 13266 super(null, a, l, o, c, u, r, s, h, d), this.isDataTexture = !0, this.image = { data: e, width: t, height: i }, this.generateMipmaps = !1, this.flipY = !1, this.unpackAlignment = 1; 13267 } 13268} 13269class ld extends on { 13270 /** 13271 * Constructs a new instanced buffer attribute. 13272 * 13273 * @param {TypedArray} array - The array holding the attribute data. 13274 * @param {number} itemSize - The item size. 13275 * @param {boolean} [normalized=false] - Whether the data are normalized or not. 13276 * @param {number} [meshPerAttribute=1] - How often a value of this buffer attribute should be repeated. 13277 */ 13278 constructor(e, t, i, r = 1) { 13279 super(e, t, i), this.isInstancedBufferAttribute = !0, this.meshPerAttribute = r; 13280 } 13281 copy(e) { 13282 return super.copy(e), this.meshPerAttribute = e.meshPerAttribute, this; 13283 } 13284 toJSON() { 13285 const e = super.toJSON(); 13286 return e.meshPerAttribute = this.meshPerAttribute, e.isInstancedBufferAttribute = !0, e; 13287 } 13288} 13289const qr = /* @__PURE__ */ new kt(), cd = /* @__PURE__ */ new kt(), Ya = [], ud = /* @__PURE__ */ new Dr(), $_ = /* @__PURE__ */ new kt(), Fs = /* @__PURE__ */ new _n(), Bs = /* @__PURE__ */ new Ss(); 13290class $u extends _n { 13291 /** 13292 * Constructs a new instanced mesh. 13293 * 13294 * @param {BufferGeometry} [geometry] - The mesh geometry. 13295 * @param {Material|Array<Material>} [material] - The mesh material. 13296 * @param {number} count - The number of instances. 13297 */ 13298 constructor(e, t, i) { 13299 super(e, t), this.isInstancedMesh = !0, this.instanceMatrix = new ld(new Float32Array(i * 16), 16), this.previousInstanceMatrix = null, this.instanceColor = null, this.morphTexture = null, this.count = i, this.boundingBox = null, this.boundingSphere = null; 13300 for (let r = 0; r < i; r++) 13301 this.setMatrixAt(r, $_); 13302 } 13303 /** 13304 * Computes the bounding box of the instanced mesh, and updates {@link InstancedMesh#boundingBox}. 13305 * The bounding box is not automatically computed by the engine; this method must be called by your app. 13306 * You may need to recompute the bounding box if an instance is transformed via {@link InstancedMesh#setMatrixAt}. 13307 */ 13308 computeBoundingBox() { 13309 const e = this.geometry, t = this.count; 13310 this.boundingBox === null && (this.boundingBox = new Dr()), e.boundingBox === null && e.computeBoundingBox(), this.boundingBox.makeEmpty(); 13311 for (let i = 0; i < t; i++) 13312 this.getMatrixAt(i, qr), ud.copy(e.boundingBox).applyMatrix4(qr), this.boundingBox.union(ud); 13313 } 13314 /** 13315 * Computes the bounding sphere of the instanced mesh, and updates {@link InstancedMesh#boundingSphere} 13316 * The engine automatically computes the bounding sphere when it is needed, e.g., for ray casting or view frustum culling. 13317 * You may need to recompute the bounding sphere if an instance is transformed via {@link InstancedMesh#setMatrixAt}. 13318 */ 13319 computeBoundingSphere() { 13320 const e = this.geometry, t = this.count; 13321 this.boundingSphere === null && (this.boundingSphere = new Ss()), e.boundingSphere === null && e.computeBoundingSphere(), this.boundingSphere.makeEmpty(); 13322 for (let i = 0; i < t; i++) 13323 this.getMatrixAt(i, qr), Bs.copy(e.boundingSphere).applyMatrix4(qr), this.boundingSphere.union(Bs); 13324 } 13325 copy(e, t) { 13326 return super.copy(e, t), this.instanceMatrix.copy(e.instanceMatrix), e.previousInstanceMatrix !== null && (this.previousInstanceMatrix = e.previousInstanceMatrix.clone()), e.morphTexture !== null && (this.morphTexture = e.morphTexture.clone()), e.instanceColor !== null && (this.instanceColor = e.instanceColor.clone()), this.count = e.count, e.boundingBox !== null && (this.boundingBox = e.boundingBox.clone()), e.boundingSphere !== null && (this.boundingSphere = e.boundingSphere.clone()), this; 13327 } 13328 /** 13329 * Gets the color of the defined instance. 13330 * 13331 * @param {number} index - The instance index. 13332 * @param {Color} color - The target object that is used to store the method's result. 13333 * @return {Color} A reference to the target color. 13334 */ 13335 getColorAt(e, t) { 13336 return this.instanceColor === null ? t.setRGB(1, 1, 1) : t.fromArray(this.instanceColor.array, e * 3); 13337 } 13338 /** 13339 * Gets the local transformation matrix of the defined instance. 13340 * 13341 * @param {number} index - The instance index. 13342 * @param {Matrix4} matrix - The target object that is used to store the method's result. 13343 * @return {Matrix4} A reference to the target matrix. 13344 */ 13345 getMatrixAt(e, t) { 13346 return t.fromArray(this.instanceMatrix.array, e * 16); 13347 } 13348 /** 13349 * Gets the morph target weights of the defined instance. 13350 * 13351 * @param {number} index - The instance index. 13352 * @param {Mesh} object - The target object that is used to store the method's result. 13353 */ 13354 getMorphAt(e, t) { 13355 const i = t.morphTargetInfluences, r = this.morphTexture.source.data.data, s = i.length + 1, a = e * s + 1; 13356 for (let l = 0; l < i.length; l++) 13357 i[l] = r[a + l]; 13358 } 13359 raycast(e, t) { 13360 const i = this.matrixWorld, r = this.count; 13361 if (Fs.geometry = this.geometry, Fs.material = this.material, Fs.material !== void 0 && (this.boundingSphere === null && this.computeBoundingSphere(), Bs.copy(this.boundingSphere), Bs.applyMatrix4(i), e.ray.intersectsSphere(Bs) !== !1)) 13362 for (let s = 0; s < r; s++) { 13363 this.getMatrixAt(s, qr), cd.multiplyMatrices(i, qr), Fs.matrixWorld = cd, Fs.raycast(e, Ya); 13364 for (let a = 0, l = Ya.length; a < l; a++) { 13365 const o = Ya[a]; 13366 o.instanceId = s, o.object = this, t.push(o); 13367 } 13368 Ya.length = 0; 13369 } 13370 } 13371 /** 13372 * Sets the given color to the defined instance. Make sure you set the `needsUpdate` flag of 13373 * {@link InstancedMesh#instanceColor} to `true` after updating all the colors. 13374 * 13375 * @param {number} index - The instance index. 13376 * @param {Color} color - The instance color. 13377 * @return {InstancedMesh} A reference to this instanced mesh. 13378 */ 13379 setColorAt(e, t) { 13380 return this.instanceColor === null && (this.instanceColor = new ld(new Float32Array(this.instanceMatrix.count * 3).fill(1), 3)), t.toArray(this.instanceColor.array, e * 3), this; 13381 } 13382 /** 13383 * Sets the given local transformation matrix to the defined instance. Make sure you set the `needsUpdate` flag of 13384 * {@link InstancedMesh#instanceMatrix} to `true` after updating all the matrices. 13385 * 13386 * @param {number} index - The instance index. 13387 * @param {Matrix4} matrix - The local transformation. 13388 * @return {InstancedMesh} A reference to this instanced mesh. 13389 */ 13390 setMatrixAt(e, t) { 13391 return t.toArray(this.instanceMatrix.array, e * 16), this; 13392 } 13393 /** 13394 * Sets the morph target weights to the defined instance. Make sure you set the `needsUpdate` flag of 13395 * {@link InstancedMesh#morphTexture} to `true` after updating all the influences. 13396 * 13397 * @param {number} index - The instance index. 13398 * @param {Mesh} object - A mesh which `morphTargetInfluences` property containing the morph target weights 13399 * of a single instance. 13400 * @return {InstancedMesh} A reference to this instanced mesh. 13401 */ 13402 setMorphAt(e, t) { 13403 const i = t.morphTargetInfluences, r = i.length + 1; 13404 this.morphTexture === null && (this.morphTexture = new Hp(new Float32Array(r * this.count), r, this.count, Ou, ti)); 13405 const s = this.morphTexture.source.data.data; 13406 let a = 0; 13407 for (let c = 0; c < i.length; c++) 13408 a += i[c]; 13409 const l = this.geometry.morphTargetsRelative ? 1 : 1 - a, o = r * e; 13410 return s[o] = l, s.set(i, o + 1), this; 13411 } 13412 updateMorphTargets() { 13413 } 13414 /** 13415 * Frees the GPU-related resources allocated by this instance. Call this 13416 * method whenever this instance is no longer used in your app. 13417 */ 13418 dispose() { 13419 this.dispatchEvent({ type: "dispose" }), this.morphTexture !== null && (this.morphTexture.dispose(), this.morphTexture = null); 13420 } 13421} 13422const Ol = /* @__PURE__ */ new W(), j_ = /* @__PURE__ */ new W(), X_ = /* @__PURE__ */ new ot(); 13423class xr { 13424 /** 13425 * Constructs a new plane. 13426 * 13427 * @param {Vector3} [normal=(1,0,0)] - A unit length vector defining the normal of the plane. 13428 * @param {number} [constant=0] - The signed distance from the origin to the plane. 13429 */ 13430 constructor(e = new W(1, 0, 0), t = 0) { 13431 this.isPlane = !0, this.normal = e, this.constant = t; 13432 } 13433 /** 13434 * Sets the plane components by copying the given values. 13435 * 13436 * @param {Vector3} normal - The normal. 13437 * @param {number} constant - The constant. 13438 * @return {Plane} A reference to this plane. 13439 */ 13440 set(e, t) { 13441 return this.normal.copy(e), this.constant = t, this; 13442 } 13443 /** 13444 * Sets the plane components by defining `x`, `y`, `z` as the 13445 * plane normal and `w` as the constant. 13446 * 13447 * @param {number} x - The value for the normal's x component. 13448 * @param {number} y - The value for the normal's y component. 13449 * @param {number} z - The value for the normal's z component. 13450 * @param {number} w - The constant value. 13451 * @return {Plane} A reference to this plane. 13452 */ 13453 setComponents(e, t, i, r) { 13454 return this.normal.set(e, t, i), this.constant = r, this; 13455 } 13456 /** 13457 * Sets the plane from the given normal and coplanar point (that is a point 13458 * that lies onto the plane). 13459 * 13460 * @param {Vector3} normal - The normal. 13461 * @param {Vector3} point - A coplanar point. 13462 * @return {Plane} A reference to this plane. 13463 */ 13464 setFromNormalAndCoplanarPoint(e, t) { 13465 return this.normal.copy(e), this.constant = -t.dot(this.normal), this; 13466 } 13467 /** 13468 * Sets the plane from three coplanar points. The winding order is 13469 * assumed to be counter-clockwise, and determines the direction of 13470 * the plane normal. 13471 * 13472 * @param {Vector3} a - The first coplanar point. 13473 * @param {Vector3} b - The second coplanar point. 13474 * @param {Vector3} c - The third coplanar point. 13475 * @return {Plane} A reference to this plane. 13476 */ 13477 setFromCoplanarPoints(e, t, i) { 13478 const r = Ol.subVectors(i, t).cross(j_.subVectors(e, t)).normalize(); 13479 return this.setFromNormalAndCoplanarPoint(r, e), this; 13480 } 13481 /** 13482 * Copies the values of the given plane to this instance. 13483 * 13484 * @param {Plane} plane - The plane to copy. 13485 * @return {Plane} A reference to this plane. 13486 */ 13487 copy(e) { 13488 return this.normal.copy(e.normal), this.constant = e.constant, this; 13489 } 13490 /** 13491 * Normalizes the plane normal and adjusts the constant accordingly. 13492 * 13493 * @return {Plane} A reference to this plane. 13494 */ 13495 normalize() { 13496 const e = 1 / this.normal.length(); 13497 return this.normal.multiplyScalar(e), this.constant *= e, this; 13498 } 13499 /** 13500 * Negates both the plane normal and the constant. 13501 * 13502 * @return {Plane} A reference to this plane. 13503 */ 13504 negate() { 13505 return this.constant *= -1, this.normal.negate(), this; 13506 } 13507 /** 13508 * Returns the signed distance from the given point to this plane. 13509 * 13510 * @param {Vector3} point - The point to compute the distance for. 13511 * @return {number} The signed distance. 13512 */ 13513 distanceToPoint(e) { 13514 return this.normal.dot(e) + this.constant; 13515 } 13516 /** 13517 * Returns the signed distance from the given sphere to this plane. 13518 * 13519 * @param {Sphere} sphere - The sphere to compute the distance for. 13520 * @return {number} The signed distance. 13521 */ 13522 distanceToSphere(e) { 13523 return this.distanceToPoint(e.center) - e.radius; 13524 } 13525 /** 13526 * Projects a the given point onto the plane. 13527 * 13528 * @param {Vector3} point - The point to project. 13529 * @param {Vector3} target - The target vector that is used to store the method's result. 13530 * @return {Vector3} The projected point on the plane. 13531 */ 13532 projectPoint(e, t) { 13533 return t.copy(e).addScaledVector(this.normal, -this.distanceToPoint(e)); 13534 } 13535 /** 13536 * Returns the intersection point of the passed line and the plane. Returns 13537 * `null` if the line does not intersect. Returns the line's starting point if 13538 * the line is coplanar with the plane. 13539 * 13540 * @param {Line3} line - The line to compute the intersection for. 13541 * @param {Vector3} target - The target vector that is used to store the method's result. 13542 * @param {boolean} [clampToLine=true] - Whether to clamp the intersection to the line segment. 13543 * @return {?Vector3} The intersection point. Returns `null` if no intersection is detected. 13544 */ 13545 intersectLine(e, t, i = !0) { 13546 const r = e.delta(Ol), s = this.normal.dot(r); 13547 if (s === 0) 13548 return this.distanceToPoint(e.start) === 0 ? t.copy(e.start) : null; 13549 const a = -(e.start.dot(this.normal) + this.constant) / s; 13550 return i === !0 && (a < 0 || a > 1) ? null : t.copy(e.start).addScaledVector(r, a); 13551 } 13552 /** 13553 * Returns `true` if the given line segment intersects with (passes through) the plane. 13554 * 13555 * @param {Line3} line - The line to test. 13556 * @return {boolean} Whether the given line segment intersects with the plane or not. 13557 */ 13558 intersectsLine(e) { 13559 const t = this.distanceToPoint(e.start), i = this.distanceToPoint(e.end); 13560 return t < 0 && i > 0 || i < 0 && t > 0; 13561 } 13562 /** 13563 * Returns `true` if the given bounding box intersects with the plane. 13564 * 13565 * @param {Box3} box - The bounding box to test. 13566 * @return {boolean} Whether the given bounding box intersects with the plane or not. 13567 */ 13568 intersectsBox(e) { 13569 return e.intersectsPlane(this); 13570 } 13571 /** 13572 * Returns `true` if the given bounding sphere intersects with the plane. 13573 * 13574 * @param {Sphere} sphere - The bounding sphere to test. 13575 * @return {boolean} Whether the given bounding sphere intersects with the plane or not. 13576 */ 13577 intersectsSphere(e) { 13578 return e.intersectsPlane(this); 13579 } 13580 /** 13581 * Returns a coplanar vector to the plane, by calculating the 13582 * projection of the normal at the origin onto the plane. 13583 * 13584 * @param {Vector3} target - The target vector that is used to store the method's result. 13585 * @return {Vector3} The coplanar point. 13586 */ 13587 coplanarPoint(e) { 13588 return e.copy(this.normal).multiplyScalar(-this.constant); 13589 } 13590 /** 13591 * Apply a 4x4 matrix to the plane. The matrix must be an affine, homogeneous transform. 13592 * 13593 * The optional normal matrix can be pre-computed like so: 13594 * ```js 13595 * const optionalNormalMatrix = new THREE.Matrix3().getNormalMatrix( matrix ); 13596 * ``` 13597 * 13598 * @param {Matrix4} matrix - The transformation matrix. 13599 * @param {Matrix4} [optionalNormalMatrix] - A pre-computed normal matrix. 13600 * @return {Plane} A reference to this plane. 13601 */ 13602 applyMatrix4(e, t) { 13603 const i = t || X_.getNormalMatrix(e), r = this.coplanarPoint(Ol).applyMatrix4(e), s = this.normal.applyMatrix3(i).normalize(); 13604 return this.constant = -r.dot(s), this; 13605 } 13606 /** 13607 * Translates the plane by the distance defined by the given offset vector. 13608 * Note that this only affects the plane constant and will not affect the normal vector. 13609 * 13610 * @param {Vector3} offset - The offset vector. 13611 * @return {Plane} A reference to this plane. 13612 */ 13613 translate(e) { 13614 return this.constant -= e.dot(this.normal), this; 13615 } 13616 /** 13617 * Returns `true` if this plane is equal with the given one. 13618 * 13619 * @param {Plane} plane - The plane to test for equality. 13620 * @return {boolean} Whether this plane is equal with the given one. 13621 */ 13622 equals(e) { 13623 return e.normal.equals(this.normal) && e.constant === this.constant; 13624 } 13625 /** 13626 * Returns a new plane with copied values from this instance. 13627 * 13628 * @return {Plane} A clone of this instance. 13629 */ 13630 clone() { 13631 return new this.constructor().copy(this); 13632 } 13633} 13634const gr = /* @__PURE__ */ new Ss(), q_ = /* @__PURE__ */ new wt(0.5, 0.5), Ka = /* @__PURE__ */ new W(); 13635class ju { 13636 /** 13637 * Constructs a new frustum. 13638 * 13639 * @param {Plane} [p0] - The first plane that encloses the frustum. 13640 * @param {Plane} [p1] - The second plane that encloses the frustum. 13641 * @param {Plane} [p2] - The third plane that encloses the frustum. 13642 * @param {Plane} [p3] - The fourth plane that encloses the frustum. 13643 * @param {Plane} [p4] - The fifth plane that encloses the frustum. 13644 * @param {Plane} [p5] - The sixth plane that encloses the frustum. 13645 */ 13646 constructor(e = new xr(), t = new xr(), i = new xr(), r = new xr(), s = new xr(), a = new xr()) { 13647 this.planes = [e, t, i, r, s, a]; 13648 } 13649 /** 13650 * Sets the frustum planes by copying the given planes. 13651 * 13652 * @param {Plane} [p0] - The first plane that encloses the frustum. 13653 * @param {Plane} [p1] - The second plane that encloses the frustum. 13654 * @param {Plane} [p2] - The third plane that encloses the frustum. 13655 * @param {Plane} [p3] - The fourth plane that encloses the frustum. 13656 * @param {Plane} [p4] - The fifth plane that encloses the frustum. 13657 * @param {Plane} [p5] - The sixth plane that encloses the frustum. 13658 * @return {Frustum} A reference to this frustum. 13659 */ 13660 set(e, t, i, r, s, a) { 13661 const l = this.planes; 13662 return l[0].copy(e), l[1].copy(t), l[2].copy(i), l[3].copy(r), l[4].copy(s), l[5].copy(a), this; 13663 } 13664 /** 13665 * Copies the values of the given frustum to this instance. 13666 * 13667 * @param {Frustum} frustum - The frustum to copy. 13668 * @return {Frustum} A reference to this frustum. 13669 */ 13670 copy(e) { 13671 const t = this.planes; 13672 for (let i = 0; i < 6; i++) 13673 t[i].copy(e.planes[i]); 13674 return this; 13675 } 13676 /** 13677 * Sets the frustum planes from the given projection matrix. 13678 * 13679 * @param {Matrix4} m - The projection matrix. 13680 * @param {(WebGLCoordinateSystem|WebGPUCoordinateSystem)} coordinateSystem - The coordinate system. 13681 * @param {boolean} [reversedDepth=false] - Whether to use a reversed depth. 13682 * @return {Frustum} A reference to this frustum. 13683 */ 13684 setFromProjectionMatrix(e, t = ui, i = !1) { 13685 const r = this.planes, s = e.elements, a = s[0], l = s[1], o = s[2], c = s[3], u = s[4], h = s[5], d = s[6], f = s[7], p = s[8], v = s[9], m = s[10], g = s[11], _ = s[12], x = s[13], E = s[14], R = s[15]; 13686 if (r[0].setComponents(c - a, f - u, g - p, R - _).normalize(), r[1].setComponents(c + a, f + u, g + p, R + _).normalize(), r[2].setComponents(c + l, f + h, g + v, R + x).normalize(), r[3].setComponents(c - l, f - h, g - v, R - x).normalize(), i) 13687 r[4].setComponents(o, d, m, E).normalize(), r[5].setComponents(c - o, f - d, g - m, R - E).normalize(); 13688 else if (r[4].setComponents(c - o, f - d, g - m, R - E).normalize(), t === ui) 13689 r[5].setComponents(c + o, f + d, g + m, R + E).normalize(); 13690 else if (t === la) 13691 r[5].setComponents(o, d, m, E).normalize(); 13692 else 13693 throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: " + t); 13694 return this; 13695 } 13696 /** 13697 * Returns `true` if the 3D object's bounding sphere is intersecting this frustum. 13698 * 13699 * Note that the 3D object must have a geometry so that the bounding sphere can be calculated. 13700 * 13701 * @param {Object3D} object - The 3D object to test. 13702 * @return {boolean} Whether the 3D object's bounding sphere is intersecting this frustum or not. 13703 */ 13704 intersectsObject(e) { 13705 if (e.boundingSphere !== void 0) 13706 e.boundingSphere === null && e.computeBoundingSphere(), gr.copy(e.boundingSphere).applyMatrix4(e.matrixWorld); 13707 else { 13708 const t = e.geometry; 13709 t.boundingSphere === null && t.computeBoundingSphere(), gr.copy(t.boundingSphere).applyMatrix4(e.matrixWorld); 13710 } 13711 return this.intersectsSphere(gr); 13712 } 13713 /** 13714 * Returns `true` if the given sprite is intersecting this frustum. 13715 * 13716 * @param {Sprite} sprite - The sprite to test. 13717 * @return {boolean} Whether the sprite is intersecting this frustum or not. 13718 */ 13719 intersectsSprite(e) { 13720 gr.center.set(0, 0, 0); 13721 const t = q_.distanceTo(e.center); 13722 return gr.radius = 0.7071067811865476 + t, gr.applyMatrix4(e.matrixWorld), this.intersectsSphere(gr); 13723 } 13724 /** 13725 * Returns `true` if the given bounding sphere is intersecting this frustum. 13726 * 13727 * @param {Sphere} sphere - The bounding sphere to test. 13728 * @return {boolean} Whether the bounding sphere is intersecting this frustum or not. 13729 */ 13730 intersectsSphere(e) { 13731 const t = this.planes, i = e.center, r = -e.radius; 13732 for (let s = 0; s < 6; s++) 13733 if (t[s].distanceToPoint(i) < r) 13734 return !1; 13735 return !0; 13736 } 13737 /** 13738 * Returns `true` if the given bounding box is intersecting this frustum. 13739 * 13740 * @param {Box3} box - The bounding box to test. 13741 * @return {boolean} Whether the bounding box is intersecting this frustum or not. 13742 */ 13743 intersectsBox(e) { 13744 const t = this.planes; 13745 for (let i = 0; i < 6; i++) { 13746 const r = t[i]; 13747 if (Ka.x = r.normal.x > 0 ? e.max.x : e.min.x, Ka.y = r.normal.y > 0 ? e.max.y : e.min.y, Ka.z = r.normal.z > 0 ? e.max.z : e.min.z, r.distanceToPoint(Ka) < 0) 13748 return !1; 13749 } 13750 return !0; 13751 } 13752 /** 13753 * Returns `true` if the given point lies within the frustum. 13754 * 13755 * @param {Vector3} point - The point to test. 13756 * @return {boolean} Whether the point lies within this frustum or not. 13757 */ 13758 containsPoint(e) { 13759 const t = this.planes; 13760 for (let i = 0; i < 6; i++) 13761 if (t[i].distanceToPoint(e) < 0) 13762 return !1; 13763 return !0; 13764 } 13765 /** 13766 * Returns a new frustum with copied values from this instance. 13767 * 13768 * @return {Frustum} A clone of this instance. 13769 */ 13770 clone() { 13771 return new this.constructor().copy(this); 13772 } 13773} 13774class Y_ extends Es { 13775 /** 13776 * Constructs a new points material. 13777 * 13778 * @param {Object} [parameters] - An object with one or more properties 13779 * defining the material's appearance. Any property of the material 13780 * (including any property from inherited materials) can be passed 13781 * in here. Color values can be passed any type of value accepted 13782 * by {@link Color#set}. 13783 */ 13784 constructor(e) { 13785 super(), this.isPointsMaterial = !0, this.type = "PointsMaterial", this.color = new Et(16777215), this.map = null, this.alphaMap = null, this.size = 1, this.sizeAttenuation = !0, this.fog = !0, this.setValues(e); 13786 } 13787 copy(e) { 13788 return super.copy(e), this.color.copy(e.color), this.map = e.map, this.alphaMap = e.alphaMap, this.size = e.size, this.sizeAttenuation = e.sizeAttenuation, this.fog = e.fog, this; 13789 } 13790} 13791const hd = /* @__PURE__ */ new kt(), Zc = /* @__PURE__ */ new Wu(), Ja = /* @__PURE__ */ new Ss(), Za = /* @__PURE__ */ new W(); 13792class K_ extends Zt { 13793 /** 13794 * Constructs a new point cloud. 13795 * 13796 * @param {BufferGeometry} [geometry] - The points geometry. 13797 * @param {Material|Array<Material>} [material] - The points material. 13798 */ 13799 constructor(e = new xn(), t = new Y_()) { 13800 super(), this.isPoints = !0, this.type = "Points", this.geometry = e, this.material = t, this.morphTargetDictionary = void 0, this.morphTargetInfluences = void 0, this.updateMorphTargets(); 13801 } 13802 copy(e, t) { 13803 return super.copy(e, t), this.material = Array.isArray(e.material) ? e.material.slice() : e.material, this.geometry = e.geometry, this; 13804 } 13805 /** 13806 * Computes intersection points between a casted ray and this point cloud. 13807 * 13808 * @param {Raycaster} raycaster - The raycaster. 13809 * @param {Array<Object>} intersects - The target array that holds the intersection points. 13810 */ 13811 raycast(e, t) { 13812 const i = this.geometry, r = this.matrixWorld, s = e.params.Points.threshold, a = i.drawRange; 13813 if (i.boundingSphere === null && i.computeBoundingSphere(), Ja.copy(i.boundingSphere), Ja.applyMatrix4(r), Ja.radius += s, e.ray.intersectsSphere(Ja) === !1) return; 13814 hd.copy(r).invert(), Zc.copy(e.ray).applyMatrix4(hd); 13815 const l = s / ((this.scale.x + this.scale.y + this.scale.z) / 3), o = l * l, c = i.index, h = i.attributes.position; 13816 if (c !== null) { 13817 const d = Math.max(0, a.start), f = Math.min(c.count, a.start + a.count); 13818 for (let p = d, v = f; p < v; p++) { 13819 const m = c.getX(p); 13820 Za.fromBufferAttribute(h, m), dd(Za, m, o, r, e, t, this); 13821 } 13822 } else { 13823 const d = Math.max(0, a.start), f = Math.min(h.count, a.start + a.count); 13824 for (let p = d, v = f; p < v; p++) 13825 Za.fromBufferAttribute(h, p), dd(Za, p, o, r, e, t, this); 13826 } 13827 } 13828 /** 13829 * Sets the values of {@link Points#morphTargetDictionary} and {@link Points#morphTargetInfluences} 13830 * to make sure existing morph targets can influence this 3D object. 13831 */ 13832 updateMorphTargets() { 13833 const t = this.geometry.morphAttributes, i = Object.keys(t); 13834 if (i.length > 0) { 13835 const r = t[i[0]]; 13836 if (r !== void 0) { 13837 this.morphTargetInfluences = [], this.morphTargetDictionary = {}; 13838 for (let s = 0, a = r.length; s < a; s++) { 13839 const l = r[s].name || String(s); 13840 this.morphTargetInfluences.push(0), this.morphTargetDictionary[l] = s; 13841 } 13842 } 13843 } 13844 } 13845} 13846function dd(n, e, t, i, r, s, a) { 13847 const l = Zc.distanceSqToPoint(n); 13848 if (l < t) { 13849 const o = new W(); 13850 Zc.closestPointToPoint(n, o), o.applyMatrix4(i); 13851 const c = r.ray.origin.distanceTo(o); 13852 if (c < r.near || c > r.far) return; 13853 s.push({ 13854 distance: c, 13855 distanceToRay: Math.sqrt(l), 13856 point: o, 13857 index: e, 13858 face: null, 13859 faceIndex: null, 13860 barycoord: null, 13861 object: a 13862 }); 13863 } 13864} 13865class Gp extends gn { 13866 /** 13867 * Constructs a new cube texture. 13868 * 13869 * @param {Array<Image>} [images=[]] - An array holding a image for each side of a cube. 13870 * @param {number} [mapping=CubeReflectionMapping] - The texture mapping. 13871 * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. 13872 * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. 13873 * @param {number} [magFilter=LinearFilter] - The mag filter value. 13874 * @param {number} [minFilter=LinearMipmapLinearFilter] - The min filter value. 13875 * @param {number} [format=RGBAFormat] - The texture format. 13876 * @param {number} [type=UnsignedByteType] - The texture type. 13877 * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. 13878 * @param {string}
13878 [colorSpace=NoColorSpace] - The color space value. 13879 */ 13880 constructor(e = [], t = Cr, i, r, s, a, l, o, c, u) { 13881 super(e, t, i, r, s, a, l, o, c, u), this.isCubeTexture = !0, this.flipY = !1; 13882 } 13883 /** 13884 * Alias for {@link CubeTexture#image}. 13885 * 13886 * @type {Array<Image>} 13887 */ 13888 get images() { 13889 return this.image; 13890 } 13891 set images(e) { 13892 this.image = e; 13893 } 13894} 13895class vs extends gn { 13896 /** 13897 * Constructs a new depth texture. 13898 * 13899 * @param {number} width - The width of the texture. 13900 * @param {number} height - The height of the texture. 13901 * @param {number} [type=UnsignedIntType] - The texture type. 13902 * @param {number} [mapping=Texture.DEFAULT_MAPPING] - The texture mapping. 13903 * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. 13904 * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. 13905 * @param {number} [magFilter=LinearFilter] - The mag filter value. 13906 * @param {number} [minFilter=LinearFilter] - The min filter value. 13907 * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. 13908 * @param {number} [format=DepthFormat] - The texture format. 13909 * @param {number} [depth=1] - The depth of the texture. 13910 */ 13911 constructor(e, t, i = gi, r, s, a, l = sn, o = sn, c, u = Fi, h = 1) { 13912 if (u !== Fi && u !== Tr) 13913 throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat"); 13914 const d = { width: e, height: t, depth: h }; 13915 super(d, r, s, a, l, o, u, i, c), this.isDepthTexture = !0, this.flipY = !1, this.generateMipmaps = !1, this.compareFunction = null; 13916 } 13917 copy(e) { 13918 return super.copy(e), this.source = new Gu(Object.assign({}, e.image)), this.compareFunction = e.compareFunction, this; 13919 } 13920 toJSON(e) { 13921 const t = super.toJSON(e); 13922 return this.compareFunction !== null && (t.compareFunction = this.compareFunction), t; 13923 } 13924} 13925class J_ extends vs { 13926 /** 13927 * Constructs a new cube depth texture. 13928 * 13929 * @param {number} size - The size (width and height) of each cube face. 13930 * @param {number} [type=UnsignedIntType] - The texture type. 13931 * @param {number} [mapping=CubeReflectionMapping] - The texture mapping. 13932 * @param {number} [wrapS=ClampToEdgeWrapping] - The wrapS value. 13933 * @param {number} [wrapT=ClampToEdgeWrapping] - The wrapT value. 13934 * @param {number} [magFilter=NearestFilter] - The mag filter value. 13935 * @param {number} [minFilter=NearestFilter] - The min filter value. 13936 * @param {number} [anisotropy=Texture.DEFAULT_ANISOTROPY] - The anisotropy value. 13937 * @param {number} [format=DepthFormat] - The texture format. 13938 */ 13939 constructor(e, t = gi, i = Cr, r, s, a = sn, l = sn, o, c = Fi) { 13940 const u = { width: e, height: e, depth: 1 }, h = [u, u, u, u, u, u]; 13941 super(e, e, t, i, r, s, a, l, o, c), this.image = h, this.isCubeDepthTexture = !0, this.isCubeTexture = !0; 13942 } 13943 /** 13944 * Alias for {@link CubeDepthTexture#image}. 13945 * 13946 * @type {Array<Image>} 13947 */ 13948 get images() { 13949 return this.image; 13950 } 13951 set images(e) { 13952 this.image = e; 13953 } 13954} 13955class Vp extends gn { 13956 /** 13957 * Creates a new raw texture. 13958 * 13959 * @param {?(WebGLTexture|GPUTexture)} [sourceTexture=null] - The external texture. 13960 */ 13961 constructor(e = null) { 13962 super(), this.sourceTexture = e, this.isExternalTexture = !0; 13963 } 13964 copy(e) { 13965 return super.copy(e), this.sourceTexture = e.sourceTexture, this; 13966 } 13967} 13968class Sa extends xn { 13969 /** 13970 * Constructs a new box geometry. 13971 * 13972 * @param {number} [width=1] - The width. That is, the length of the edges parallel to the X axis. 13973 * @param {number} [height=1] - The height. That is, the length of the edges parallel to the Y axis. 13974 * @param {number} [depth=1] - The depth. That is, the length of the edges parallel to the Z axis. 13975 * @param {number} [widthSegments=1] - Number of segmented rectangular faces along the width of the sides. 13976 * @param {number} [heightSegments=1] - Number of segmented rectangular faces along the height of the sides. 13977 * @param {number} [depthSegments=1] - Number of segmented rectangular faces along the depth of the sides. 13978 */ 13979 constructor(e = 1, t = 1, i = 1, r = 1, s = 1, a = 1) { 13980 super(), this.type = "BoxGeometry", this.parameters = { 13981 width: e, 13982 height: t, 13983 depth: i, 13984 widthSegments: r, 13985 heightSegments: s, 13986 depthSegments: a 13987 }; 13988 const l = this; 13989 r = Math.floor(r), s = Math.floor(s), a = Math.floor(a); 13990 const o = [], c = [], u = [], h = []; 13991 let d = 0, f = 0; 13992 p("z", "y", "x", -1, -1, i, t, e, a, s, 0), p("z", "y", "x", 1, -1, i, t, -e, a, s, 1), p("x", "z", "y", 1, 1, e, i, t, r, a, 2), p("x", "z", "y", 1, -1, e, i, -t, r, a, 3), p("x", "y", "z", 1, -1, e, t, i, r, s, 4), p("x", "y", "z", -1, -1, e, t, -i, r, s, 5), this.setIndex(o), this.setAttribute("position", new vn(c, 3)), this.setAttribute("normal", new vn(u, 3)), this.setAttribute("uv", new vn(h, 2)); 13993 function p(v, m, g, _, x, E, R, T, w, y, M) { 13994 const L = E / w, C = R / y, U = E / 2, V = R / 2, F = T / 2, I = w + 1, k = y + 1; 13995 let H = 0, X = 0; 13996 const K = new W(); 13997 for (let ae = 0; ae < k; ae++) { 13998 const se = ae * C - V; 13999 for (let he = 0; he < I; he++) {
vendor: 4,409 bytes, lines 14000-14102
14000 const Ce = he * L - U; 14001 K[v] = Ce * _, K[m] = se * x, K[g] = F, c.push(K.x, K.y, K.z), K[v] = 0, K[m] = 0, K[g] = T > 0 ? 1 : -1, u.push(K.x, K.y, K.z), h.push(he / w), h.push(1 - ae / y), H += 1; 14002 } 14003 } 14004 for (let ae = 0; ae < y; ae++) 14005 for (let se = 0; se < w; se++) { 14006 const he = d + se + I * ae, Ce = d + se + I * (ae + 1), Ie = d + (se + 1) + I * (ae + 1), Ee = d + (se + 1) + I * ae; 14007 o.push(he, Ce, Ee), o.push(Ce, Ie, Ee), X += 6; 14008 } 14009 l.addGroup(f, X, M), f += X, d += H; 14010 } 14011 } 14012 copy(e) { 14013 return super.copy(e), this.parameters = Object.assign({}, e.parameters), this; 14014 } 14015 /** 14016 * Factory method for creating an instance of this class from the given 14017 * JSON object. 14018 * 14019 * @param {Object} data - A JSON object representing the serialized geometry. 14020 * @return {BoxGeometry} A new instance. 14021 */ 14022 static fromJSON(e) { 14023 return new Sa(e.width, e.height, e.depth, e.widthSegments, e.heightSegments, e.depthSegments); 14024 } 14025} 14026class Ea extends xn { 14027 /** 14028 * Constructs a new cylinder geometry. 14029 * 14030 * @param {number} [radiusTop=1] - Radius of the cylinder at the top. 14031 * @param {number} [radiusBottom=1] - Radius of the cylinder at the bottom. 14032 * @param {number} [height=1] - Height of the cylinder. 14033 * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cylinder. 14034 * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cylinder. 14035 * @param {boolean} [openEnded=false] - Whether the base of the cylinder is open or capped. 14036 * @param {number} [thetaStart=0] - Start angle for first segment, in radians. 14037 * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians. 14038 * The default value results in a complete cylinder. 14039 */ 14040 constructor(e = 1, t = 1, i = 1, r = 32, s = 1, a = !1, l = 0, o = Math.PI * 2) { 14041 super(), this.type = "CylinderGeometry", this.parameters = { 14042 radiusTop: e, 14043 radiusBottom: t, 14044 height: i, 14045 radialSegments: r, 14046 heightSegments: s, 14047 openEnded: a, 14048 thetaStart: l, 14049 thetaLength: o 14050 }; 14051 const c = this; 14052 r = Math.floor(r), s = Math.floor(s); 14053 const u = [], h = [], d = [], f = []; 14054 let p = 0; 14055 const v = [], m = i / 2; 14056 let g = 0; 14057 _(), a === !1 && (e > 0 && x(!0), t > 0 && x(!1)), this.setIndex(u), this.setAttribute("position", new vn(h, 3)), this.setAttribute("normal", new vn(d, 3)), this.setAttribute("uv", new vn(f, 2)); 14058 function _() { 14059 const E = new W(), R = new W(); 14060 let T = 0; 14061 const w = (t - e) / i; 14062 for (let y = 0; y <= s; y++) { 14063 const M = [], L = y / s, C = L * (t - e) + e; 14064 for (let U = 0; U <= r; U++) { 14065 const V = U / r, F = V * o + l, I = Math.sin(F), k = Math.cos(F); 14066 R.x = C * I, R.y = -L * i + m, R.z = C * k, h.push(R.x, R.y, R.z), E.set(I, w, k).normalize(), d.push(E.x, E.y, E.z), f.push(V, 1 - L), M.push(p++); 14067 } 14068 v.push(M); 14069 } 14070 for (let y = 0; y < r; y++) 14071 for (let M = 0; M < s; M++) { 14072 const L = v[M][y], C = v[M + 1][y], U = v[M + 1][y + 1], V = v[M][y + 1]; 14073 (e > 0 || M !== 0) && (u.push(L, C, V), T += 3), (t > 0 || M !== s - 1) && (u.push(C, U, V), T += 3); 14074 } 14075 c.addGroup(g, T, 0), g += T; 14076 } 14077 function x(E) { 14078 const R = p, T = new wt(), w = new W(); 14079 let y = 0; 14080 const M = E === !0 ? e : t, L = E === !0 ? 1 : -1; 14081 for (let U = 1; U <= r; U++) 14082 h.push(0, m * L, 0), d.push(0, L, 0), f.push(0.5, 0.5), p++; 14083 const C = p; 14084 for (let U = 0; U <= r; U++) { 14085 const F = U / r * o + l, I = Math.cos(F), k = Math.sin(F); 14086 w.x = M * k, w.y = m * L, w.z = M * I, h.push(w.x, w.y, w.z), d.push(0, L, 0), T.x = I * 0.5 + 0.5, T.y = k * 0.5 * L + 0.5, f.push(T.x, T.y), p++; 14087 } 14088 for (let U = 0; U < r; U++) { 14089 const V = R + U, F = C + U; 14090 E === !0 ? u.push(F, F + 1, V) : u.push(F + 1, F, V), y += 3; 14091 } 14092 c.addGroup(g, y, E === !0 ? 1 : 2), g += y; 14093 } 14094 } 14095 copy(e) { 14096 return super.copy(e), this.parameters = Object.assign({}, e.parameters), this; 14097 } 14098 /** 14099 * Factory method for creating an instance of this class from the given 14100 * JSON object. 14101 * 14102 * @param {Object} data - A JSON object representing the serialized geometry.
vendor: 4,415 bytes, lines 14103-14211
14103 * @return {CylinderGeometry} A new instance. 14104 */ 14105 static fromJSON(e) { 14106 return new Ea(e.radiusTop, e.radiusBottom, e.height, e.radialSegments, e.heightSegments, e.openEnded, e.thetaStart, e.thetaLength); 14107 } 14108} 14109class Xo extends Ea { 14110 /** 14111 * Constructs a new cone geometry. 14112 * 14113 * @param {number} [radius=1] - Radius of the cone base. 14114 * @param {number} [height=1] - Height of the cone. 14115 * @param {number} [radialSegments=32] - Number of segmented faces around the circumference of the cone. 14116 * @param {number} [heightSegments=1] - Number of rows of faces along the height of the cone. 14117 * @param {boolean} [openEnded=false] - Whether the base of the cone is open or capped. 14118 * @param {number} [thetaStart=0] - Start angle for first segment, in radians. 14119 * @param {number} [thetaLength=Math.PI*2] - The central angle, often called theta, of the circular sector, in radians. 14120 * The default value results in a complete cone. 14121 */ 14122 constructor(e = 1, t = 1, i = 32, r = 1, s = !1, a = 0, l = Math.PI * 2) { 14123 super(0, e, t, i, r, s, a, l), this.type = "ConeGeometry", this.parameters = { 14124 radius: e, 14125 height: t, 14126 radialSegments: i, 14127 heightSegments: r, 14128 openEnded: s, 14129 thetaStart: a, 14130 thetaLength: l 14131 }; 14132 } 14133 /** 14134 * Factory method for creating an instance of this class from the given 14135 * JSON object. 14136 * 14137 * @param {Object} data - A JSON object representing the serialized geometry. 14138 * @return {ConeGeometry} A new instance. 14139 */ 14140 static fromJSON(e) { 14141 return new Xo(e.radius, e.height, e.radialSegments, e.heightSegments, e.openEnded, e.thetaStart, e.thetaLength); 14142 } 14143} 14144class qo extends xn { 14145 /** 14146 * Constructs a new plane geometry. 14147 * 14148 * @param {number} [width=1] - The width along the X axis. 14149 * @param {number} [height=1] - The height along the Y axis 14150 * @param {number} [widthSegments=1] - The number of segments along the X axis. 14151 * @param {number} [heightSegments=1] - The number of segments along the Y axis. 14152 */ 14153 constructor(e = 1, t = 1, i = 1, r = 1) { 14154 super(), this.type = "PlaneGeometry", this.parameters = { 14155 width: e, 14156 height: t, 14157 widthSegments: i, 14158 heightSegments: r 14159 }; 14160 const s = e / 2, a = t / 2, l = Math.floor(i), o = Math.floor(r), c = l + 1, u = o + 1, h = e / l, d = t / o, f = [], p = [], v = [], m = []; 14161 for (let g = 0; g < u; g++) { 14162 const _ = g * d - a; 14163 for (let x = 0; x < c; x++) { 14164 const E = x * h - s; 14165 p.push(E, -_, 0), v.push(0, 0, 1), m.push(x / l), m.push(1 - g / o); 14166 } 14167 } 14168 for (let g = 0; g < o; g++) 14169 for (let _ = 0; _ < l; _++) { 14170 const x = _ + c * g, E = _ + c * (g + 1), R = _ + 1 + c * (g + 1), T = _ + 1 + c * g; 14171 f.push(x, E, T), f.push(E, R, T); 14172 } 14173 this.setIndex(f), this.setAttribute("position", new vn(p, 3)), this.setAttribute("normal", new vn(v, 3)), this.setAttribute("uv", new vn(m, 2)); 14174 } 14175 copy(e) { 14176 return super.copy(e), this.parameters = Object.assign({}, e.parameters), this; 14177 } 14178 /** 14179 * Factory method for creating an instance of this class from the given 14180 * JSON object. 14181 * 14182 * @param {Object} data - A JSON object representing the serialized geometry. 14183 * @return {PlaneGeometry} A new instance. 14184 */ 14185 static fromJSON(e) { 14186 return new qo(e.width, e.height, e.widthSegments, e.heightSegments); 14187 } 14188} 14189class Ms extends xn { 14190 /** 14191 * Constructs a new sphere geometry. 14192 * 14193 * @param {number} [radius=1] - The sphere radius. 14194 * @param {number} [widthSegments=32] - The number of horizontal segments. Minimum value is `3`. 14195 * @param {number} [heightSegments=16] - The number of vertical segments. Minimum value is `2`. 14196 * @param {number} [phiStart=0] - The horizontal starting angle in radians. 14197 * @param {number} [phiLength=Math.PI*2] - The horizontal sweep angle size. 14198 * @param {number} [thetaStart=0] - The vertical starting angle in radians. 14199 * @param {number} [thetaLength=Math.PI] - The vertical sweep angle size. 14200 */ 14201 constructor(e = 1, t = 32, i = 16, r = 0, s = Math.PI * 2, a = 0, l = Math.PI) { 14202 super(), this.type = "SphereGeometry", this.parameters = { 14203 radius: e, 14204 widthSegments: t, 14205 heightSegments: i, 14206 phiStart: r, 14207 phiLength: s, 14208 thetaStart: a, 14209 thetaLength: l 14210 }, t = Math.max(3, Math.floor(t)), i = Math.max(2, Math.floor(i)); 14211 const o = Math.min(a + l, Math.PI);
14212 let c = 0; 14213 const u = [], h = new W(), d = new W(), f = [], p = [], v = [], m = []; 14214 for (let g = 0; g <= i; g++) { 14215 const _ = [], x = g / i; 14216 let E = 0; 14217 g === 0 && a === 0 ? E = 0.5 / t : g === i && o === Math.PI && (E = -0.5 / t); 14218 for (let R = 0; R <= t; R++) { 14219 const T = R / t; 14220 h.x = -e * Math.cos(r + T * s) * Math.sin(a + x * l), h.y = e * Math.cos(a + x * l), h.z = e * Math.sin(r + T * s) * Math.sin(a + x * l), p.push(h.x, h.y, h.z), d.copy(h).normalize(), v.push(d.x, d.y, d.z), m.push(T + E, 1 - x), _.push(c++); 14221 } 14222 u.push(_); 14223 } 14224 for (let g = 0; g < i; g++) 14225 for (let _ = 0; _ < t; _++) { 14226 const x = u[g][_ + 1], E = u[g][_], R = u[g + 1][_], T = u[g + 1][_ + 1]; 14227 (g !== 0 || a > 0) && f.push(x, E, T), (g !== i - 1 || o < Math.PI) && f.push(E, R, T); 14228 } 14229 this.setIndex(f), this.setAttribute("position", new vn(p, 3)), this.setAttribute("normal", new vn(v, 3)), this.setAttribute("uv", new vn(m, 2)); 14230 } 14231 copy(e) { 14232 return super.copy(e), this.parameters = Object.assign({}, e.parameters), this; 14233 } 14234 /** 14235 * Factory method for creating an instance of this class from the given 14236 * JSON object. 14237 * 14238 * @param {Object} data - A JSON object representing the serialized geometry. 14239 * @return {SphereGeometry} A new instance. 14240 */ 14241 static fromJSON(e) { 14242 return new Ms(e.radius, e.widthSegments, e.heightSegments, e.phiStart, e.phiLength, e.thetaStart, e.thetaLength); 14243 } 14244} 14245function _s(n) { 14246 const e = {}; 14247 for (const t in n) { 14248 e[t] = {}; 14249 for (const i in n[t]) { 14250 const r = n[t][i]; 14251 if (fd(r)) 14252 r.isRenderTargetTexture ? (tt("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."), e[t][i] = null) : e[t][i] = r.clone(); 14253 else if (Array.isArray(r)) 14254 if (fd(r[0])) { 14255 const s = []; 14256 for (let a = 0, l = r.length; a < l; a++) 14257 s[a] = r[a].clone(); 14258 e[t][i] = s; 14259 } else 14260 e[t][i] = r.slice(); 14261 else 14262 e[t][i] = r; 14263 } 14264 } 14265 return e; 14266} 14267function pn(n) { 14268 const e = {}; 14269 for (let t = 0; t < n.length; t++) { 14270 const i = _s(n[t]); 14271 for (const r in i) 14272 e[r] = i[r]; 14273 } 14274 return e; 14275} 14276function fd(n) { 14277 return n && (n.isColor || n.isMatrix3 || n.isMatrix4 || n.isVector2 || n.isVector3 || n.isVector4 || n.isTexture || n.isQuaternion); 14278} 14279function Z_(n) { 14280 const e = []; 14281 for (let t = 0; t < n.length; t++) 14282 e.push(n[t].clone()); 14283 return e; 14284} 14285function Wp(n) { 14286 const e = n.getRenderTarget(); 14287 return e === null ? n.outputColorSpace : e.isXRRenderTarget === !0 ? e.texture.colorSpace : _t.workingColorSpace; 14288} 14289const Q_ = { clone: _s, merge: pn }; 14290var ey = `void main() { 14291 gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); 14292}`, ty = `void main() { 14293 gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 ); 14294}`;
vendor: 12,749 bytes, lines 14295-14569
14295class yn extends Es { 14296 /** 14297 * Constructs a new shader material. 14298 * 14299 * @param {Object} [parameters] - An object with one or more properties 14300 * defining the material's appearance. Any property of the material 14301 * (including any property from inherited materials) can be passed 14302 * in here. Color values can be passed any type of value accepted 14303 * by {@link Color#set}. 14304 */ 14305 constructor(e) { 14306 super(), this.isShaderMaterial = !0, this.type = "ShaderMaterial", this.defines = {}, this.uniforms = {}, this.uniformsGroups = [], this.vertexShader = ey, this.fragmentShader = ty, this.linewidth = 1, this.wireframe = !1, this.wireframeLinewidth = 1, this.fog = !1, this.lights = !1, this.clipping = !1, this.forceSinglePass = !0, this.extensions = { 14307 clipCullDistance: !1, 14308 // set to use vertex shader clipping 14309 multiDraw: !1 14310 // set to use vertex shader multi_draw / enable gl_DrawID 14311 }, this.defaultAttributeValues = { 14312 color: [1, 1, 1], 14313 uv: [0, 0], 14314 uv1: [0, 0] 14315 }, this.index0AttributeName = void 0, this.uniformsNeedUpdate = !1, this.glslVersion = null, e !== void 0 && this.setValues(e); 14316 } 14317 copy(e) { 14318 return super.copy(e), this.fragmentShader = e.fragmentShader, this.vertexShader = e.vertexShader, this.uniforms = _s(e.uniforms), this.uniformsGroups = Z_(e.uniformsGroups), this.defines = Object.assign({}, e.defines), this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.fog = e.fog, this.lights = e.lights, this.clipping = e.clipping, this.extensions = Object.assign({}, e.extensions), this.glslVersion = e.glslVersion, this.defaultAttributeValues = Object.assign({}, e.defaultAttributeValues), this.index0AttributeName = e.index0AttributeName, this.uniformsNeedUpdate = e.uniformsNeedUpdate, this; 14319 } 14320 toJSON(e) { 14321 const t = super.toJSON(e); 14322 t.glslVersion = this.glslVersion, t.uniforms = {}; 14323 for (const r in this.uniforms) { 14324 const a = this.uniforms[r].value; 14325 a && a.isTexture ? t.uniforms[r] = { 14326 type: "t", 14327 value: a.toJSON(e).uuid 14328 } : a && a.isColor ? t.uniforms[r] = { 14329 type: "c", 14330 value: a.getHex() 14331 } : a && a.isVector2 ? t.uniforms[r] = { 14332 type: "v2", 14333 value: a.toArray() 14334 } : a && a.isVector3 ? t.uniforms[r] = { 14335 type: "v3", 14336 value: a.toArray() 14337 } : a && a.isVector4 ? t.uniforms[r] = { 14338 type: "v4", 14339 value: a.toArray() 14340 } : a && a.isMatrix3 ? t.uniforms[r] = { 14341 type: "m3", 14342 value: a.toArray() 14343 } : a && a.isMatrix4 ? t.uniforms[r] = { 14344 type: "m4", 14345 value: a.toArray() 14346 } : t.uniforms[r] = { 14347 value: a 14348 }; 14349 } 14350 Object.keys(this.defines).length > 0 && (t.defines = this.defines), t.vertexShader = this.vertexShader, t.fragmentShader = this.fragmentShader, t.lights = this.lights, t.clipping = this.clipping; 14351 const i = {}; 14352 for (const r in this.extensions) 14353 this.extensions[r] === !0 && (i[r] = !0); 14354 return Object.keys(i).length > 0 && (t.extensions = i), t; 14355 } 14356} 14357class ny extends yn { 14358 /** 14359 * Constructs a new raw shader material. 14360 * 14361 * @param {Object} [parameters] - An object with one or more properties 14362 * defining the material's appearance. Any property of the material 14363 * (including any property from inherited materials) can be passed 14364 * in here. Color values can be passed any type of value accepted 14365 * by {@link Color#set}. 14366 */ 14367 constructor(e) { 14368 super(e), this.isRawShaderMaterial = !0, this.type = "RawShaderMaterial"; 14369 } 14370} 14371class Xu extends Es { 14372 /** 14373 * Constructs a new mesh phong material. 14374 * 14375 * @param {Object} [parameters] - An object with one or more properties 14376 * defining the material's appearance. Any property of the material 14377 * (including any property from inherited materials) can be passed 14378 * in here. Color values can be passed any type of value accepted 14379 * by {@link Color#set}. 14380 */ 14381 constructor(e) { 14382 super(), this.isMeshPhongMaterial = !0, this.type = "MeshPhongMaterial", this.color = new Et(16777215), this.specular = new Et(1118481), this.shininess = 30, this.map = null, this.lightMap = null, this.lightMapIntensity = 1, this.aoMap = null, this.aoMapIntensity = 1, this.emissive = new Et(0), this.emissiveIntensity = 1, this.emissiveMap = null, this.bumpMap = null, this.bumpScale = 1, this.normalMap = null, this.normalMapType = Yc, this.normalScale = new wt(1, 1), this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.specularMap = null, this.alphaMap = null, this.envMap = null, this.envMapRotation = new ar(), this.combine = Nu, this.reflectivity = 1, this.envMapIntensity = 1, this.refractionRatio = 0.98, this.wireframe = !1, this.wireframeLinewidth = 1, this.wireframeLinecap = "round", this.wireframeLinejoin = "round", this.flatShading = !1, this.fog = !0, this.setValues(e); 14383 } 14384 copy(e) { 14385 return super.copy(e), this.color.copy(e.color), this.specular.copy(e.specular), this.shininess = e.shininess, this.map = e.map, this.lightMap = e.lightMap, this.lightMapIntensity = e.lightMapIntensity, this.aoMap = e.aoMap, this.aoMapIntensity = e.aoMapIntensity, this.emissive.copy(e.emissive), this.emissiveMap = e.emissiveMap, this.emissiveIntensity = e.emissiveIntensity, this.bumpMap = e.bumpMap, this.bumpScale = e.bumpScale, this.normalMap = e.normalMap, this.normalMapType = e.normalMapType, this.normalScale.copy(e.normalScale), this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this.specularMap = e.specularMap, this.alphaMap = e.alphaMap, this.envMap = e.envMap, this.envMapRotation.copy(e.envMapRotation), this.combine = e.combine, this.reflectivity = e.reflectivity, this.envMapIntensity = e.envMapIntensity, this.refractionRatio = e.refractionRatio, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this.wireframeLinecap = e.wireframeLinecap, this.wireframeLinejoin = e.wireframeLinejoin, this.flatShading = e.flatShading, this.fog = e.fog, this; 14386 } 14387} 14388class iy extends Es { 14389 /** 14390 * Constructs a new mesh depth material. 14391 * 14392 * @param {Object} [parameters] - An object with one or more properties 14393 * defining the material's appearance. Any property of the material 14394 * (including any property from inherited materials) can be passed 14395 * in here. Color values can be passed any type of value accepted 14396 * by {@link Color#set}. 14397 */ 14398 constructor(e) { 14399 super(), this.isMeshDepthMaterial = !0, this.type = "MeshDepthMaterial", this.depthPacking = p_, this.map = null, this.alphaMap = null, this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.wireframe = !1, this.wireframeLinewidth = 1, this.setValues(e); 14400 } 14401 copy(e) { 14402 return super.copy(e), this.depthPacking = e.depthPacking, this.map = e.map, this.alphaMap = e.alphaMap, this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this.wireframe = e.wireframe, this.wireframeLinewidth = e.wireframeLinewidth, this; 14403 } 14404} 14405class ry extends Es { 14406 /** 14407 * Constructs a new mesh distance material. 14408 * 14409 * @param {Object} [parameters] - An object with one or more properties 14410 * defining the material's appearance. Any property of the material 14411 * (including any property from inherited materials) can be passed 14412 * in here. Color values can be passed any type of value accepted 14413 * by {@link Color#set}. 14414 */ 14415 constructor(e) { 14416 super(), this.isMeshDistanceMaterial = !0, this.type = "MeshDistanceMaterial", this.map = null, this.alphaMap = null, this.displacementMap = null, this.displacementScale = 1, this.displacementBias = 0, this.setValues(e); 14417 } 14418 copy(e) { 14419 return super.copy(e), this.map = e.map, this.alphaMap = e.alphaMap, this.displacementMap = e.displacementMap, this.displacementScale = e.displacementScale, this.displacementBias = e.displacementBias, this; 14420 } 14421} 14422class $p extends Zt { 14423 /** 14424 * Constructs a new light. 14425 * 14426 * @param {(number|Color|string)} [color=0xffffff] - The light's color. 14427 * @param {number} [intensity=1] - The light's strength/intensity. 14428 */ 14429 constructor(e, t = 1) { 14430 super(), this.isLight = !0, this.type = "Light", this.color = new Et(e), this.intensity = t; 14431 } 14432 /** 14433 * Frees the GPU-related resources allocated by this instance. Call this 14434 * method whenever this instance is no longer used in your app. 14435 */ 14436 dispose() { 14437 this.dispatchEvent({ type: "dispose" }); 14438 } 14439 copy(e, t) { 14440 return super.copy(e, t), this.color.copy(e.color), this.intensity = e.intensity, this; 14441 } 14442 toJSON(e) { 14443 const t = super.toJSON(e); 14444 return t.object.color = this.color.getHex(), t.object.intensity = this.intensity, t; 14445 } 14446} 14447const kl = /* @__PURE__ */ new kt(), pd = /* @__PURE__ */ new W(), md = /* @__PURE__ */ new W(); 14448class sy { 14449 /** 14450 * Constructs a new light shadow. 14451 * 14452 * @param {Camera} camera - The light's view of the world. 14453 */ 14454 constructor(e) { 14455 this.camera = e, this.intensity = 1, this.bias = 0, this.biasNode = null, this.normalBias = 0, this.radius = 1, this.blurSamples = 8, this.mapSize = new wt(512, 512), this.mapType = Pn, this.map = null, this.mapPass = null, this.matrix = new kt(), this.autoUpdate = !0, this.needsUpdate = !1, this._frustum = new ju(), this._frameExtents = new wt(1, 1), this._viewportCount = 1, this._viewports = [ 14456 new Gt(0, 0, 1, 1) 14457 ]; 14458 } 14459 /** 14460 * Used internally by the renderer to get the number of viewports that need 14461 * to be rendered for this shadow. 14462 * 14463 * @return {number} The viewport count. 14464 */ 14465 getViewportCount() { 14466 return this._viewportCount; 14467 } 14468 /** 14469 * Gets the shadow cameras frustum. Used internally by the renderer to cull objects. 14470 * 14471 * @return {Frustum} The shadow camera frustum. 14472 */ 14473 getFrustum() { 14474 return this._frustum; 14475 } 14476 /** 14477 * Update the matrices for the camera and shadow, used internally by the renderer. 14478 * 14479 * @param {Light} light - The light for which the shadow is being rendered. 14480 */ 14481 updateMatrices(e) { 14482 const t = this.camera, i = this.matrix; 14483 pd.setFromMatrixPosition(e.matrixWorld), t.position.copy(pd), md.setFromMatrixPosition(e.target.matrixWorld), t.lookAt(md), t.updateMatrixWorld(), kl.multiplyMatrices(t.projectionMatrix, t.matrixWorldInverse), this._frustum.setFromProjectionMatrix(kl, t.coordinateSystem, t.reversedDepth), t.coordinateSystem === la || t.reversedDepth ? i.set( 14484 0.5, 14485 0, 14486 0, 14487 0.5, 14488 0, 14489 0.5, 14490 0, 14491 0.5, 14492 0, 14493 0, 14494 1, 14495 0, 14496 // Identity Z (preserving the correct [0, 1] range from the projection matrix) 14497 0, 14498 0, 14499 0, 14500 1 14501 ) : i.set( 14502 0.5, 14503 0, 14504 0, 14505 0.5, 14506 0, 14507 0.5, 14508 0, 14509 0.5, 14510 0, 14511 0, 14512 0.5, 14513 0.5, 14514 0, 14515 0, 14516 0, 14517 1 14518 ), i.multiply(kl); 14519 } 14520 /** 14521 * Returns a viewport definition for the given viewport index. 14522 * 14523 * @param {number} viewportIndex - The viewport index. 14524 * @return {Vector4} The viewport. 14525 */ 14526 getViewport(e) { 14527 return this._viewports[e]; 14528 } 14529 /** 14530 * Returns the frame extends. 14531 * 14532 * @return {Vector2} The frame extends. 14533 */ 14534 getFrameExtents() { 14535 return this._frameExtents; 14536 } 14537 /** 14538 * Frees the GPU-related resources allocated by this instance. Call this 14539 * method whenever this instance is no longer used in your app. 14540 */ 14541 dispose() { 14542 this.map && this.map.dispose(), this.mapPass && this.mapPass.dispose(); 14543 } 14544 /** 14545 * Copies the values of the given light shadow instance to this instance. 14546 * 14547 * @param {LightShadow} source - The light shadow to copy. 14548 * @return {LightShadow} A reference to this light shadow instance. 14549 */ 14550 copy(e) { 14551 return this.camera = e.camera.clone(), this.intensity = e.intensity, this.bias = e.bias, this.radius = e.radius, this.autoUpdate = e.autoUpdate, this.needsUpdate = e.needsUpdate, this.normalBias = e.normalBias, this.blurSamples = e.blurSamples, this.mapSize.copy(e.mapSize), this.biasNode = e.biasNode, this; 14552 } 14553 /** 14554 * Returns a new light shadow instance with copied values from this instance. 14555 * 14556 * @return {LightShadow} A clone of this instance. 14557 */ 14558 clone() { 14559 return new this.constructor().copy(this); 14560 } 14561 /** 14562 * Serializes the light shadow into JSON. 14563 * 14564 * @return {Object} A JSON object representing the serialized light shadow. 14565 * @see {@link ObjectLoader#parse} 14566 */ 14567 toJSON() { 14568 const e = {}; 14569 return this.intensity !== 1 && (e.intensity = this.intensity), this.bias !== 0 && (e.bias = this.bias), this.normalBias !== 0 && (e.normalBias = this.normalBias), this.radius !== 1 && (e.radiu
14569s = this.radius), (this.mapSize.x !== 512 || this.mapSize.y !== 512) && (e.mapSize = this.mapSize.toArray()), e.camera = this.camera.toJSON(!1).object, delete e.camera.matrix, e; 14570 } 14571} 14572const Qa = /* @__PURE__ */ new W(), eo = /* @__PURE__ */ new Wn(), si = /* @__PURE__ */ new W(); 14573class jp extends Zt { 14574 /** 14575 * Constructs a new camera. 14576 */ 14577 constructor() { 14578 super(), this.isCamera = !0, this.type = "Camera", this.matrixWorldInverse = new kt(), this.projectionMatrix = new kt(), this.projectionMatrixInverse = new kt(), this.coordinateSystem = ui, this._reversedDepth = !1; 14579 } 14580 /** 14581 * The flag that indicates whether the camera uses a reversed depth buffer. 14582 * 14583 * @type {boolean} 14584 * @default false 14585 */ 14586 get reversedDepth() { 14587 return this._reversedDepth; 14588 } 14589 copy(e, t) { 14590 return super.copy(e, t), this.matrixWorldInverse.copy(e.matrixWorldInverse), this.projectionMatrix.copy(e.projectionMatrix), this.projectionMatrixInverse.copy(e.projectionMatrixInverse), this.coordinateSystem = e.coordinateSystem, this; 14591 } 14592 /** 14593 * Returns a vector representing the ("look") direction of the 3D object in world space. 14594 * 14595 * This method is overwritten since cameras have a different forward vector compared to other 14596 * 3D objects. A camera looks down its local, negative z-axis by default. 14597 * 14598 * @param {Vector3} target - The target vector the result is stored to. 14599 * @return {Vector3} The 3D object's direction in world space. 14600 */ 14601 getWorldDirection(e) { 14602 return super.getWorldDirection(e).negate(); 14603 } 14604 updateMatrixWorld(e) { 14605 super.updateMatrixWorld(e), this.matrixWorld.decompose(Qa, eo, si), si.x === 1 && si.y === 1 && si.z === 1 ? this.matrixWorldInverse.copy(this.matrixWorld).invert() : this.matrixWorldInverse.compose(Qa, eo, si.set(1, 1, 1)).invert(); 14606 } 14607 updateWorldMatrix(e, t) { 14608 super.updateWorldMatrix(e, t), this.matrixWorld.decompose(Qa, eo, si), si.x === 1 && si.y === 1 && si.z === 1 ? this.matrixWorldInverse.copy(this.matrixWorld).invert() : this.matrixWorldInverse.compose(Qa, eo, si.set(1, 1, 1)).invert(); 14609 } 14610 clone() { 14611 return new this.constructor().copy(this); 14612 } 14613} 14614const Xi = /* @__PURE__ */ new W(), gd = /* @__PURE__ */ new wt(), vd = /* @__PURE__ */ new wt(); 14615class mn extends jp { 14616 /** 14617 * Constructs a new perspective camera. 14618 * 14619 * @param {number} [fov=50] - The vertical field of view. 14620 * @param {number} [aspect=1] - The aspect ratio. 14621 * @param {number} [near=0.1] - The camera's near plane. 14622 * @param {number} [far=2000] - The camera's far plane. 14623 */ 14624 constructor(e = 50, t = 1, i = 0.1, r = 2e3) { 14625 super(), this.isPerspectiveCamera = !0, this.type = "PerspectiveCamera", this.fov = e, this.zoom = 1, this.near = i, this.far = r, this.focus = 10, this.aspect = t, this.view = null, this.filmGauge = 35, this.filmOffset = 0, this.updateProjectionMatrix(); 14626 } 14627 copy(e, t) { 14628 return super.copy(e, t), this.fov = e.fov, this.zoom = e.zoom, this.near = e.near, this.far = e.far, this.focus = e.focus, this.aspect = e.aspect, this.view = e.view === null ? null : Object.assign({}, e.view), this.filmGauge = e.filmGauge, this.filmOffset = e.filmOffset, this; 14629 } 14630 /** 14631 * Sets the FOV by focal length in respect to the current {@link PerspectiveCamera#filmGauge}. 14632 * 14633 * The default film gauge is 35, so that the focal length can be specified for 14634 * a 35mm (full frame) camera. 14635 * 14636 * @param {number} focalLength - Values for focal length and film gauge must have the same unit. 14637 */ 14638 setFocalLength(e) { 14639 const t = 0.5 * this.getFilmHeight() / e; 14640 this.fov = Jc * 2 * Math.atan(t), this.updateProjectionMatrix(); 14641 } 14642 /** 14643 * Returns the focal length from the current {@link PerspectiveCamera#fov} and 14644 * {@link PerspectiveCamera#filmGauge}. 14645 * 14646 * @return {number} The computed focal length. 14647 */ 14648 getFocalLength() { 14649 const e = Math.tan(fl * 0.5 * this.fov); 14650 return 0.5 * this.getFilmHeight() / e; 14651 } 14652 /** 14653 * Returns the current vertical field of view angle in degrees considering {@link PerspectiveCamera#zoom}. 14654 * 14655 * @return {number} The effective FOV. 14656 */
vendor: 30,527 bytes, lines 14657-15423
14657 getEffectiveFOV() { 14658 return Jc * 2 * Math.atan( 14659 Math.tan(fl * 0.5 * this.fov) / this.zoom 14660 ); 14661 } 14662 /** 14663 * Returns the width of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or 14664 * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}. 14665 * 14666 * @return {number} The film width. 14667 */ 14668 getFilmWidth() { 14669 return this.filmGauge * Math.min(this.aspect, 1); 14670 } 14671 /** 14672 * Returns the height of the image on the film. If {@link PerspectiveCamera#aspect} is greater than or 14673 * equal to one (landscape format), the result equals {@link PerspectiveCamera#filmGauge}. 14674 * 14675 * @return {number} The film width. 14676 */ 14677 getFilmHeight() { 14678 return this.filmGauge / Math.max(this.aspect, 1); 14679 } 14680 /** 14681 * Computes the 2D bounds of the camera's viewable rectangle at a given distance along the viewing direction. 14682 * Sets `minTarget` and `maxTarget` to the coordinates of the lower-left and upper-right corners of the view rectangle. 14683 * 14684 * @param {number} distance - The viewing distance. 14685 * @param {Vector2} minTarget - The lower-left corner of the view rectangle is written into this vector. 14686 * @param {Vector2} maxTarget - The upper-right corner of the view rectangle is written into this vector. 14687 */ 14688 getViewBounds(e, t, i) { 14689 Xi.set(-1, -1, 0.5).applyMatrix4(this.projectionMatrixInverse), t.set(Xi.x, Xi.y).multiplyScalar(-e / Xi.z), Xi.set(1, 1, 0.5).applyMatrix4(this.projectionMatrixInverse), i.set(Xi.x, Xi.y).multiplyScalar(-e / Xi.z); 14690 } 14691 /** 14692 * Computes the width and height of the camera's viewable rectangle at a given distance along the viewing direction. 14693 * 14694 * @param {number} distance - The viewing distance. 14695 * @param {Vector2} target - The target vector that is used to store result where x is width and y is height. 14696 * @returns {Vector2} The view size. 14697 */ 14698 getViewSize(e, t) { 14699 return this.getViewBounds(e, gd, vd), t.subVectors(vd, gd); 14700 } 14701 /** 14702 * Sets an offset in a larger frustum. This is useful for multi-window or 14703 * multi-monitor/multi-machine setups. 14704 * 14705 * For example, if you have 3x2 monitors and each monitor is 1920x1080 and 14706 * the monitors are in grid like this 14707 *``` 14708 * +---+---+---+ 14709 * | A | B | C | 14710 * +---+---+---+ 14711 * | D | E | F | 14712 * +---+---+---+ 14713 *``` 14714 * then for each monitor you would call it like this: 14715 *```js 14716 * const w = 1920; 14717 * const h = 1080; 14718 * const fullWidth = w * 3; 14719 * const fullHeight = h * 2; 14720 * 14721 * // --A-- 14722 * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 0, w, h ); 14723 * // --B-- 14724 * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 0, w, h ); 14725 * // --C-- 14726 * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 0, w, h ); 14727 * // --D-- 14728 * camera.setViewOffset( fullWidth, fullHeight, w * 0, h * 1, w, h ); 14729 * // --E-- 14730 * camera.setViewOffset( fullWidth, fullHeight, w * 1, h * 1, w, h ); 14731 * // --F-- 14732 * camera.setViewOffset( fullWidth, fullHeight, w * 2, h * 1, w, h ); 14733 * ``` 14734 * 14735 * Note there is no reason monitors have to be the same size or in a grid. 14736 * 14737 * @param {number} fullWidth - The full width of multiview setup. 14738 * @param {number} fullHeight - The full height of multiview setup. 14739 * @param {number} x - The horizontal offset of the subcamera. 14740 * @param {number} y - The vertical offset of the subcamera. 14741 * @param {number} width - The width of subcamera. 14742 * @param {number} height - The height of subcamera. 14743 */ 14744 setViewOffset(e, t, i, r, s, a) { 14745 this.aspect = e / t, this.view === null && (this.view = { 14746 enabled: !0, 14747 fullWidth: 1, 14748 fullHeight: 1, 14749 offsetX: 0, 14750 offsetY: 0, 14751 width: 1, 14752 height: 1 14753 }), this.view.enabled = !0, this.view.fullWidth = e, this.view.fullHeight = t, this.view.offsetX = i, this.view.offsetY = r, this.view.width = s, this.view.height = a, this.updateProjectionMatrix(); 14754 } 14755 /** 14756 * Removes the view offset from the projection matrix. 14757 */ 14758 clearViewOffset() { 14759 this.view !== null && (this.view.enabled = !1), this.updateProjectionMatrix(); 14760 } 14761 /** 14762 * Updates the camera's projection matrix. Must be called after any change of 14763 * camera properties. 14764 */ 14765 updateProjectionMatrix() { 14766 const e = this.near; 14767 let t = e * Math.tan(fl * 0.5 * this.fov) / this.zoom, i = 2 * t, r = this.aspect * i, s = -0.5 * r; 14768 const a = this.view; 14769 if (this.view !== null && this.view.enabled) { 14770 const o = a.fullWidth, c = a.fullHeight; 14771 s += a.offsetX * r / o, t -= a.offsetY * i / c, r *= a.width / o, i *= a.height / c; 14772 } 14773 const l = this.filmOffset; 14774 l !== 0 && (s += e * l / this.getFilmWidth()), this.projectionMatrix.makePerspective(s, s + r, t, t - i, e, this.far, this.coordinateSystem, this.reversedDepth), this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); 14775 } 14776 toJSON(e) { 14777 const t = super.toJSON(e); 14778 return t.object.fov = this.fov, t.object.zoom = this.zoom, t.object.near = this.near, t.object.far = this.far, t.object.focus = this.focus, t.object.aspect = this.aspect, this.view !== null && (t.object.view = Object.assign({}, this.view)), t.object.filmGauge = this.filmGauge, t.object.filmOffset = this.filmOffset, t; 14779 } 14780} 14781class qu extends jp { 14782 /** 14783 * Constructs a new orthographic camera. 14784 * 14785 * @param {number} [left=-1] - The left plane of the camera's frustum. 14786 * @param {number} [right=1] - The right plane of the camera's frustum. 14787 * @param {number} [top=1] - The top plane of the camera's frustum. 14788 * @param {number} [bottom=-1] - The bottom plane of the camera's frustum. 14789 * @param {number} [near=0.1] - The camera's near plane. 14790 * @param {number} [far=2000] - The camera's far plane. 14791 */ 14792 constructor(e = -1, t = 1, i = 1, r = -1, s = 0.1, a = 2e3) { 14793 super(), this.isOrthographicCamera = !0, this.type = "OrthographicCamera", this.zoom = 1, this.view = null, this.left = e, this.right = t, this.top = i, this.bottom = r, this.near = s, this.far = a, this.updateProjectionMatrix(); 14794 } 14795 copy(e, t) { 14796 return super.copy(e, t), this.left = e.left, this.right = e.right, this.top = e.top, this.bottom = e.bottom, this.near = e.near, this.far = e.far, this.zoom = e.zoom, this.view = e.view === null ? null : Object.assign({}, e.view), this; 14797 } 14798 /** 14799 * Sets an offset in a larger frustum. This is useful for multi-window or 14800 * multi-monitor/multi-machine setups. 14801 * 14802 * @param {number} fullWidth - The full width of multiview setup. 14803 * @param {number} fullHeight - The full height of multiview setup. 14804 * @param {number} x - The horizontal offset of the subcamera. 14805 * @param {number} y - The vertical offset of the subcamera. 14806 * @param {number} width - The width of subcamera. 14807 * @param {number} height - The height of subcamera. 14808 * @see {@link PerspectiveCamera#setViewOffset} 14809 */ 14810 setViewOffset(e, t, i, r, s, a) { 14811 this.view === null && (this.view = { 14812 enabled: !0, 14813 fullWidth: 1, 14814 fullHeight: 1, 14815 offsetX: 0, 14816 offsetY: 0, 14817 width: 1, 14818 height: 1 14819 }), this.view.enabled = !0, this.view.fullWidth = e, this.view.fullHeight = t, this.view.offsetX = i, this.view.offsetY = r, this.view.width = s, this.view.height = a, this.updateProjectionMatrix(); 14820 } 14821 /** 14822 * Removes the view offset from the projection matrix. 14823 */ 14824 clearViewOffset() { 14825 this.view !== null && (this.view.enabled = !1), this.updateProjectionMatrix(); 14826 } 14827 /** 14828 * Updates the camera's projection matrix. Must be called after any change of 14829 * camera properties. 14830 */ 14831 updateProjectionMatrix() { 14832 const e = (this.right - this.left) / (2 * this.zoom), t = (this.top - this.bottom) / (2 * this.zoom), i = (this.right + this.left) / 2, r = (this.top + this.bottom) / 2; 14833 let s = i - e, a = i + e, l = r + t, o = r - t; 14834 if (this.view !== null && this.view.enabled) { 14835 const c = (this.right - this.left) / this.view.fullWidth / this.zoom, u = (this.top - this.bottom) / this.view.fullHeight / this.zoom; 14836 s += c * this.view.offsetX, a = s + c * this.view.width, l -= u * this.view.offsetY, o = l - u * this.view.height; 14837 } 14838 this.projectionMatrix.makeOrthographic(s, a, l, o, this.near, this.far, this.coordinateSystem, this.reversedDepth), this.projectionMatrixInverse.copy(this.projectionMatrix).invert(); 14839 } 14840 toJSON(e) { 14841 const t = super.toJSON(e); 14842 return t.object.zoom = this.zoom, t.object.left = this.left, t.object.right = this.right, t.object.top = this.top, t.object.bottom = this.bottom, t.object.near = this.near, t.object.far = this.far, this.view !== null && (t.object.view = Object.assign({}, this.view)), t; 14843 } 14844} 14845class ay extends sy { 14846 /** 14847 * Constructs a new directional light shadow. 14848 */ 14849 constructor() { 14850 super(new qu(-5, 5, 5, -5, 0.5, 500)), this.isDirectionalLightShadow = !0; 14851 } 14852} 14853class ys extends $p { 14854 /** 14855 * Constructs a new directional light. 14856 * 14857 * @param {(number|Color|string)} [color=0xffffff] - The light's color. 14858 * @param {number} [intensity=1] - The light's strength/intensity. 14859 */ 14860 constructor(e, t) { 14861 super(e, t), this.isDirectionalLight = !0, this.type = "DirectionalLight", this.position.copy(Zt.DEFAULT_UP), this.updateMatrix(), this.target = new Zt(), this.shadow = new ay(); 14862 } 14863 dispose() { 14864 super.dispose(), this.shadow.dispose(); 14865 } 14866 copy(e) { 14867 return super.copy(e), this.target = e.target.clone(), this.shadow = e.shadow.clone(), this; 14868 } 14869 toJSON(e) { 14870 const t = super.toJSON(e); 14871 return t.object.shadow = this.shadow.toJSON(), t.object.target = this.target.uuid, t; 14872 } 14873} 14874class Yu extends $p { 14875 /** 14876 * Constructs a new ambient light. 14877 * 14878 * @param {(number|Color|string)} [color=0xffffff] - The light's color. 14879 * @param {number} [intensity=1] - The light's strength/intensity. 14880 */ 14881 constructor(e, t) { 14882 super(e, t), this.isAmbientLight = !0, this.type = "AmbientLight"; 14883 } 14884} 14885const Yr = -90, Kr = 1; 14886class oy extends Zt { 14887 /** 14888 * Constructs a new cube camera. 14889 * 14890 * @param {number} near - The camera's near plane. 14891 * @param {number} far - The camera's far plane. 14892 * @param {WebGLCubeRenderTarget} renderTarget - The cube render target. 14893 */ 14894 constructor(e, t, i) { 14895 super(), this.type = "CubeCamera", this.renderTarget = i, this.coordinateSystem = null, this.activeMipmapLevel = 0; 14896 const r = new mn(Yr, Kr, e, t); 14897 r.layers = this.layers, this.add(r); 14898 const s = new mn(Yr, Kr, e, t); 14899 s.layers = this.layers, this.add(s); 14900 const a = new mn(Yr, Kr, e, t); 14901 a.layers = this.layers, this.add(a); 14902 const l = new mn(Yr, Kr, e, t); 14903 l.layers = this.layers, this.add(l); 14904 const o = new mn(Yr, Kr, e, t); 14905 o.layers = this.layers, this.add(o); 14906 const c = new mn(Yr, Kr, e, t); 14907 c.layers = this.layers, this.add(c); 14908 } 14909 /** 14910 * Must be called when the coordinate system of the cube camera is changed. 14911 */ 14912 updateCoordinateSystem() { 14913 const e = this.coordinateSystem, t = this.children.concat(), [i, r, s, a, l, o] = t; 14914 for (const c of t) this.remove(c); 14915 if (e === ui) 14916 i.up.set(0, 1, 0), i.lookAt(1, 0, 0), r.up.set(0, 1, 0), r.lookAt(-1, 0, 0), s.up.set(0, 0, -1), s.lookAt(0, 1, 0), a.up.set(0, 0, 1), a.lookAt(0, -1, 0), l.up.set(0, 1, 0), l.lookAt(0, 0, 1), o.up.set(0, 1, 0), o.lookAt(0, 0, -1); 14917 else if (e === la) 14918 i.up.set(0, -1, 0), i.lookAt(-1, 0, 0), r.up.set(0, -1, 0), r.lookAt(1, 0, 0), s.up.set(0, 0, 1), s.lookAt(0, 1, 0), a.up.set(0, 0, -1), a.lookAt(0, -1, 0), l.up.set(0, -1, 0), l.lookAt(0, 0, 1), o.up.set(0, -1, 0), o.lookAt(0, 0, -1); 14919 else 14920 throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: " + e); 14921 for (const c of t) 14922 this.add(c), c.updateMatrixWorld(); 14923 } 14924 /** 14925 * Calling this method will render the given scene with the given renderer 14926 * into the cube render target of the camera. 14927 * 14928 * @param {(Renderer|WebGLRenderer)} renderer - The renderer. 14929 * @param {Scene} scene - The scene to render. 14930 */ 14931 update(e, t) { 14932 this.parent === null && this.updateMatrixWorld(); 14933 const { renderTarget: i, activeMipmapLevel: r } = this; 14934 this.coordinateSystem !== e.coordinateSystem && (this.coordinateSystem = e.coordinateSystem, this.updateCoordinateSystem()); 14935 const [s, a, l, o, c, u] = this.children, h = e.getRenderTarget(), d = e.getActiveCubeFace(), f = e.getActiveMipmapLevel(), p = e.xr.enabled; 14936 e.xr.enabled = !1; 14937 const v = i.texture.generateMipmaps; 14938 i.texture.generateMipmaps = !1; 14939 let m = !1; 14940 e.isWebGLRenderer === !0 ? m = e.state.buffers.depth.getReversed() : m = e.reversedDepthBuffer, e.setRenderTarget(i, 0, r), m && e.autoClear === !1 && e.clearDepth(), e.render(t, s), e.setRenderTarget(i, 1, r), m && e.autoClear === !1 && e.clearDepth(), e.render(t, a), e.setRenderTarget(i, 2, r), m && e.autoClear === !1 && e.clearDepth(), e.render(t, l), e.setRenderTarget(i, 3, r), m && e.autoClear === !1 && e.clearDepth(), e.render(t, o), e.setRenderTarget(i, 4, r), m && e.autoClear === !1 && e.clearDepth(), e.render(t, c), i.texture.generateMipmaps = v, e.setRenderTarget(i, 5, r), m && e.autoClear === !1 && e.clearDepth(), e.render(t, u), e.setRenderTarget(h, d, f), e.xr.enabled = p, i.texture.needsPMREMUpdate = !0; 14941 } 14942} 14943class ly extends mn { 14944 /** 14945 * Constructs a new array camera. 14946 * 14947 * @param {Array<PerspectiveCamera>} [array=[]] - An array of perspective sub cameras. 14948 */ 14949 constructor(e = []) { 14950 super(), this.isArrayCamera = !0, this.isMultiViewCamera = !1, this.cameras = e; 14951 } 14952} 14953const _d = /* @__PURE__ */ new kt(); 14954class Xp { 14955 /** 14956 * Constructs a new raycaster. 14957 * 14958 * @param {Vector3} origin - The origin vector where the ray casts from. 14959 * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray. 14960 * @param {number} [near=0] - All results returned are further away than near. Near can't be negative. 14961 * @param {number} [far=Infinity] - All results returned are closer than far. Far can't be lower than near. 14962 */ 14963 constructor(e, t, i = 0, r = 1 / 0) { 14964 this.ray = new Wu(e, t), this.near = i, this.far = r, this.camera = null, this.layers = new Vu(), this.params = { 14965 Mesh: {}, 14966 Line: { threshold: 1 }, 14967 LOD: {}, 14968 Points: { threshold: 1 }, 14969 Sprite: {} 14970 }; 14971 } 14972 /** 14973 * Updates the ray with a new origin and direction by copying the values from the arguments. 14974 * 14975 * @param {Vector3} origin - The origin vector where the ray casts from. 14976 * @param {Vector3} direction - The (normalized) direction vector that gives direction to the ray. 14977 */ 14978 set(e, t) { 14979 this.ray.set(e, t); 14980 } 14981 /** 14982 * Uses the given coordinates and camera to compute a new origin and direction for the internal ray. 14983 * 14984 * @param {Vector2} coords - 2D coordinates of the mouse, in normalized device coordinates (NDC). 14985 * X and Y components should be between `-1` and `1`. 14986 * @param {Camera} camera - The camera from which the ray should originate. 14987 */ 14988 setFromCamera(e, t) { 14989 t.isPerspectiveCamera ? (this.ray.origin.setFromMatrixPosition(t.matrixWorld), this.ray.direction.set(e.x, e.y, 0.5).unproject(t).sub(this.ray.origin).normalize(), this.camera = t) : t.isOrthographicCamera ? (this.ray.origin.set(e.x, e.y, (t.near + t.far) / (t.near - t.far)).unproject(t), this.ray.direction.set(0, 0, -1).transformDirection(t.matrixWorld), this.camera = t) : xt("Raycaster: Unsupported camera type: " + t.type); 14990 } 14991 /** 14992 * Uses the given WebXR controller to compute a new origin and direction for the internal ray. 14993 * 14994 * @param {WebXRController} controller - The controller to copy the position and direction from. 14995 * @return {Raycaster} A reference to this raycaster. 14996 */ 14997 setFromXRController(e) { 14998 return _d.identity().extractRotation(e.matrixWorld), this.ray.origin.setFromMatrixPosition(e.matrixWorld), this.ray.direction.set(0, 0, -1).applyMatrix4(_d), this; 14999 } 15000 /** 15001 * The intersection point of a raycaster intersection test. 15002 * @typedef {Object} Raycaster~Intersection 15003 * @property {number} distance - The distance from the ray's origin to the intersection point. 15004 * @property {number} distanceToRay - Some 3D objects e.g. {@link Points} provide the distance of the 15005 * intersection to the nearest point on the ray. For other objects it will be `undefined`. 15006 * @property {Vector3} point - The intersection point, in world coordinates. 15007 * @property {Object} face - The face that has been intersected. 15008 * @property {number} faceIndex - The face index. 15009 * @property {Object3D} object - The 3D object that has been intersected. 15010 * @property {Vector2} uv - U,V coordinates at point of intersection. 15011 * @property {Vector2} uv1 - Second set of U,V coordinates at point of intersection. 15012 * @property {Vector3} normal - Interpolated normal vector at point of intersection. 15013 * @property {number} instanceId - The index number of the instance where the ray 15014 * intersects the {@link InstancedMesh}. 15015 */ 15016 /** 15017 * Checks all intersection between the ray and the object with or without the 15018 * descendants. Intersections are returned sorted by distance, closest first. 15019 * 15020 * `Raycaster` delegates to the `raycast()` method of the passed 3D object, when 15021 * evaluating whether the ray intersects the object or not. This allows meshes to respond 15022 * differently to ray casting than lines or points. 15023 * 15024 * Note that for meshes, faces must be pointed towards the origin of the ray in order 15025 * to be detected; intersections of the ray passing through the back of a face will not 15026 * be detected. To raycast against both faces of an object, you'll want to set {@link Material#side} 15027 * to `THREE.DoubleSide`. 15028 * 15029 * @param {Object3D} object - The 3D object to check for intersection with the ray. 15030 * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants. 15031 * Otherwise it only checks intersection with the object. 15032 * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method. 15033 * @return {Array<Raycaster~Intersection>} An array holding the intersection points. 15034 */ 15035 intersectObject(e, t = !0, i = []) { 15036 return Qc(e, this, i, t), i.sort(yd), i; 15037 } 15038 /** 15039 * Checks all intersection between the ray and the objects with or without 15040 * the descendants. Intersections are returned sorted by distance, closest first. 15041 * 15042 * @param {Array<Object3D>} objects - The 3D objects to check for intersection with the ray. 15043 * @param {boolean} [recursive=true] - If set to `true`, it also checks all descendants. 15044 * Otherwise it only checks intersection with the object. 15045 * @param {Array<Raycaster~Intersection>} [intersects=[]] The target array that holds the result of the method. 15046 * @return {Array<Raycaster~Intersection>} An array holding the intersection points. 15047 */ 15048 intersectObjects(e, t = !0, i = []) { 15049 for (let r = 0, s = e.length; r < s; r++) 15050 Qc(e[r], this, i, t); 15051 return i.sort(yd), i; 15052 } 15053} 15054function yd(n, e) { 15055 return n.distance - e.distance; 15056} 15057function Qc(n, e, t, i) { 15058 let r = !0; 15059 if (n.layers.test(e.layers) && n.raycast(e, t) === !1 && (r = !1), r === !0 && i === !0) { 15060 const s = n.children; 15061 for (let a = 0, l = s.length; a < l; a++) 15062 Qc(s[a], e, t, !0); 15063 } 15064} 15065const lh = class lh { 15066 /** 15067 * Constructs a new 2x2 matrix. The arguments are supposed to be 15068 * in row-major order. If no arguments are provided, the constructor 15069 * initializes the matrix as an identity matrix. 15070 * 15071 * @param {number} [n11] - 1-1 matrix element. 15072 * @param {number} [n12] - 1-2 matrix element. 15073 * @param {number} [n21] - 2-1 matrix element. 15074 * @param {number} [n22] - 2-2 matrix element. 15075 */ 15076 constructor(e, t, i, r) { 15077 this.elements = [ 15078 1, 15079 0, 15080 0, 15081 1 15082 ], e !== void 0 && this.set(e, t, i, r); 15083 } 15084 /** 15085 * Sets this matrix to the 2x2 identity matrix. 15086 * 15087 * @return {Matrix2} A reference to this matrix. 15088 */ 15089 identity() { 15090 return this.set( 15091 1, 15092 0, 15093 0, 15094 1 15095 ), this; 15096 } 15097 /** 15098 * Sets the elements of the matrix from the given array. 15099 * 15100 * @param {Array<number>} array - The matrix elements in column-major order. 15101 * @param {number} [offset=0] - Index of the first element in the array. 15102 * @return {Matrix2} A reference to this matrix. 15103 */ 15104 fromArray(e, t = 0) { 15105 for (let i = 0; i < 4; i++) 15106 this.elements[i] = e[i + t]; 15107 return this; 15108 } 15109 /** 15110 * Sets the elements of the matrix.The arguments are supposed to be 15111 * in row-major order. 15112 * 15113 * @param {number} n11 - 1-1 matrix element. 15114 * @param {number} n12 - 1-2 matrix element. 15115 * @param {number} n21 - 2-1 matrix element. 15116 * @param {number} n22 - 2-2 matrix element. 15117 * @return {Matrix2} A reference to this matrix. 15118 */ 15119 set(e, t, i, r) { 15120 const s = this.elements; 15121 return s[0] = e, s[2] = t, s[1] = i, s[3] = r, this; 15122 } 15123}; 15124lh.prototype.isMatrix2 = !0; 15125let xd = lh; 15126function bd(n, e, t, i) { 15127 const r = cy(i); 15128 switch (t) { 15129 // https://registry.khronos.org/OpenGL-Refpages/es3.0/html/glTexImage2D.xhtml 15130 case Ip: 15131 return n * e; 15132 case Ou: 15133 return n * e / r.components * r.byteLength; 15134 case ku: 15135 return n * e / r.components * r.byteLength; 15136 case Pr: 15137 return n * e * 2 / r.components * r.byteLength; 15138 case Fu: 15139 return n * e * 2 / r.components * r.byteLength; 15140 case Dp: 15141 return n * e * 3 / r.components * r.byteLength; 15142 case ni: 15143 return n * e * 4 / r.components * r.byteLength; 15144 case Bu: 15145 return n * e * 4 / r.components * r.byteLength; 15146 // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_s3tc_srgb/ 15147 case yo: 15148 case xo: 15149 return Math.floor((n + 3) / 4) * Math.floor((e + 3) / 4) * 8; 15150 case bo: 15151 case wo: 15152 return Math.floor((n + 3) / 4) * Math.floor((e + 3) / 4) * 16; 15153 // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_pvrtc/ 15154 case xc: 15155 case wc: 15156 return Math.max(n, 16) * Math.max(e, 8) / 4; 15157 case yc: 15158 case bc: 15159 return Math.max(n, 8) * Math.max(e, 8) / 2; 15160 // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_etc/ 15161 case Sc: 15162 case Ec: 15163 case Tc: 15164 case Ac: 15165 return Math.floor((n + 3) / 4) * Math.floor((e + 3) / 4) * 8; 15166 case Mc: 15167 case Ro: 15168 case Rc: 15169 return Math.floor((n + 3) / 4) * Math.floor((e + 3) / 4) * 16; 15170 // https://registry.khronos.org/webgl/extensions/WEBGL_compressed_texture_astc/ 15171 case Cc: 15172 return Math.floor((n + 3) / 4) * Math.floor((e + 3) / 4) * 16; 15173 case Pc: 15174 return Math.floor((n + 4) / 5) * Math.floor((e + 3) / 4) * 16; 15175 case Lc: 15176 return Math.floor((n + 4) / 5) * Math.floor((e + 4) / 5) * 16; 15177 case Nc: 15178 return Math.floor((n + 5) / 6) * Math.floor((e + 4) / 5) * 16; 15179 case Ic: 15180 return Math.floor((n + 5) / 6) * Math.floor((e + 5) / 6) * 16; 15181 case Dc: 15182 return Math.floor((n + 7) / 8) * Math.floor((e + 4) / 5) * 16; 15183 case Uc: 15184 return Math.floor((n + 7) / 8) * Math.floor((e + 5) / 6) * 16; 15185 case Oc: 15186 return Math.floor((n + 7) / 8) * Math.floor((e + 7) / 8) * 16; 15187 case kc: 15188 return Math.floor((n + 9) / 10) * Math.floor((e + 4) / 5) * 16; 15189 case Fc: 15190 return Math.floor((n + 9) / 10) * Math.floor((e + 5) / 6) * 16; 15191 case Bc: 15192 return Math.floor((n + 9) / 10) * Math.floor((e + 7) / 8) * 16; 15193 case zc: 15194 return Math.floor((n + 9) / 10) * Math.floor((e + 9) / 10) * 16; 15195 case Hc: 15196 return Math.floor((n + 11) / 12) * Math.floor((e + 9) / 10) * 16; 15197 case Gc: 15198 return Math.floor((n + 11) / 12) * Math.floor((e + 11) / 12) * 16; 15199 // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_bptc/ 15200 case Vc: 15201 case Wc: 15202 case $c: 15203 return Math.ceil(n / 4) * Math.ceil(e / 4) * 16; 15204 // https://registry.khronos.org/webgl/extensions/EXT_texture_compression_rgtc/ 15205 case jc: 15206 case Xc: 15207 return Math.ceil(n / 4) * Math.ceil(e / 4) * 8; 15208 case Co: 15209 case qc: 15210 return Math.ceil(n / 4) * Math.ceil(e / 4) * 16; 15211 } 15212 throw new Error( 15213 `Unable to determine texture byte length for ${t} format.` 15214 ); 15215} 15216function cy(n) { 15217 switch (n) { 15218 case Pn: 15219 case Cp: 15220 return { byteLength: 1, components: 1 }; 15221 case aa: 15222 case Pp: 15223 case ki: 15224 return { byteLength: 2, components: 1 }; 15225 case Du: 15226 case Uu: 15227 return { byteLength: 2, components: 4 }; 15228 case gi: 15229 case Iu: 15230 case ti: 15231 return { byteLength: 4, components: 1 }; 15232 case Lp: 15233 case Np: 15234 return { byteLength: 4, components: 3 }; 15235 } 15236 throw new Error(`Unknown texture type ${n}.`); 15237} 15238typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register", { detail: { 15239 revision: Lu 15240} })); 15241typeof window < "u" && (window.__THREE__ ? tt("WARNING: Multiple instances of Three.js being imported.") : window.__THREE__ = Lu); 15242/** 15243 * @license 15244 * Copyright 2010-2026 Three.js Authors 15245 * SPDX-License-Identifier: MIT 15246 */ 15247function qp() { 15248 let n = null, e = !1, t = null, i = null; 15249 function r(s, a) { 15250 t(s, a), i = n.requestAnimationFrame(r); 15251 } 15252 return { 15253 start: function() { 15254 e !== !0 && t !== null && n !== null && (i = n.requestAnimationFrame(r), e = !0); 15255 }, 15256 stop: function() { 15257 n !== null && n.cancelAnimationFrame(i), e = !1; 15258 }, 15259 setAnimationLoop: function(s) { 15260 t = s; 15261 }, 15262 setContext: function(s) { 15263 n = s; 15264 } 15265 }; 15266} 15267function uy(n) { 15268 const e = /* @__PURE__ */ new WeakMap(); 15269 function t(l, o) { 15270 const c = l.array, u = l.usage, h = c.byteLength, d = n.createBuffer(); 15271 n.bindBuffer(o, d), n.bufferData(o, c, u), l.onUploadCallback(); 15272 let f; 15273 if (c instanceof Float32Array) 15274 f = n.FLOAT; 15275 else if (typeof Float16Array < "u" && c instanceof Float16Array) 15276 f = n.HALF_FLOAT; 15277 else if (c instanceof Uint16Array) 15278 l.isFloat16BufferAttribute ? f = n.HALF_FLOAT : f = n.UNSIGNED_SHORT; 15279 else if (c instanceof Int16Array) 15280 f = n.SHORT; 15281 else if (c instanceof Uint32Array) 15282 f = n.UNSIGNED_INT; 15283 else if (c instanceof Int32Array) 15284 f = n.INT; 15285 else if (c instanceof Int8Array) 15286 f = n.BYTE; 15287 else if (c instanceof Uint8Array) 15288 f = n.UNSIGNED_BYTE; 15289 else if (c instanceof Uint8ClampedArray) 15290 f = n.UNSIGNED_BYTE; 15291 else 15292 throw new Error("THREE.WebGLAttributes: Unsupported buffer data format: " + c); 15293 return { 15294 buffer: d, 15295 type: f, 15296 bytesPerElement: c.BYTES_PER_ELEMENT, 15297 version: l.version, 15298 size: h 15299 }; 15300 } 15301 function i(l, o, c) { 15302 const u = o.array, h = o.updateRanges; 15303 if (n.bindBuffer(c, l), h.length === 0) 15304 n.bufferSubData(c, 0, u); 15305 else { 15306 h.sort((f, p) => f.start - p.start); 15307 let d = 0; 15308 for (let f = 1; f < h.length; f++) { 15309 const p = h[d], v = h[f]; 15310 v.start <= p.start + p.count + 1 ? p.count = Math.max( 15311 p.count, 15312 v.start + v.count - p.start 15313 ) : (++d, h[d] = v); 15314 } 15315 h.length = d + 1; 15316 for (let f = 0, p = h.length; f < p; f++) { 15317 const v = h[f]; 15318 n.bufferSubData( 15319 c, 15320 v.start * u.BYTES_PER_ELEMENT, 15321 u, 15322 v.start, 15323 v.count 15324 ); 15325 } 15326 o.clearUpdateRanges(); 15327 } 15328 o.onUploadCallback(); 15329 } 15330 function r(l) { 15331 return l.isInterleavedBufferAttribute && (l = l.data), e.get(l); 15332 } 15333 function s(l) { 15334 l.isInterleavedBufferAttribute && (l = l.data); 15335 const o = e.get(l); 15336 o && (n.deleteBuffer(o.buffer), e.delete(l)); 15337 } 15338 function a(l, o) { 15339 if (l.isInterleavedBufferAttribute && (l = l.data), l.isGLBufferAttribute) { 15340 const u = e.get(l); 15341 (!u || u.version < l.version) && e.set(l, { 15342 buffer: l.buffer, 15343 type: l.type, 15344 bytesPerElement: l.elementSize, 15345 version: l.version 15346 }); 15347 return; 15348 } 15349 const c = e.get(l); 15350 if (c === void 0) 15351 e.set(l, t(l, o)); 15352 else if (c.version < l.version) { 15353 if (c.size !== l.array.byteLength) 15354 throw new Error("THREE.WebGLAttributes: The size of the buffer attribute's array buffer does not match the original size. Resizing buffer attributes is not supported."); 15355 i(c.buffer, l, o), c.version = l.version; 15356 } 15357 } 15358 return { 15359 get: r, 15360 remove: s, 15361 update: a 15362 }; 15363} 15364var hy = `#ifdef USE_ALPHAHASH 15365 if ( diffuseColor.a < getAlphaHashThreshold( vPosition ) ) discard; 15366#endif`, dy = `#ifdef USE_ALPHAHASH 15367 const float ALPHA_HASH_SCALE = 0.05; 15368 float hash2D( vec2 value ) { 15369 return fract( 1.0e4 * sin( 17.0 * value.x + 0.1 * value.y ) * ( 0.1 + abs( sin( 13.0 * value.y + value.x ) ) ) ); 15370 } 15371 float hash3D( vec3 value ) { 15372 return hash2D( vec2( hash2D( value.xy ), value.z ) ); 15373 } 15374 float getAlphaHashThreshold( vec3 position ) { 15375 float maxDeriv = max( 15376 length( dFdx( position.xyz ) ), 15377 length( dFdy( position.xyz ) ) 15378 ); 15379 float pixScale = 1.0 / ( ALPHA_HASH_SCALE * maxDeriv ); 15380 vec2 pixScales = vec2( 15381 exp2( floor( log2( pixScale ) ) ), 15382 exp2( ceil( log2( pixScale ) ) ) 15383 ); 15384 vec2 alpha = vec2( 15385 hash3D( floor( pixScales.x * position.xyz ) ), 15386 hash3D( floor( pixScales.y * position.xyz ) ) 15387 ); 15388 float lerpFactor = fract( log2( pixScale ) ); 15389 float x = ( 1.0 - lerpFactor ) * alpha.x + lerpFactor * alpha.y; 15390 float a = min( lerpFactor, 1.0 - lerpFactor ); 15391 vec3 cases = vec3( 15392 x * x / ( 2.0 * a * ( 1.0 - a ) ), 15393 ( x - 0.5 * a ) / ( 1.0 - a ), 15394 1.0 - ( ( 1.0 - x ) * ( 1.0 - x ) / ( 2.0 * a * ( 1.0 - a ) ) ) 15395 ); 15396 float threshold = ( x < ( 1.0 - a ) ) 15397 ? ( ( x < a ) ? cases.x : cases.y ) 15398 : cases.z; 15399 return clamp( threshold , 1.0e-6, 1.0 ); 15400 } 15401#endif`, fy = `#ifdef USE_ALPHAMAP 15402 diffuseColor.a *= texture2D( alphaMap, vAlphaMapUv ).g; 15403#endif`, py = `#ifdef USE_ALPHAMAP 15404 uniform sampler2D alphaMap; 15405#endif`, my = `#ifdef USE_ALPHATEST 15406 #ifdef ALPHA_TO_COVERAGE 15407 diffuseColor.a = smoothstep( alphaTest, alphaTest + fwidth( diffuseColor.a ), diffuseColor.a ); 15408 if ( diffuseColor.a == 0.0 ) discard; 15409 #else 15410 if ( diffuseColor.a < alphaTest ) discard; 15411 #endif 15412#endif`, gy = `#ifdef USE_ALPHATEST 15413 uniform float alphaTest; 15414#endif`, vy = `#ifdef USE_AOMAP 15415 float ambientOcclusion = ( texture2D( aoMap, vAoMapUv ).r - 1.0 ) * aoMapIntensity + 1.0; 15416 reflectedLight.indirectDiffuse *= ambientOcclusion; 15417 #if defined( USE_CLEARCOAT ) 15418 clearcoatSpecularIndirect *= ambientOcclusion; 15419 #endif 15420 #if defined( USE_SHEEN ) 15421 sheenSpecularIndirect *= ambientOcclusion; 15422 #endif 15423 #if defined( USE_ENVMAP ) && defined( STANDARD )
15424 float dotNV = saturate( dot( geometryNormal, geometryViewDir ) ); 15425 reflectedLight.indirectSpecular *= computeSpecularOcclusion( dotNV, ambientOcclusion, material.roughness ); 15426 #endif 15427#endif`, _y = `#ifdef USE_AOMAP 15428 uniform sampler2D aoMap; 15429 uniform float aoMapIntensity; 15430#endif`, yy = `#ifdef USE_BATCHING 15431 #if ! defined( GL_ANGLE_multi_draw ) 15432 #define gl_DrawID _gl_DrawID 15433 uniform int _gl_DrawID; 15434 #endif 15435 uniform highp sampler2D batchingTexture; 15436 uniform highp usampler2D batchingIdTexture; 15437 mat4 getBatchingMatrix( const in float i ) { 15438 int size = textureSize( batchingTexture, 0 ).x; 15439 int j = int( i ) * 4; 15440 int x = j % size; 15441 int y = j / size; 15442 vec4 v1 = texelFetch( batchingTexture, ivec2( x, y ), 0 ); 15443 vec4 v2 = texelFetch( batchingTexture, ivec2( x + 1, y ), 0 ); 15444 vec4 v3 = texelFetch( batchingTexture, ivec2( x + 2, y ), 0 ); 15445 vec4 v4 = texelFetch( batchingTexture, ivec2( x + 3, y ), 0 ); 15446 return mat4( v1, v2, v3, v4 ); 15447 } 15448 float getIndirectIndex( const in int i ) { 15449 int size = textureSize( batchingIdTexture, 0 ).x; 15450 int x = i % size; 15451 int y = i / size; 15452 return float( texelFetch( batchingIdTexture, ivec2( x, y ), 0 ).r ); 15453 } 15454#endif 15455#ifdef USE_BATCHING_COLOR 15456 uniform sampler2D batchingColorTexture; 15457 vec4 getBatchingColor( const in float i ) { 15458 int size = textureSize( batchingColorTexture, 0 ).x; 15459 int j = int( i ); 15460 int x = j % size; 15461 int y = j / size; 15462 return texelFetch( batchingColorTexture, ivec2( x, y ), 0 ); 15463 } 15464#endif`, xy = `#ifdef USE_BATCHING 15465 mat4 batchingMatrix = getBatchingMatrix( getIndirectIndex( gl_DrawID ) ); 15466#endif`, by = `vec3 transformed = vec3( position ); 15467#ifdef USE_ALPHAHASH 15468 vPosition = vec3( position ); 15469#endif`, wy = `vec3 objectNormal = vec3( normal ); 15470#ifdef USE_TANGENT 15471 vec3 objectTangent = vec3( tangent.xyz ); 15472#endif`, Sy = `float G_BlinnPhong_Implicit( ) { 15473 return 0.25; 15474} 15475float D_BlinnPhong( const in float shininess, const in float dotNH ) { 15476 return RECIPROCAL_PI * ( shininess * 0.5 + 1.0 ) * pow( dotNH, shininess ); 15477} 15478vec3 BRDF_BlinnPhong( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in vec3 specularColor, const in float shininess ) { 15479 vec3 halfDir = normalize( lightDir + viewDir ); 15480 float dotNH = saturate( dot( normal, halfDir ) ); 15481 float dotVH = saturate( dot( viewDir, halfDir ) ); 15482 vec3 F = F_Schlick( specularColor, 1.0, dotVH ); 15483 float G = G_BlinnPhong_Implicit( ); 15484 float D = D_BlinnPhong( shininess, dotNH ); 15485 return F * ( G * D ); 15486} // validated`, Ey = `#ifdef USE_IRIDESCENCE 15487 const mat3 XYZ_TO_REC709 = mat3( 15488 3.2404542, -0.9692660, 0.0556434, 15489 -1.5371385, 1.8760108, -0.2040259, 15490 -0.4985314, 0.0415560, 1.0572252 15491 ); 15492 vec3 Fresnel0ToIor( vec3 fresnel0 ) { 15493 vec3 sqrtF0 = sqrt( fresnel0 ); 15494 return ( vec3( 1.0 ) + sqrtF0 ) / ( vec3( 1.0 ) - sqrtF0 ); 15495 } 15496 vec3 IorToFresnel0( vec3 transmittedIor, float incidentIor ) { 15497 return pow2( ( transmittedIor - vec3( incidentIor ) ) / ( transmittedIor + vec3( incidentIor ) ) ); 15498 } 15499 float IorToFresnel0( float transmittedIor, float incidentIor ) { 15500 return pow2( ( transmittedIor - incidentIor ) / ( transmittedIor + incidentIor )); 15501 } 15502 vec3 evalSensitivity( float OPD, vec3 shift ) { 15503 float phase = 2.0 * PI * OPD * 1.0e-9; 15504 vec3 val = vec3( 5.4856e-13, 4.4201e-13, 5.2481e-13 ); 15505 vec3 pos = vec3( 1.6810e+06, 1.7953e+06, 2.2084e+06 ); 15506 vec3 var = vec3( 4.3278e+09, 9.3046e+09, 6.6121e+09 ); 15507 vec3 xyz = val * sqrt( 2.0 * PI * var ) * cos( pos * phase + shift ) * exp( - pow2( phase ) * var ); 15508 xyz.x += 9.7470e-14 * sqrt( 2.0 * PI * 4.5282e+09 ) * cos( 2.2399e+06 * phase + shift[ 0 ] ) * exp( - 4.5282e+09 * pow2( phase ) ); 15509 xyz /= 1.0685e-7; 15510 vec3 rgb = XYZ_TO_REC709 * xyz; 15511 return rgb; 15512 } 15513 vec3 evalIridescence( float outsideIOR, float eta2, float cosTheta1, float thinFilmThickness, vec3 baseF0 ) { 15514 vec3 I; 15515 float iridescenceIOR = mix( outsideIOR, eta2, smoothstep( 0.0, 0.03, thinFilmThickness ) ); 15516 float sinTheta2Sq = pow2( outsideIOR / iridescenceIOR ) * ( 1.0 - pow2( cosTheta1 ) ); 15517 float cosTheta2Sq = 1.0 - sinTheta2Sq; 15518 if ( cosTheta2Sq < 0.0 ) { 15519 return vec3( 1.0 ); 15520 } 15521 float cosTheta2 = sqrt( cosTheta2Sq ); 15522 float R0 = IorToFresnel0( iridescenceIOR, outsideIOR );
15523 float R12 = F_Schlick( R0, 1.0, cosTheta1 ); 15524 float T121 = 1.0 - R12; 15525 float phi12 = 0.0; 15526 if ( iridescenceIOR < outsideIOR ) phi12 = PI; 15527 float phi21 = PI - phi12; 15528 vec3 baseIOR = Fresnel0ToIor( clamp( baseF0, 0.0, 0.9999 ) ); vec3 R1 = IorToFresnel0( baseIOR, iridescenceIOR ); 15529 vec3 R23 = F_Schlick( R1, 1.0, cosTheta2 ); 15530 vec3 phi23 = vec3( 0.0 ); 15531 if ( baseIOR[ 0 ] < iridescenceIOR ) phi23[ 0 ] = PI; 15532 if ( baseIOR[ 1 ] < iridescenceIOR ) phi23[ 1 ] = PI; 15533 if ( baseIOR[ 2 ] < iridescenceIOR ) phi23[ 2 ] = PI; 15534 float OPD = 2.0 * iridescenceIOR * thinFilmThickness * cosTheta2; 15535 vec3 phi = vec3( phi21 ) + phi23; 15536 vec3 R123 = clamp( R12 * R23, 1e-5, 0.9999 ); 15537 vec3 r123 = sqrt( R123 ); 15538 vec3 Rs = pow2( T121 ) * R23 / ( vec3( 1.0 ) - R123 ); 15539 vec3 C0 = R12 + Rs; 15540 I = C0; 15541 vec3 Cm = Rs - T121; 15542 for ( int m = 1; m <= 2; ++ m ) { 15543 Cm *= r123; 15544 vec3 Sm = 2.0 * evalSensitivity( float( m ) * OPD, float( m ) * phi ); 15545 I += Cm * Sm; 15546 } 15547 return max( I, vec3( 0.0 ) ); 15548 } 15549#endif`, My = `#ifdef USE_BUMPMAP 15550 uniform sampler2D bumpMap; 15551 uniform float bumpScale; 15552 vec2 dHdxy_fwd() { 15553 vec2 dSTdx = dFdx( vBumpMapUv ); 15554 vec2 dSTdy = dFdy( vBumpMapUv ); 15555 float Hll = bumpScale * texture2D( bumpMap, vBumpMapUv ).x; 15556 float dBx = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdx ).x - Hll; 15557 float dBy = bumpScale * texture2D( bumpMap, vBumpMapUv + dSTdy ).x - Hll; 15558 return vec2( dBx, dBy ); 15559 } 15560 vec3 perturbNormalArb( vec3 surf_pos, vec3 surf_norm, vec2 dHdxy, float faceDirection ) { 15561 vec3 vSigmaX = normalize( dFdx( surf_pos.xyz ) ); 15562 vec3 vSigmaY = normalize( dFdy( surf_pos.xyz ) ); 15563 vec3 vN = surf_norm; 15564 vec3 R1 = cross( vSigmaY, vN ); 15565 vec3 R2 = cross( vN, vSigmaX ); 15566 float fDet = dot( vSigmaX, R1 ) * faceDirection; 15567 vec3 vGrad = sign( fDet ) * ( dHdxy.x * R1 + dHdxy.y * R2 ); 15568 return normalize( abs( fDet ) * surf_norm - vGrad ); 15569 } 15570#endif`, Ty = `#if NUM_CLIPPING_PLANES > 0 15571 vec4 plane; 15572 #ifdef ALPHA_TO_COVERAGE 15573 float distanceToPlane, distanceGradient; 15574 float clipOpacity = 1.0; 15575 #pragma unroll_loop_start 15576 for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { 15577 plane = clippingPlanes[ i ]; 15578 distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; 15579 distanceGradient = fwidth( distanceToPlane ) / 2.0; 15580 clipOpacity *= smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); 15581 if ( clipOpacity == 0.0 ) discard; 15582 } 15583 #pragma unroll_loop_end 15584 #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES 15585 float unionClipOpacity = 1.0; 15586 #pragma unroll_loop_start 15587 for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { 15588 plane = clippingPlanes[ i ]; 15589 distanceToPlane = - dot( vClipPosition, plane.xyz ) + plane.w; 15590 distanceGradient = fwidth( distanceToPlane ) / 2.0; 15591 unionClipOpacity *= 1.0 - smoothstep( - distanceGradient, distanceGradient, distanceToPlane ); 15592 } 15593 #pragma unroll_loop_end 15594 clipOpacity *= 1.0 - unionClipOpacity; 15595 #endif 15596 diffuseColor.a *= clipOpacity; 15597 if ( diffuseColor.a == 0.0 ) discard; 15598 #else 15599 #pragma unroll_loop_start 15600 for ( int i = 0; i < UNION_CLIPPING_PLANES; i ++ ) { 15601 plane = clippingPlanes[ i ]; 15602 if ( dot( vClipPosition, plane.xyz ) > plane.w ) discard; 15603 } 15604 #pragma unroll_loop_end 15605 #if UNION_CLIPPING_PLANES < NUM_CLIPPING_PLANES 15606 bool clipped = true; 15607 #pragma unroll_loop_start 15608 for ( int i = UNION_CLIPPING_PLANES; i < NUM_CLIPPING_PLANES; i ++ ) { 15609 plane = clippingPlanes[ i ]; 15610 clipped = ( dot( vClipPosition, plane.xyz ) > plane.w ) && clipped; 15611 } 15612 #pragma unroll_loop_end 15613 if ( clipped ) discard; 15614 #endif 15615 #endif 15616#endif`, Ay = `#if NUM_CLIPPING_PLANES > 0 15617 varying vec3 vClipPosition; 15618 uniform vec4 clippingPlanes[ NUM_CLIPPING_PLANES ]; 15619#endif`, Ry = `#if NUM_CLIPPING_PLANES > 0 15620 varying vec3 vClipPosition; 15621#endif`, Cy = `#if NUM_CLIPPING_PLANES > 0 15622 vClipPosition = - mvPosition.xyz; 15623#endif`, Py = `#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) 15624 diffuseColor *= vColor; 15625#endif`, Ly = `#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) 15626 varying vec4 vColor; 15627#endif`, Ny = `#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) 15628 varying vec4 vColor; 15629#endif`, Iy = `#if defined( USE_COLOR ) || defined( USE_COLOR_ALPHA ) || defined( USE_INSTANCING_COLOR ) || defined( USE_BATCHING_COLOR ) 15630 vColor = vec4( 1.0 ); 15631#endif 15632#ifdef USE_COLOR_ALPHA 15633 vColor *= color; 15634#elif defined( USE_COLOR ) 15635 vColor.rgb *= color; 15636#endif 15637#ifdef USE_INSTANCING_COLOR 15638 vColor.rgb *= instanceColor.rgb; 15639#endif 15640#ifdef USE_BATCHING_COLOR 15641 vColor *= getBatchingColor( getIndirectIndex( gl_DrawID ) ); 15642#endif`, Dy = `#define PI 3.141592653589793 15643#define PI2 6.283185307179586 15644#define PI_HALF 1.5707963267948966 15645#define RECIPROCAL_PI 0.3183098861837907 15646#define RECIPROCAL_PI2 0.15915494309189535 15647#define EPSILON 1e-6 15648#ifndef saturate 15649#define saturate( a ) clamp( a, 0.0, 1.0 ) 15650#endif 15651#define whiteComplement( a ) ( 1.0 - saturate( a ) ) 15652float pow2( const in float x ) { return x*x; } 15653vec3 pow2( const in vec3 x ) { return x*x; } 15654float pow3( const in float x ) { return x*x*x; } 15655float pow4( const in float x ) { float x2 = x*x; return x2*x2; } 15656float max3( const in vec3 v ) { return max( max( v.x, v.y ), v.z ); } 15657float average( const in vec3 v ) { return dot( v, vec3( 0.3333333 ) ); } 15658highp float rand( const in vec2 uv ) { 15659 const highp float a = 12.9898, b = 78.233, c = 43758.5453; 15660 highp float dt = dot( uv.xy, vec2( a,b ) ), sn = mod( dt, PI ); 15661 return fract( sin( sn ) * c ); 15662} 15663#ifdef HIGH_PRECISION 15664 float precisionSafeLength( vec3 v ) { return length( v ); } 15665#else 15666 float precisionSafeLength( vec3 v ) { 15667 float maxComponent = max3( abs( v ) ); 15668 return length( v / maxComponent ) * maxComponent; 15669 } 15670#endif 15671struct IncidentLight { 15672 vec3 color; 15673 vec3 direction; 15674 bool visible; 15675}; 15676struct ReflectedLight { 15677 vec3 directDiffuse; 15678 vec3 directSpecular; 15679 vec3 indirectDiffuse; 15680 vec3 indirectSpecular; 15681}; 15682#ifdef USE_ALPHAHASH 15683 varying vec3 vPosition; 15684#endif 15685vec3 transformDirection( in vec3 dir, in mat4 matrix ) { 15686 return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); 15687} 15688vec3 inverseTransformDirection( in vec3 dir, in mat4 matrix ) { 15689 return normalize( ( vec4( dir, 0.0 ) * matrix ).xyz ); 15690} 15691bool isPerspectiveMatrix( mat4 m ) { 15692 return m[ 2 ][ 3 ] == - 1.0; 15693} 15694vec2 equirectUv( in vec3 dir ) { 15695 float u = atan( dir.z, dir.x ) * RECIPROCAL_PI2 + 0.5; 15696 float v = asin( clamp( dir.y, - 1.0, 1.0 ) ) * RECIPROCAL_PI + 0.5; 15697 return vec2( u, v ); 15698}
15699vec3 BRDF_Lambert( const in vec3 diffuseColor ) { 15700 return RECIPROCAL_PI * diffuseColor; 15701} 15702vec3 F_Schlick( const in vec3 f0, const in float f90, const in float dotVH ) { 15703 float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); 15704 return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); 15705} 15706float F_Schlick( const in float f0, const in float f90, const in float dotVH ) { 15707 float fresnel = exp2( ( - 5.55473 * dotVH - 6.98316 ) * dotVH ); 15708 return f0 * ( 1.0 - fresnel ) + ( f90 * fresnel ); 15709} // validated`, Uy = `#ifdef ENVMAP_TYPE_CUBE_UV 15710 #define cubeUV_minMipLevel 4.0 15711 #define cubeUV_minTileSize 16.0 15712 float getFace( vec3 direction ) { 15713 vec3 absDirection = abs( direction ); 15714 float face = - 1.0; 15715 if ( absDirection.x > absDirection.z ) { 15716 if ( absDirection.x > absDirection.y ) 15717 face = direction.x > 0.0 ? 0.0 : 3.0; 15718 else 15719 face = direction.y > 0.0 ? 1.0 : 4.0; 15720 } else { 15721 if ( absDirection.z > absDirection.y ) 15722 face = direction.z > 0.0 ? 2.0 : 5.0; 15723 else 15724 face = direction.y > 0.0 ? 1.0 : 4.0; 15725 } 15726 return face; 15727 } 15728 vec2 getUV( vec3 direction, float face ) { 15729 vec2 uv; 15730 if ( face == 0.0 ) { 15731 uv = vec2( direction.z, direction.y ) / abs( direction.x ); 15732 } else if ( face == 1.0 ) { 15733 uv = vec2( - direction.x, - direction.z ) / abs( direction.y ); 15734 } else if ( face == 2.0 ) { 15735 uv = vec2( - direction.x, direction.y ) / abs( direction.z ); 15736 } else if ( face == 3.0 ) { 15737 uv = vec2( - direction.z, direction.y ) / abs( direction.x ); 15738 } else if ( face == 4.0 ) { 15739 uv = vec2( - direction.x, direction.z ) / abs( direction.y ); 15740 } else { 15741 uv = vec2( direction.x, direction.y ) / abs( direction.z ); 15742 } 15743 return 0.5 * ( uv + 1.0 ); 15744 } 15745 vec3 bilinearCubeUV( sampler2D envMap, vec3 direction, float mipInt ) { 15746 float face = getFace( direction ); 15747 float filterInt = max( cubeUV_minMipLevel - mipInt, 0.0 ); 15748 mipInt = max( mipInt, cubeUV_minMipLevel ); 15749 float faceSize = exp2( mipInt ); 15750 highp vec2 uv = getUV( direction, face ) * ( faceSize - 2.0 ) + 1.0; 15751 if ( face > 2.0 ) { 15752 uv.y += faceSize; 15753 face -= 3.0; 15754 } 15755 uv.x += face * faceSize; 15756 uv.x += filterInt * 3.0 * cubeUV_minTileSize; 15757 uv.y += 4.0 * ( exp2( CUBEUV_MAX_MIP ) - faceSize ); 15758 uv.x *= CUBEUV_TEXEL_WIDTH; 15759 uv.y *= CUBEUV_TEXEL_HEIGHT; 15760 #ifdef texture2DGradEXT 15761 return texture2DGradEXT( envMap, uv, vec2( 0.0 ), vec2( 0.0 ) ).rgb; 15762 #else 15763 return texture2D( envMap, uv ).rgb; 15764 #endif 15765 } 15766 #define cubeUV_r0 1.0 15767 #define cubeUV_m0 - 2.0 15768 #define cubeUV_r1 0.8 15769 #define cubeUV_m1 - 1.0 15770 #define cubeUV_r4 0.4 15771 #define cubeUV_m4 2.0 15772 #define cubeUV_r5 0.305 15773 #define cubeUV_m5 3.0 15774 #define cubeUV_r6 0.21 15775 #define cubeUV_m6 4.0 15776 float roughnessToMip( float roughness ) { 15777 float mip = 0.0; 15778 if ( roughness >= cubeUV_r1 ) { 15779 mip = ( cubeUV_r0 - roughness ) * ( cubeUV_m1 - cubeUV_m0 ) / ( cubeUV_r0 - cubeUV_r1 ) + cubeUV_m0; 15780 } else if ( roughness >= cubeUV_r4 ) { 15781 mip = ( cubeUV_r1 - roughness ) * ( cubeUV_m4 - cubeUV_m1 ) / ( cubeUV_r1 - cubeUV_r4 ) + cubeUV_m1; 15782 } else if ( roughness >= cubeUV_r5 ) { 15783 mip = ( cubeUV_r4 - roughness ) * ( cubeUV_m5 - cubeUV_m4 ) / ( cubeUV_r4 - cubeUV_r5 ) + cubeUV_m4; 15784 } else if ( roughness >= cubeUV_r6 ) { 15785 mip = ( cubeUV_r5 - roughness ) * ( cubeUV_m6 - cubeUV_m5 ) / ( cubeUV_r5 - cubeUV_r6 ) + cubeUV_m5; 15786 } else { 15787 mip = - 2.0 * log2( 1.16 * roughness ); } 15788 return mip; 15789 } 15790 vec4 textureCubeUV( sampler2D envMap, vec3 sampleDir, float roughness ) { 15791 float mip = clamp( roughnessToMip( roughness ), cubeUV_m0, CUBEUV_MAX_MIP ); 15792 float mipF = fract( mip ); 15793 float mipInt = floor( mip ); 15794 vec3 color0 = bilinearCubeUV( envMap, sampleDir, mipInt ); 15795 if ( mipF == 0.0 ) { 15796 return vec4( color0, 1.0 ); 15797 } else { 15798 vec3 color1 = bilinearCubeUV( envMap, sampleDir, mipInt + 1.0 ); 15799 return vec4( mix( color0, color1, mipF ), 1.0 ); 15800 } 15801 } 15802#endif`, Oy = `vec3 transformedNormal = objectNormal; 15803#ifdef USE_TANGENT 15804 vec3 transformedTangent = objectTangent; 15805#endif 15806#ifdef USE_BATCHING 15807 mat3 bm = mat3( batchingMatrix ); 15808 transformedNormal /= vec3( dot( bm[ 0 ], bm[ 0 ] ), dot( bm[ 1 ], bm[ 1 ] ), dot( bm[ 2 ], bm[ 2 ] ) ); 15809 transformedNormal = bm * transformedNormal; 15810 #ifdef USE_TANGENT 15811 transformedTangent = bm * transformedTangent; 15812 #endif 15813#endif 15814#ifdef USE_INSTANCING 15815 mat3 im = mat3( instanceMatrix ); 15816 transformedNormal /= vec3( dot( im[ 0 ], im[ 0 ] ), dot( im[ 1 ], im[ 1 ] ), dot( im[ 2 ], im[ 2 ] ) ); 15817 transformedNormal = im * transformedNormal; 15818 #ifdef USE_TANGENT 15819 transformedTangent = im * transformedTangent; 15820 #endif 15821#endif 15822transformedNormal = normalMatrix * transformedNormal; 15823#ifdef FLIP_SIDED 15824 transformedNormal = - transformedNormal; 15825#endif 15826#ifdef USE_TANGENT 15827 transformedTangent = ( modelViewMatrix * vec4( transformedTangent, 0.0 ) ).xyz; 15828 #ifdef FLIP_SIDED 15829 transformedTangent = - transformedTangent; 15830 #endif 15831#endif`, ky = `#ifdef USE_DISPLACEMENTMAP 15832 uniform sampler2D displacementMap; 15833 uniform float displacementScale; 15834 uniform float displacementBias; 15835#endif`, Fy = `#ifdef USE_DISPLACEMENTMAP 15836 transformed += normalize( objectNormal ) * ( texture2D( displacementMap, vDisplacementMapUv ).x * displacementScale + dis
15836placementBias ); 15837#endif`, By = `#ifdef USE_EMISSIVEMAP 15838 vec4 emissiveColor = texture2D( emissiveMap, vEmissiveMapUv ); 15839 #ifdef DECODE_VIDEO_TEXTURE_EMISSIVE 15840 emissiveColor = sRGBTransferEOTF( emissiveColor ); 15841 #endif 15842 totalEmissiveRadiance *= emissiveColor.rgb; 15843#endif`, zy = `#ifdef USE_EMISSIVEMAP 15844 uniform sampler2D emissiveMap; 15845#endif`, Hy = "gl_FragColor = linearToOutputTexel( gl_FragColor );", Gy = `vec4 LinearTransferOETF( in vec4 value ) { 15846 return value; 15847} 15848vec4 sRGBTransferEOTF( in vec4 value ) { 15849 return vec4( mix( pow( value.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), value.rgb * 0.0773993808, vec3( lessThanEqual( value.rgb, vec3( 0.04045 ) ) ) ), value.a ); 15850} 15851vec4 sRGBTransferOETF( in vec4 value ) { 15852 return vec4( mix( pow( value.rgb, vec3( 0.41666 ) ) * 1.055 - vec3( 0.055 ), value.rgb * 12.92, vec3( lessThanEqual( value.rgb, vec3( 0.0031308 ) ) ) ), value.a ); 15853}`, Vy = `#ifdef USE_ENVMAP 15854 #ifdef ENV_WORLDPOS 15855 vec3 cameraToFrag; 15856 if ( isOrthographic ) { 15857 cameraToFrag = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); 15858 } else { 15859 cameraToFrag = normalize( vWorldPosition - cameraPosition ); 15860 } 15861 vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); 15862 #ifdef ENVMAP_MODE_REFLECTION 15863 vec3 reflectVec = reflect( cameraToFrag, worldNormal ); 15864 #else 15865 vec3 reflectVec = refract( cameraToFrag, worldNormal, refractionRatio ); 15866 #endif 15867 #else 15868 vec3 reflectVec = vReflect; 15869 #endif 15870 #ifdef ENVMAP_TYPE_CUBE 15871 vec4 envColor = textureCube( envMap, envMapRotation * reflectVec ); 15872 #ifdef ENVMAP_BLENDING_MULTIPLY 15873 outgoingLight = mix( outgoingLight, outgoingLight * envColor.xyz, specularStrength * reflectivity ); 15874 #elif defined( ENVMAP_BLENDING_MIX ) 15875 outgoingLight = mix( outgoingLight, envColor.xyz, specularStrength * reflectivity ); 15876 #elif defined( ENVMAP_BLENDING_ADD ) 15877 outgoingLight += envColor.xyz * specularStrength * reflectivity; 15878 #endif 15879 #endif 15880#endif`, Wy = `#ifdef USE_ENVMAP 15881 uniform float envMapIntensity; 15882 uniform mat3 envMapRotation; 15883 #ifdef ENVMAP_TYPE_CUBE 15884 uniform samplerCube envMap; 15885 #else 15886 uniform sampler2D envMap; 15887 #endif 15888#endif`, $y = `#ifdef USE_ENVMAP 15889 uniform float reflectivity; 15890 #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) 15891 #define ENV_WORLDPOS 15892 #endif 15893 #ifdef ENV_WORLDPOS 15894 varying vec3 vWorldPosition; 15895 uniform float refractionRatio; 15896 #else 15897 varying vec3 vReflect; 15898 #endif 15899#endif`, jy = `#ifdef USE_ENVMAP 15900 #if defined( USE_BUMPMAP ) || defined( USE_NORMALMAP ) || defined( PHONG ) || defined( LAMBERT ) 15901 #define ENV_WORLDPOS 15902 #endif 15903 #ifdef ENV_WORLDPOS 15904 15905 varying vec3 vWorldPosition; 15906 #else 15907 varying vec3 vReflect; 15908 uniform float refractionRatio; 15909 #endif 15910#endif`, Xy = `#ifdef USE_ENVMAP 15911 #ifdef ENV_WORLDPOS 15912 vWorldPosition = worldPosition.xyz; 15913 #else 15914 vec3 cameraToVertex; 15915 if ( isOrthographic ) { 15916 cameraToVertex = normalize( vec3( - viewMatrix[ 0 ][ 2 ], - viewMatrix[ 1 ][ 2 ], - viewMatrix[ 2 ][ 2 ] ) ); 15917 } else {
15918 cameraToVertex = normalize( worldPosition.xyz - cameraPosition ); 15919 } 15920 vec3 worldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); 15921 #ifdef ENVMAP_MODE_REFLECTION 15922 vReflect = reflect( cameraToVertex, worldNormal ); 15923 #else 15924 vReflect = refract( cameraToVertex, worldNormal, refractionRatio ); 15925 #endif 15926 #endif 15927#endif`, qy = `#ifdef USE_FOG 15928 vFogDepth = - mvPosition.z; 15929#endif`, Yy = `#ifdef USE_FOG 15930 varying float vFogDepth; 15931#endif`, Ky = `#ifdef USE_FOG 15932 #ifdef FOG_EXP2 15933 float fogFactor = 1.0 - exp( - fogDensity * fogDensity * vFogDepth * vFogDepth ); 15934 #else 15935 float fogFactor = smoothstep( fogNear, fogFar, vFogDepth ); 15936 #endif 15937 gl_FragColor.rgb = mix( gl_FragColor.rgb, fogColor, fogFactor ); 15938#endif`, Jy = `#ifdef USE_FOG 15939 uniform vec3 fogColor; 15940 varying float vFogDepth; 15941 #ifdef FOG_EXP2 15942 uniform float fogDensity; 15943 #else 15944 uniform float fogNear; 15945 uniform float fogFar; 15946 #endif 15947#endif`, Zy = `#ifdef USE_GRADIENTMAP 15948 uniform sampler2D gradientMap; 15949#endif 15950vec3 getGradientIrradiance( vec3 normal, vec3 lightDirection ) { 15951 float dotNL = dot( normal, lightDirection ); 15952 vec2 coord = vec2( dotNL * 0.5 + 0.5, 0.0 ); 15953 #ifdef USE_GRADIENTMAP 15954 return vec3( texture2D( gradientMap, coord ).r ); 15955 #else 15956 vec2 fw = fwidth( coord ) * 0.5; 15957 return mix( vec3( 0.7 ), vec3( 1.0 ), smoothstep( 0.7 - fw.x, 0.7 + fw.x, coord.x ) ); 15958 #endif 15959}`, Qy = `#ifdef USE_LIGHTMAP 15960 uniform sampler2D lightMap; 15961 uniform float lightMapIntensity; 15962#endif`, ex = `LambertMaterial material; 15963material.diffuseColor = diffuseColor.rgb; 15964material.specularStrength = specularStrength;`, tx = `varying vec3 vViewPosition; 15965struct LambertMaterial { 15966 vec3 diffuseColor; 15967 float specularStrength; 15968}; 15969void RE_Direct_Lambert( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { 15970 float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); 15971 vec3 irradiance = dotNL * directLight.color; 15972 reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); 15973} 15974void RE_IndirectDiffuse_Lambert( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in LambertMaterial material, inout ReflectedLight reflectedLight ) { 15975 reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); 15976} 15977#define RE_Direct RE_Direct_Lambert 15978#define RE_IndirectDiffuse RE_IndirectDiffuse_Lambert`, nx = `uniform bool receiveShadow; 15979uniform vec3 ambientLightColor; 15980#if defined( USE_LIGHT_PROBES ) 15981 uniform vec3 lightProbe[ 9 ]; 15982#endif 15983vec3 shGetIrradianceAt( in vec3 normal, in vec3 shCoefficients[ 9 ] ) { 15984 float x = normal.x, y = normal.y, z = normal.z; 15985 vec3 result = shCoefficients[ 0 ] * 0.886227; 15986 result += shCoefficients[ 1 ] * 2.0 * 0.511664 * y; 15987 result += shCoefficients[ 2 ] * 2.0 * 0.511664 * z; 15988 result += shCoefficients[ 3 ] * 2.0 * 0.511664 * x; 15989 result += shCoefficients[ 4 ] * 2.0 * 0.429043 * x * y; 15990 result += shCoefficients[ 5 ] * 2.0 * 0.429043 * y * z; 15991 result += shCoefficients[ 6 ] * ( 0.743125 * z * z - 0.247708 ); 15992 result += shCoefficients[ 7 ] * 2.0 * 0.429043 * x * z; 15993 result += shCoefficients[ 8 ] * 0.429043 * ( x * x - y * y ); 15994 return result; 15995} 15996vec3 getLightProbeIrradiance( const in vec3 lightProbe[ 9 ], const in vec3 normal ) { 15997 vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); 15998 vec3 irradiance = shGetIrradianceAt( worldNormal, lightProbe ); 15999 return irradiance; 16000} 16001vec3 getAmbientLightIrradiance( const in vec3 ambientLightColor ) { 16002 vec3 irradiance = ambientLightColor; 16003 return irradiance; 16004} 16005float getDistanceAttenuation( const in float lightDistance, const in float cutoffDistance, const in float decayExponent ) { 16006 float distanceFalloff = 1.0 / max( pow( lightDistance, decayExponent ), 0.01 ); 16007 if ( cutoffDistance > 0.0 ) { 16008 distanceFalloff *= pow2( saturate( 1.0 - pow4( lightDistance / cutoffDistance ) ) ); 16009 } 16010 return distanceFalloff; 16011} 16012float getSpotAttenuation( const in float coneCosine, const in float penumbraCosine, const in float angleCosine ) { 16013 return smoothstep( coneCosine, penumbraCosine, angleCosine ); 16014} 16015#if NUM_DIR_LIGHTS > 0 16016 struct DirectionalLight { 16017 vec3 direction; 16018 vec3 color; 16019 }; 16020 uniform DirectionalLight directionalLights[ NUM_DIR_LIGHTS ]; 16021 void getDirectionalLightInfo( const in DirectionalLight directionalLight, out IncidentLight light ) { 16022 light.color = directionalLight.color; 16023 light.direction = directionalLight.direction; 16024 light.visible = true; 16025 } 16026#endif 16027#if NUM_POINT_LIGHTS > 0 16028 struct PointLight { 16029 vec3 position; 16030 vec3 color; 16031 float distance; 16032 float decay; 16033 }; 16034 uniform PointLight pointLights[ NUM_POINT_LIGHTS ]; 16035 void getPointLightInfo( const in PointLight pointLight, const in vec3 geometryPosition, out IncidentLight light ) { 16036 vec3 lVector = pointLight.position - geometryPosition; 16037 light.direction = normalize( lVector ); 16038 float lightDistance = length( lVector ); 16039 light.color = pointLight.color; 16040 light.color *= getDistanceAttenuation( lightDistance, pointLight.distance, pointLight.decay ); 16041 light.visible = ( light.color != vec3( 0.0 ) ); 16042 } 16043#endif
16044#if NUM_SPOT_LIGHTS > 0 16045 struct SpotLight { 16046 vec3 position; 16047 vec3 direction; 16048 vec3 color; 16049 float distance; 16050 float decay; 16051 float coneCos; 16052 float penumbraCos; 16053 }; 16054 uniform SpotLight spotLights[ NUM_SPOT_LIGHTS ]; 16055 void getSpotLightInfo( const in SpotLight spotLight, const in vec3 geometryPosition, out IncidentLight light ) { 16056 vec3 lVector = spotLight.position - geometryPosition; 16057 light.direction = normalize( lVector ); 16058 float angleCos = dot( light.direction, spotLight.direction ); 16059 float spotAttenuation = getSpotAttenuation( spotLight.coneCos, spotLight.penumbraCos, angleCos ); 16060 if ( spotAttenuation > 0.0 ) { 16061 float lightDistance = length( lVector ); 16062 light.color = spotLight.color * spotAttenuation; 16063 light.color *= getDistanceAttenuation( lightDistance, spotLight.distance, spotLight.decay ); 16064 light.visible = ( light.color != vec3( 0.0 ) ); 16065 } else { 16066 light.color = vec3( 0.0 ); 16067 light.visible = false; 16068 } 16069 } 16070#endif 16071#if NUM_RECT_AREA_LIGHTS > 0 16072 struct RectAreaLight { 16073 vec3 color; 16074 vec3 position; 16075 vec3 halfWidth; 16076 vec3 halfHeight; 16077 }; 16078 uniform sampler2D ltc_1; uniform sampler2D ltc_2; 16079 uniform RectAreaLight rectAreaLights[ NUM_RECT_AREA_LIGHTS ]; 16080#endif 16081#if NUM_HEMI_LIGHTS > 0 16082 struct HemisphereLight { 16083 vec3 direction; 16084 vec3 skyColor; 16085 vec3 groundColor; 16086 }; 16087 uniform HemisphereLight hemisphereLights[ NUM_HEMI_LIGHTS ]; 16088 vec3 getHemisphereLightIrradiance( const in HemisphereLight hemiLight, const in vec3 normal ) { 16089 float dotNL = dot( normal, hemiLight.direction ); 16090 float hemiDiffuseWeight = 0.5 * dotNL + 0.5; 16091 vec3 irradiance = mix( hemiLight.groundColor, hemiLight.skyColor, hemiDiffuseWeight ); 16092 return irradiance; 16093 } 16094#endif 16095#include <lightprobes_pars_fragment>`, ix = `#ifdef USE_ENVMAP 16096 vec3 getIBLIrradiance( const in vec3 normal ) { 16097 #ifdef ENVMAP_TYPE_CUBE_UV 16098 vec3 worldNormal = inverseTransformDirection( normal, viewMatrix ); 16099 vec4 envMapColor = textureCubeUV( envMap, envMapRotation * worldNormal, 1.0 ); 16100 return PI * envMapColor.rgb * envMapIntensity; 16101 #else 16102 return vec3( 0.0 ); 16103 #endif 16104 } 16105 vec3 getIBLRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness ) { 16106 #ifdef ENVMAP_TYPE_CUBE_UV 16107 vec3 reflectVec = reflect( - viewDir, normal ); 16108 reflectVec = normalize( mix( reflectVec, normal, pow4( roughness ) ) ); 16109 reflectVec = inverseTransformDirection( reflectVec, viewMatrix ); 16110 vec4 envMapColor = textureCubeUV( envMap, envMapRotation * reflectVec, roughness ); 16111 return envMapColor.rgb * envMapIntensity; 16112 #else 16113 return vec3( 0.0 ); 16114 #endif 16115 } 16116 #ifdef USE_ANISOTROPY 16117 vec3 getIBLAnisotropyRadiance( const in vec3 viewDir, const in vec3 normal, const in float roughness, const in vec3 bitangent, const in float anisotropy ) { 16118 #ifdef ENVMAP_TYPE_CUBE_UV 16119 vec3 bentNormal = cross( bitangent, viewDir ); 16120 bentNormal = normalize( cross( bentNormal, bitangent ) ); 16121 bentNormal = normalize( mix( bentNormal, normal, pow2( pow2( 1.0 - anisotropy * ( 1.0 - roughness ) ) ) ) ); 16122 return getIBLRadiance( viewDir, bentNormal, roughness ); 16123 #else 16124 return vec3( 0.0 ); 16125 #endif 16126 } 16127 #endif 16128#endif`, rx = `ToonMaterial material; 16129material.diffuseColor = diffuseColor.rgb;`, sx = `varying vec3 vViewPosition; 16130struct ToonMaterial { 16131 vec3 diffuseColor; 16132}; 16133void RE_Direct_Toon( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { 16134 vec3 irradiance = getGradientIrradiance( geometryNormal, directLight.direction ) * directLight.color; 16135 reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); 16136} 16137void RE_IndirectDiffuse_Toon( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in ToonMaterial material, inout ReflectedLight reflectedLight ) { 16138 reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); 16139} 16140#define RE_Direct RE_Direct_Toon 16141#define RE_IndirectDiffuse RE_IndirectDiffuse_Toon`, ax = `BlinnPhongMaterial material; 16142material.diffuseColor = diffuseColor.rgb; 16143material.specularColor = specular; 16144material.specularShininess = shininess; 16145material.specularStrength = specularStrength;`, ox = `varying vec3 vViewPosition; 16146struct BlinnPhongMaterial { 16147 vec3 diffuseColor; 16148 vec3 specularColor; 16149 float specularShininess; 16150 float specularStrength; 16151}; 16152void RE_Direct_BlinnPhong( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) {
16153 float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); 16154 vec3 irradiance = dotNL * directLight.color; 16155 reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); 16156 reflectedLight.directSpecular += irradiance * BRDF_BlinnPhong( directLight.direction, geometryViewDir, geometryNormal, material.specularColor, material.specularShininess ) * material.specularStrength; 16157} 16158void RE_IndirectDiffuse_BlinnPhong( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in BlinnPhongMaterial material, inout ReflectedLight reflectedLight ) { 16159 reflectedLight.indirectDiffuse += irradiance * BRDF_Lambert( material.diffuseColor ); 16160} 16161#define RE_Direct RE_Direct_BlinnPhong 16162#define RE_IndirectDiffuse RE_IndirectDiffuse_BlinnPhong`, lx = `PhysicalMaterial material; 16163material.diffuseColor = diffuseColor.rgb; 16164material.diffuseContribution = diffuseColor.rgb * ( 1.0 - metalnessFactor ); 16165material.metalness = metalnessFactor; 16166vec3 dxy = max( abs( dFdx( nonPerturbedNormal ) ), abs( dFdy( nonPerturbedNormal ) ) ); 16167float geometryRoughness = max( max( dxy.x, dxy.y ), dxy.z ); 16168material.roughness = max( roughnessFactor, 0.0525 );material.roughness += geometryRoughness; 16169material.roughness = min( material.roughness, 1.0 ); 16170#ifdef IOR 16171 material.ior = ior; 16172 #ifdef USE_SPECULAR 16173 float specularIntensityFactor = specularIntensity; 16174 vec3 specularColorFactor = specularColor; 16175 #ifdef USE_SPECULAR_COLORMAP 16176 specularColorFactor *= texture2D( specularColorMap, vSpecularColorMapUv ).rgb; 16177 #endif 16178 #ifdef USE_SPECULAR_INTENSITYMAP 16179 specularIntensityFactor *= texture2D( specularIntensityMap, vSpecularIntensityMapUv ).a; 16180 #endif 16181 material.specularF90 = mix( specularIntensityFactor, 1.0, metalnessFactor ); 16182 #else 16183 float specularIntensityFactor = 1.0; 16184 vec3 specularColorFactor = vec3( 1.0 ); 16185 material.specularF90 = 1.0; 16186 #endif 16187 material.specularColor = min( pow2( ( material.ior - 1.0 ) / ( material.ior + 1.0 ) ) * specularColorFactor, vec3( 1.0 ) ) * specularIntensityFactor; 16188 material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); 16189#else 16190 material.specularColor = vec3( 0.04 ); 16191 material.specularColorBlended = mix( material.specularColor, diffuseColor.rgb, metalnessFactor ); 16192 material.specularF90 = 1.0; 16193#endif 16194#ifdef USE_CLEARCOAT 16195 material.clearcoat = clearcoat; 16196 material.clearcoatRoughness = clearcoatRoughness; 16197 material.clearcoatF0 = vec3( 0.04 ); 16198 material.clearcoatF90 = 1.0; 16199 #ifdef USE_CLEARCOATMAP 16200 material.clearcoat *= texture2D( clearcoatMap, vClearcoatMapUv ).x; 16201 #endif 16202 #ifdef USE_CLEARCOAT_ROUGHNESSMAP 16203 material.clearcoatRoughness *= texture2D( clearcoatRoughnessMap, vClearcoatRoughnessMapUv ).y; 16204 #endif 16205 material.clearcoat = saturate( material.clearcoat ); material.clearcoatRoughness = max( material.clearcoatRoughness, 0.0525 ); 16206 material.clearcoatRoughness += geometryRoughness; 16207 material.clearcoatRoughness = min( material.clearcoatRoughness, 1.0 ); 16208#endif 16209#ifdef USE_DISPERSION 16210 material.dispersion = dispersion; 16211#endif 16212#ifdef USE_IRIDESCENCE 16213 material.iridescence = iridescence; 16214 material.iridescenceIOR = iridescenceIOR; 16215 #ifdef USE_IRIDESCENCEMAP 16216 material.iridescence *= texture2D( iridescenceMap, vIridescenceMapUv ).r; 16217 #endif 16218 #ifdef USE_IRIDESCENCE_THICKNESSMAP 16219 material.iridescenceThickness = (iridescenceThicknessMaximum - iridescenceThicknessMinimum) * texture2D( iridescenceThicknessMap, vIridescenceThicknessMapUv ).g + iridescenceThicknessMinimum; 16220 #else 16221 material.iridescenceThickness = iridescenceThicknessMaximum; 16222 #endif 16223#endif 16224#ifdef USE_SHEEN 16225 material.sheenColor = sheenColor; 16226 #ifdef USE_SHEEN_COLORMAP 16227 material.sheenColor *= texture2D( sheenColorMap, vSheenColorMapUv ).rgb; 16228 #endif 16229 material.sheenRoughness = clamp( sheenRoughness, 0.0001, 1.0 ); 16230 #ifdef USE_SHEEN_ROUGHNESSMAP 16231 material.sheenRoughness *= texture2D( sheenRoughnessMap, vSheenRoughnessMapUv ).a; 16232 #endif 16233#endif 16234#ifdef USE_ANISOTROPY 16235 #ifdef USE_ANISOTROPYMAP 16236 mat2 anisotropyMat = mat2( anisotropyVector.x, anisotropyVector.y, - anisotropyVector.y, anisotropyVector.x ); 16237 vec3 anisotropyPolar = texture2D( anisotropyMap, vAnisotropyMapUv ).rgb; 16238 vec2 anisotropyV = anisotropyMat * normalize( 2.0 * anisotropyPolar.rg - vec2( 1.0 ) ) * anisotropyPolar.b; 16239 #else 16240 vec2 anisotropyV = anisotropyVector; 16241 #endif 16242 material.anisotropy = length( anisotropyV ); 16243 if( material.anisotropy == 0.0 ) { 16244 anisotropyV = vec2( 1.0, 0.0 ); 16245 } else { 16246 anisotropyV /= material.anisotropy; 16247 material.anisotropy = saturate( material.anisotropy ); 16248 } 16249 material.alphaT = mix( pow2( material.roughness ), 1.0, pow2( material.anisotropy ) );
16250 material.anisotropyT = tbn[ 0 ] * anisotropyV.x + tbn[ 1 ] * anisotropyV.y; 16251 material.anisotropyB = tbn[ 1 ] * anisotropyV.x - tbn[ 0 ] * anisotropyV.y; 16252#endif`, cx = `uniform sampler2D dfgLUT; 16253struct PhysicalMaterial { 16254 vec3 diffuseColor; 16255 vec3 diffuseContribution; 16256 vec3 specularColor; 16257 vec3 specularColorBlended; 16258 float roughness; 16259 float metalness; 16260 float specularF90; 16261 float dispersion; 16262 #ifdef USE_CLEARCOAT 16263 float clearcoat; 16264 float clearcoatRoughness; 16265 vec3 clearcoatF0; 16266 float clearcoatF90; 16267 #endif 16268 #ifdef USE_IRIDESCENCE 16269 float iridescence; 16270 float iridescenceIOR; 16271 float iridescenceThickness; 16272 vec3 iridescenceFresnel; 16273 vec3 iridescenceF0; 16274 vec3 iridescenceFresnelDielectric; 16275 vec3 iridescenceFresnelMetallic; 16276 #endif 16277 #ifdef USE_SHEEN 16278 vec3 sheenColor; 16279 float sheenRoughness; 16280 #endif 16281 #ifdef IOR 16282 float ior; 16283 #endif 16284 #ifdef USE_TRANSMISSION 16285 float transmission; 16286 float transmissionAlpha; 16287 float thickness; 16288 float attenuationDistance; 16289 vec3 attenuationColor; 16290 #endif 16291 #ifdef USE_ANISOTROPY 16292 float anisotropy; 16293 float alphaT; 16294 vec3 anisotropyT; 16295 vec3 anisotropyB; 16296 #endif 16297}; 16298vec3 clearcoatSpecularDirect = vec3( 0.0 ); 16299vec3 clearcoatSpecularIndirect = vec3( 0.0 ); 16300vec3 sheenSpecularDirect = vec3( 0.0 ); 16301vec3 sheenSpecularIndirect = vec3(0.0 ); 16302vec3 Schlick_to_F0( const in vec3 f, const in float f90, const in float dotVH ) { 16303 float x = clamp( 1.0 - dotVH, 0.0, 1.0 ); 16304 float x2 = x * x; 16305 float x5 = clamp( x * x2 * x2, 0.0, 0.9999 ); 16306 return ( f - vec3( f90 ) * x5 ) / ( 1.0 - x5 ); 16307} 16308float V_GGX_SmithCorrelated( const in float alpha, const in float dotNL, const in float dotNV ) { 16309 float a2 = pow2( alpha ); 16310 float gv = dotNL * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNV ) ); 16311 float gl = dotNV * sqrt( a2 + ( 1.0 - a2 ) * pow2( dotNL ) ); 16312 return 0.5 / max( gv + gl, EPSILON ); 16313} 16314float D_GGX( const in float alpha, const in float dotNH ) { 16315 float a2 = pow2( alpha ); 16316 float denom = pow2( dotNH ) * ( a2 - 1.0 ) + 1.0; 16317 return RECIPROCAL_PI * a2 / pow2( denom ); 16318} 16319#ifdef USE_ANISOTROPY 16320 float V_GGX_SmithCorrelated_Anisotropic( const in float alphaT, const in float alphaB, const in float dotTV, const in float dotBV, const in float dotTL, const in float dotBL, const in float dotNV, const in float dotNL ) { 16321 float gv = dotNL * length( vec3( alphaT * dotTV, alphaB * dotBV, dotNV ) ); 16322 float gl = dotNV * length( vec3( alphaT * dotTL, alphaB * dotBL, dotNL ) ); 16323 return 0.5 / max( gv + gl, EPSILON )
vendor: 7,372 bytes, lines 16323-16482
16323; 16324 } 16325 float D_GGX_Anisotropic( const in float alphaT, const in float alphaB, const in float dotNH, const in float dotTH, const in float dotBH ) { 16326 float a2 = alphaT * alphaB; 16327 highp vec3 v = vec3( alphaB * dotTH, alphaT * dotBH, a2 * dotNH ); 16328 highp float v2 = dot( v, v ); 16329 float w2 = a2 / v2; 16330 return RECIPROCAL_PI * a2 * pow2 ( w2 ); 16331 } 16332#endif 16333#ifdef USE_CLEARCOAT 16334 vec3 BRDF_GGX_Clearcoat( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material) { 16335 vec3 f0 = material.clearcoatF0; 16336 float f90 = material.clearcoatF90; 16337 float roughness = material.clearcoatRoughness; 16338 float alpha = pow2( roughness ); 16339 vec3 halfDir = normalize( lightDir + viewDir ); 16340 float dotNL = saturate( dot( normal, lightDir ) ); 16341 float dotNV = saturate( dot( normal, viewDir ) ); 16342 float dotNH = saturate( dot( normal, halfDir ) ); 16343 float dotVH = saturate( dot( viewDir, halfDir ) ); 16344 vec3 F = F_Schlick( f0, f90, dotVH ); 16345 float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); 16346 float D = D_GGX( alpha, dotNH ); 16347 return F * ( V * D ); 16348 } 16349#endif 16350vec3 BRDF_GGX( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { 16351 vec3 f0 = material.specularColorBlended; 16352 float f90 = material.specularF90; 16353 float roughness = material.roughness; 16354 float alpha = pow2( roughness ); 16355 vec3 halfDir = normalize( lightDir + viewDir ); 16356 float dotNL = saturate( dot( normal, lightDir ) ); 16357 float dotNV = saturate( dot( normal, viewDir ) ); 16358 float dotNH = saturate( dot( normal, halfDir ) ); 16359 float dotVH = saturate( dot( viewDir, halfDir ) ); 16360 vec3 F = F_Schlick( f0, f90, dotVH ); 16361 #ifdef USE_IRIDESCENCE 16362 F = mix( F, material.iridescenceFresnel, material.iridescence ); 16363 #endif 16364 #ifdef USE_ANISOTROPY 16365 float dotTL = dot( material.anisotropyT, lightDir ); 16366 float dotTV = dot( material.anisotropyT, viewDir ); 16367 float dotTH = dot( material.anisotropyT, halfDir ); 16368 float dotBL = dot( material.anisotropyB, lightDir ); 16369 float dotBV = dot( material.anisotropyB, viewDir ); 16370 float dotBH = dot( material.anisotropyB, halfDir ); 16371 float V = V_GGX_SmithCorrelated_Anisotropic( material.alphaT, alpha, dotTV, dotBV, dotTL, dotBL, dotNV, dotNL ); 16372 float D = D_GGX_Anisotropic( material.alphaT, alpha, dotNH, dotTH, dotBH ); 16373 #else 16374 float V = V_GGX_SmithCorrelated( alpha, dotNL, dotNV ); 16375 float D = D_GGX( alpha, dotNH ); 16376 #endif 16377 return F * ( V * D ); 16378} 16379vec2 LTC_Uv( const in vec3 N, const in vec3 V, const in float roughness ) { 16380 const float LUT_SIZE = 64.0; 16381 const float LUT_SCALE = ( LUT_SIZE - 1.0 ) / LUT_SIZE; 16382 const float LUT_BIAS = 0.5 / LUT_SIZE; 16383 float dotNV = saturate( dot( N, V ) ); 16384 vec2 uv = vec2( roughness, sqrt( 1.0 - dotNV ) ); 16385 uv = uv * LUT_SCALE + LUT_BIAS; 16386 return uv; 16387} 16388float LTC_ClippedSphereFormFactor( const in vec3 f ) { 16389 float l = length( f ); 16390 return max( ( l * l + f.z ) / ( l + 1.0 ), 0.0 ); 16391} 16392vec3 LTC_EdgeVectorFormFactor( const in vec3 v1, const in vec3 v2 ) { 16393 float x = dot( v1, v2 ); 16394 float y = abs( x ); 16395 float a = 0.8543985 + ( 0.4965155 + 0.0145206 * y ) * y; 16396 float b = 3.4175940 + ( 4.1616724 + y ) * y; 16397 float v = a / b; 16398 float theta_sintheta = ( x > 0.0 ) ? v : 0.5 * inversesqrt( max( 1.0 - x * x, 1e-7 ) ) - v; 16399 return cross( v1, v2 ) * theta_sintheta; 16400} 16401vec3 LTC_Evaluate( const in vec3 N, const in vec3 V, const in vec3 P, const in mat3 mInv, const in vec3 rectCoords[ 4 ] ) { 16402 vec3 v1 = rectCoords[ 1 ] - rectCoords[ 0 ]; 16403 vec3 v2 = rectCoords[ 3 ] - rectCoords[ 0 ]; 16404 vec3 lightNormal = cross( v1, v2 ); 16405 if( dot( lightNormal, P - rectCoords[ 0 ] ) < 0.0 ) return vec3( 0.0 ); 16406 vec3 T1, T2; 16407 T1 = normalize( V - N * dot( V, N ) ); 16408 T2 = - cross( N, T1 ); 16409 mat3 mat = mInv * transpose( mat3( T1, T2, N ) ); 16410 vec3 coords[ 4 ]; 16411 coords[ 0 ] = mat * ( rectCoords[ 0 ] - P ); 16412 coords[ 1 ] = mat * ( rectCoords[ 1 ] - P ); 16413 coords[ 2 ] = mat * ( rectCoords[ 2 ] - P ); 16414 coords[ 3 ] = mat * ( rectCoords[ 3 ] - P ); 16415 coords[ 0 ] = normalize( coords[ 0 ] ); 16416 coords[ 1 ] = normalize( coords[ 1 ] ); 16417 coords[ 2 ] = normalize( coords[ 2 ] ); 16418 coords[ 3 ] = normalize( coords[ 3 ] ); 16419 vec3 vectorFormFactor = vec3( 0.0 ); 16420 vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 0 ], coords[ 1 ] ); 16421 vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 1 ], coords[ 2 ] ); 16422 vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 2 ], coords[ 3 ] ); 16423 vectorFormFactor += LTC_EdgeVectorFormFactor( coords[ 3 ], coords[ 0 ] ); 16424 float result = LTC_ClippedSphereFormFactor( vectorFormFactor ); 16425 return vec3( result ); 16426} 16427#if defined( USE_SHEEN ) 16428float D_Charlie( float roughness, float dotNH ) { 16429 float alpha = pow2( roughness ); 16430 float invAlpha = 1.0 / alpha; 16431 float cos2h = dotNH * dotNH; 16432 float sin2h = max( 1.0 - cos2h, 0.0078125 ); 16433 return ( 2.0 + invAlpha ) * pow( sin2h, invAlpha * 0.5 ) / ( 2.0 * PI ); 16434} 16435float V_Neubelt( float dotNV, float dotNL ) { 16436 return saturate( 1.0 / ( 4.0 * ( dotNL + dotNV - dotNL * dotNV ) ) ); 16437} 16438vec3 BRDF_Sheen( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, vec3 sheenColor, const in float sheenRoughness ) { 16439 vec3 halfDir = normalize( lightDir + viewDir ); 16440 float dotNL = saturate( dot( normal, lightDir ) ); 16441 float dotNV = saturate( dot( normal, viewDir ) ); 16442 float dotNH = saturate( dot( normal, halfDir ) ); 16443 float D = D_Charlie( sheenRoughness, dotNH ); 16444 float V = V_Neubelt( dotNV, dotNL ); 16445 return sheenColor * ( D * V ); 16446} 16447#endif 16448float IBLSheenBRDF( const in vec3 normal, const in vec3 viewDir, const in float roughness ) { 16449 float dotNV = saturate( dot( normal, viewDir ) ); 16450 float r2 = roughness * roughness; 16451 float rInv = 1.0 / ( roughness + 0.1 ); 16452 float a = -1.9362 + 1.0678 * roughness + 0.4573 * r2 - 0.8469 * rInv; 16453 float b = -0.6014 + 0.5538 * roughness - 0.4670 * r2 - 0.1255 * rInv; 16454 float DG = exp( a * dotNV + b ); 16455 return saturate( DG ); 16456} 16457vec3 EnvironmentBRDF( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness ) { 16458 float dotNV = saturate( dot( normal, viewDir ) ); 16459 vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; 16460 return specularColor * fab.x + specularF90 * fab.y; 16461} 16462#ifdef USE_IRIDESCENCE 16463void computeMultiscatteringIridescence( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float iridescence, const in vec3 iridescenceF0, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { 16464#else 16465void computeMultiscattering( const in vec3 normal, const in vec3 viewDir, const in vec3 specularColor, const in float specularF90, const in float roughness, inout vec3 singleScatter, inout vec3 multiScatter ) { 16466#endif 16467 float dotNV = saturate( dot( normal, viewDir ) ); 16468 vec2 fab = texture2D( dfgLUT, vec2( roughness, dotNV ) ).rg; 16469 #ifdef USE_IRIDESCENCE 16470 vec3 Fr = mix( specularColor, iridescenceF0, iridescence ); 16471 #else 16472 vec3 Fr = specularColor; 16473 #endif 16474 vec3 FssEss = Fr * fab.x + specularF90 * fab.y; 16475 float Ess = fab.x + fab.y; 16476 float Ems = 1.0 - Ess; 16477 vec3 Favg = Fr + ( 1.0 - Fr ) * 0.047619; vec3 Fms = FssEss * Favg / ( 1.0 - Ems * Favg ); 16478 singleScatter += FssEss; 16479 multiScatter += Fms * Ems; 16480} 16481vec3 BRDF_GGX_Multiscatter( const in vec3 lightDir, const in vec3 viewDir, const in vec3 normal, const in PhysicalMaterial material ) { 16482 vec3 singleScatter = BRDF_GGX( lightDir, viewDir, normal, material );
vendor: 8,354 bytes, lines 16483-16612
16483 float dotNL = saturate( dot( normal, lightDir ) ); 16484 float dotNV = saturate( dot( normal, viewDir ) ); 16485 vec2 dfgV = texture2D( dfgLUT, vec2( material.roughness, dotNV ) ).rg; 16486 vec2 dfgL = texture2D( dfgLUT, vec2( material.roughness, dotNL ) ).rg; 16487 vec3 FssEss_V = material.specularColorBlended * dfgV.x + material.specularF90 * dfgV.y; 16488 vec3 FssEss_L = material.specularColorBlended * dfgL.x + material.specularF90 * dfgL.y; 16489 float Ess_V = dfgV.x + dfgV.y; 16490 float Ess_L = dfgL.x + dfgL.y; 16491 float Ems_V = 1.0 - Ess_V; 16492 float Ems_L = 1.0 - Ess_L; 16493 vec3 Favg = material.specularColorBlended + ( 1.0 - material.specularColorBlended ) * 0.047619; 16494 vec3 Fms = FssEss_V * FssEss_L * Favg / ( 1.0 - Ems_V * Ems_L * Favg + EPSILON ); 16495 float compensationFactor = Ems_V * Ems_L; 16496 vec3 multiScatter = Fms * compensationFactor; 16497 return singleScatter + multiScatter; 16498} 16499#if NUM_RECT_AREA_LIGHTS > 0 16500 void RE_Direct_RectArea_Physical( const in RectAreaLight rectAreaLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { 16501 vec3 normal = geometryNormal; 16502 vec3 viewDir = geometryViewDir; 16503 vec3 position = geometryPosition; 16504 vec3 lightPos = rectAreaLight.position; 16505 vec3 halfWidth = rectAreaLight.halfWidth; 16506 vec3 halfHeight = rectAreaLight.halfHeight; 16507 vec3 lightColor = rectAreaLight.color; 16508 float roughness = material.roughness; 16509 vec3 rectCoords[ 4 ]; 16510 rectCoords[ 0 ] = lightPos + halfWidth - halfHeight; rectCoords[ 1 ] = lightPos - halfWidth - halfHeight; 16511 rectCoords[ 2 ] = lightPos - halfWidth + halfHeight; 16512 rectCoords[ 3 ] = lightPos + halfWidth + halfHeight; 16513 vec2 uv = LTC_Uv( normal, viewDir, roughness ); 16514 vec4 t1 = texture2D( ltc_1, uv ); 16515 vec4 t2 = texture2D( ltc_2, uv ); 16516 mat3 mInv = mat3( 16517 vec3( t1.x, 0, t1.y ), 16518 vec3( 0, 1, 0 ), 16519 vec3( t1.z, 0, t1.w ) 16520 ); 16521 vec3 fresnel = ( material.specularColorBlended * t2.x + ( material.specularF90 - material.specularColorBlended ) * t2.y ); 16522 reflectedLight.directSpecular += lightColor * fresnel * LTC_Evaluate( normal, viewDir, position, mInv, rectCoords ); 16523 reflectedLight.directDiffuse += lightColor * material.diffuseContribution * LTC_Evaluate( normal, viewDir, position, mat3( 1.0 ), rectCoords ); 16524 #ifdef USE_CLEARCOAT 16525 vec3 Ncc = geometryClearcoatNormal; 16526 vec2 uvClearcoat = LTC_Uv( Ncc, viewDir, material.clearcoatRoughness ); 16527 vec4 t1Clearcoat = texture2D( ltc_1, uvClearcoat ); 16528 vec4 t2Clearcoat = texture2D( ltc_2, uvClearcoat ); 16529 mat3 mInvClearcoat = mat3( 16530 vec3( t1Clearcoat.x, 0, t1Clearcoat.y ), 16531 vec3( 0, 1, 0 ), 16532 vec3( t1Clearcoat.z, 0, t1Clearcoat.w ) 16533 ); 16534 vec3 fresnelClearcoat = material.clearcoatF0 * t2Clearcoat.x + ( material.clearcoatF90 - material.clearcoatF0 ) * t2Clearcoat.y; 16535 clearcoatSpecularDirect += lightColor * fresnelClearcoat * LTC_Evaluate( Ncc, viewDir, position, mInvClearcoat, rectCoords ); 16536 #endif 16537 } 16538#endif 16539void RE_Direct_Physical( const in IncidentLight directLight, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { 16540 float dotNL = saturate( dot( geometryNormal, directLight.direction ) ); 16541 vec3 irradiance = dotNL * directLight.color; 16542 #ifdef USE_CLEARCOAT 16543 float dotNLcc = saturate( dot( geometryClearcoatNormal, directLight.direction ) ); 16544 vec3 ccIrradiance = dotNLcc * directLight.color; 16545 clearcoatSpecularDirect += ccIrradiance * BRDF_GGX_Clearcoat( directLight.direction, geometryViewDir, geometryClearcoatNormal, material ); 16546 #endif 16547 #ifdef USE_SHEEN 16548 16549 sheenSpecularDirect += irradiance * BRDF_Sheen( directLight.direction, geometryViewDir, geometryNormal, material.sheenColor, material.sheenRoughness ); 16550 16551 float sheenAlbedoV = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); 16552 float sheenAlbedoL = IBLSheenBRDF( geometryNormal, directLight.direction, material.sheenRoughness ); 16553 16554 float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * max( sheenAlbedoV, sheenAlbedoL ); 16555 16556 irradiance *= sheenEnergyComp; 16557 16558 #endif 16559 reflectedLight.directSpecular += irradiance * BRDF_GGX_Multiscatter( directLight.direction, geometryViewDir, geometryNormal, material ); 16560 reflectedLight.directDiffuse += irradiance * BRDF_Lambert( material.diffuseContribution ); 16561} 16562void RE_IndirectDiffuse_Physical( const in vec3 irradiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight ) { 16563 vec3 diffuse = irradiance * BRDF_Lambert( material.diffuseContribution ); 16564 #ifdef USE_SHEEN 16565 float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); 16566 float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; 16567 diffuse *= sheenEnergyComp; 16568 #endif 16569 reflectedLight.indirectDiffuse += diffuse; 16570} 16571void RE_IndirectSpecular_Physical( const in vec3 radiance, const in vec3 irradiance, const in vec3 clearcoatRadiance, const in vec3 geometryPosition, const in vec3 geometryNormal, const in vec3 geometryViewDir, const in vec3 geometryClearcoatNormal, const in PhysicalMaterial material, inout ReflectedLight reflectedLight) { 16572 #ifdef USE_CLEARCOAT 16573 clearcoatSpecularIndirect += clearcoatRadiance * EnvironmentBRDF( geometryClearcoatNormal, geometryViewDir, material.clearcoatF0, material.clearcoatF90, material.clearcoatRoughness ); 16574 #endif 16575 #ifdef USE_SHEEN 16576 sheenSpecularIndirect += irradiance * material.sheenColor * IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ) * RECIPROCAL_PI; 16577 #endif 16578 vec3 singleScatteringDielectric = vec3( 0.0 ); 16579 vec3 multiScatteringDielectric = vec3( 0.0 ); 16580 vec3 singleScatteringMetallic = vec3( 0.0 ); 16581 vec3 multiScatteringMetallic = vec3( 0.0 ); 16582 #ifdef USE_IRIDESCENCE 16583 computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.iridescence, material.iridescenceFresnelDielectric, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); 16584 computeMultiscatteringIridescence( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.iridescence, material.iridescenceFresnelMetallic, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); 16585 #else 16586 computeMultiscattering( geometryNormal, geometryViewDir, material.specularColor, material.specularF90, material.roughness, singleScatteringDielectric, multiScatteringDielectric ); 16587 computeMultiscattering( geometryNormal, geometryViewDir, material.diffuseColor, material.specularF90, material.roughness, singleScatteringMetallic, multiScatteringMetallic ); 16588 #endif 16589 vec3 singleScattering = mix( singleScatteringDielectric, singleScatteringMetallic, material.metalness ); 16590 vec3 multiScattering = mix( multiScatteringDielectric, multiScatteringMetallic, material.metalness ); 16591 vec3 totalScatteringDielectric = singleScatteringDielectric + multiScatteringDielectric; 16592 vec3 diffuse = material.diffuseContribution * ( 1.0 - totalScatteringDielectric ); 16593 vec3 cosineWeightedIrradiance = irradiance * RECIPROCAL_PI; 16594 vec3 indirectSpecular = radiance * singleScattering; 16595 indirectSpecular += multiScattering * cosineWeightedIrradiance; 16596 vec3 indirectDiffuse = diffuse * cosineWeightedIrradiance; 16597 #ifdef USE_SHEEN 16598 float sheenAlbedo = IBLSheenBRDF( geometryNormal, geometryViewDir, material.sheenRoughness ); 16599 float sheenEnergyComp = 1.0 - max3( material.sheenColor ) * sheenAlbedo; 16600 indirectSpecular *= sheenEnergyComp; 16601 indirectDiffuse *= sheenEnergyComp; 16602 #endif 16603 reflectedLight.indirectSpecular += indirectSpecular; 16604 reflectedLight.indirectDiffuse += indirectDiffuse; 16605} 16606#define RE_Direct RE_Direct_Physical 16607#define RE_Direct_RectArea RE_Direct_RectArea_Physical 16608#define RE_IndirectDiffuse RE_IndirectDiffuse_Physical 16609#define RE_IndirectSpecular RE_IndirectSpecular_Physical 16610float computeSpecularOcclusion( const in float dotNV, const in float ambientOcclusion, const in float roughness ) { 16611 return saturate( pow( dotNV + ambientOcclusion, exp2( - 16.0 * roughness - 1.0 ) ) - 1.0 + ambientOcclusion ); 16612}`,
16612 ux = ` 16613vec3 geometryPosition = - vViewPosition; 16614vec3 geometryNormal = normal; 16615vec3 geometryViewDir = ( isOrthographic ) ? vec3( 0, 0, 1 ) : normalize( vViewPosition ); 16616vec3 geometryClearcoatNormal = vec3( 0.0 ); 16617#ifdef USE_CLEARCOAT 16618 geometryClearcoatNormal = clearcoatNormal; 16619#endif 16620#ifdef USE_IRIDESCENCE 16621 float dotNVi = saturate( dot( normal, geometryViewDir ) ); 16622 if ( material.iridescenceThickness == 0.0 ) { 16623 material.iridescence = 0.0; 16624 } else { 16625 material.iridescence = saturate( material.iridescence ); 16626 } 16627 if ( material.iridescence > 0.0 ) { 16628 material.iridescenceFresnelDielectric = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.specularColor ); 16629 material.iridescenceFresnelMetallic = evalIridescence( 1.0, material.iridescenceIOR, dotNVi, material.iridescenceThickness, material.diffuseColor ); 16630 material.iridescenceFresnel = mix( material.iridescenceFresnelDielectric, material.iridescenceFresnelMetallic, material.metalness ); 16631 material.iridescenceF0 = Schlick_to_F0( material.iridescenceFresnel, 1.0, dotNVi ); 16632 } 16633#endif 16634IncidentLight directLight; 16635#if ( NUM_POINT_LIGHTS > 0 ) && defined( RE_Direct ) 16636 PointLight pointLight; 16637 #if defined( USE_SHADOWMAP ) && NUM_POINT_LIGHT_SHADOWS > 0 16638 PointLightShadow pointLightShadow; 16639 #endif 16640 #pragma unroll_loop_start 16641 for ( int i = 0; i < NUM_POINT_LIGHTS; i ++ ) { 16642 pointLight = pointLights[ i ]; 16643 getPointLightInfo( pointLight, geometryPosition, directLight ); 16644 #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_POINT_LIGHT_SHADOWS ) && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) 16645 pointLightShadow = pointLightShadows[ i ]; 16646 directLight.color *= ( directLight.visible && receiveShadow ) ? getPointShadow( pointShadowMap[ i ], pointLightShadow.shadowMapSize, pointLightShadow.shadowIntensity, pointLightShadow.shadowBias, pointLightShadow.shadowRadius, vPointShadowCoord[ i ], pointLightShadow.shadowCameraNear, pointLightShadow.shadowCameraFar ) : 1.0; 16647 #endif 16648 RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); 16649 } 16650 #pragma unroll_loop_end 16651#endif 16652#if ( NUM_SPOT_LIGHTS > 0 ) && defined( RE_Direct ) 16653 SpotLight spotLight; 16654 vec4 spotColor; 16655 vec3 spotLightCoord; 16656 bool inSpotLightMap; 16657 #if defined( USE_SHADOWMAP ) && NUM_SPOT_LIGHT_SHADOWS > 0 16658 SpotLightShadow spotLightShadow; 16659 #endif 16660 #pragma unroll_loop_start 16661 for ( int i = 0; i < NUM_SPOT_LIGHTS; i ++ ) { 16662 spotLight = spotLights[ i ]; 16663 getSpotLightInfo( spotLight, geometryPosition, directLight ); 16664 #if ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) 16665 #define SPOT_LIGHT_MAP_INDEX UNROLLED_LOOP_INDEX 16666 #elif ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) 16667 #define SPOT_LIGHT_MAP_INDEX NUM_SPOT_LIGHT_MAPS 16668 #else 16669 #define SPOT_LIGHT_MAP_INDEX ( UNROLLED_LOOP_INDEX - NUM_SPOT_LIGHT_SHADOWS + NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS ) 16670 #endif 16671 #if ( SPOT_LIGHT_MAP_INDEX < NUM_SPOT_LIGHT_MAPS ) 16672 spotLightCoord = vSpotLightCoord[ i ].xyz / vSpotLightCoord[ i ].w; 16673 inSpotLightMap = all( lessThan( abs( spotLightCoord * 2. - 1. ), vec3( 1.0 ) ) ); 16674 spotColor = texture2D( spotLightMap[ SPOT_LIGHT_MAP_INDEX ], spotLightCoord.xy ); 16675 directLight.color = inSpotLightMap ? directLight.color * spotColor.rgb : directLight.color; 16676 #endif 16677 #undef SPOT_LIGHT_MAP_INDEX 16678 #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) 16679 spotLightShadow = spotLightShadows[ i ]; 16680 directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( spotShadowMap[ i ], spotLightShadow.shadowMapSize, spotLightShadow.shadowIntensity, spotLightShadow.shadowBias, spotLightShadow.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; 16681 #endif 16682 RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); 16683 } 16684 #pragma unroll_loop_end 16685#endif 16686#if ( NUM_DIR_LIGHTS > 0 ) && defined( RE_Direct ) 16687 DirectionalLight directionalLight; 16688 #if defined( USE_SHADOWMAP ) && NUM_DIR_LIGHT_SHADOWS > 0 16689 DirectionalLightShadow directionalLightShadow; 16690 #endif 16691 #pragma unroll_loop_start 16692 for ( int i = 0; i < NUM_DIR_LIGHTS; i ++ ) { 16693 directionalLight = directionalLights[ i ]; 16694 getDirectionalLightInfo( directionalLight, directLight ); 16695 #if defined( USE_SHADOWMAP ) && ( UNROLLED_LOOP_INDEX < NUM_DIR_LIGHT_SHADOWS ) 16696 directionalLightShadow = directionalLightShadows[ i ]; 16697 directLight.color *= ( directLight.visible && receiveShadow ) ? getShadow( directionalShadowMap[ i ], directionalLightShadow.shadowMapSize, directionalLightShadow.shadowIntensity, directionalLightShadow.shadowBias, directionalLightShadow.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; 16698 #endif 16699 RE_Direct( directLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); 16700 } 16701 #pragma unroll_loop_end 16702#endif 16703#if ( NUM_RECT_AREA_LIGHTS > 0 ) && defined( RE_Direct_RectArea ) 16704 RectAreaLight rectAreaLight; 16705 #pragma unroll_loop_start 16706 for ( int i = 0; i < NUM_RECT_AREA_LIGHTS; i ++ ) { 16707 rectAreaLight = rectAreaLights[ i ]; 16708 RE_Direct_RectArea( rectAreaLight, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); 16709 } 16710 #pragma unroll_loop_end 16711#endif 16712#if defined( RE_IndirectDiffuse ) 16713 vec3 iblIrradiance = vec3( 0.0 ); 16714 vec3 irradiance = getAmbientLightIrradiance( ambientLightColor ); 16715 #if defined( USE_LIGHT_PROBES ) 16716 irradiance += getLightProbeIrradiance( lightProbe, geometryNormal ); 16717 #endif 16718 #if ( NUM_HEMI_LIGHTS > 0 ) 16719 #pragma unroll_loop_start 16720 for ( int i = 0; i < NUM_HEMI_LIGHTS; i ++ ) { 16721 irradiance += getHemisphereLightIrradiance( hemisphereLights[ i ], geometryNormal ); 16722 } 16723 #pragma unroll_loop_end 16724 #endif 16725 #ifdef USE_LIGHT_PROBES_GRID 16726 vec3 probeWorldPos = ( ( vec4( geometryPosition, 1.0 ) - viewMatrix[ 3 ] ) * viewMatrix ).xyz; 16727 vec3 probeWorldNormal = inverseTransformDirection( geometryNormal, viewMatrix ); 16728 irradiance += getLightProbeGridIrradiance( probeWorldPos, probeWorldNormal ); 16729 #endif 16730#endif 16731#if defined( RE_IndirectSpecular ) 16732 vec3 radiance = vec3( 0.0 ); 16733 vec3 clearcoatRadiance = vec3( 0.0 ); 16734#endif`, hx = `#if defined( RE_IndirectDiffuse ) 16735 #ifdef USE_LIGHTMAP 16736 vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); 16737 vec3 lightMapIrradiance = lightMapTexel.rgb * lightMapIntensity; 16738 irradiance += lightMapIrradiance; 16739 #endif 16740 #if defined( USE_ENVMAP ) && defined( ENVMAP_TYPE_CUBE_UV ) 16741 #if defined( STANDARD ) || defined( LAMBERT ) || defined( PHONG ) 16742 iblIrradiance += getIBLIrradiance( geometryNormal ); 16743 #endif 16744 #endif 16745#endif 16746#if defined( USE_ENVMAP ) && defined( RE_IndirectSpecular ) 16747 #ifdef USE_ANISOTROPY 16748 radiance += getIBLAnisotropyRadiance( geometryViewDir, geometryNormal, material.roughness, material.anisotropyB, material.anisotropy ); 16749 #else 16750 radiance += getIBLRadiance( geometryViewDir, geometryNormal, material.roughness ); 16751 #endif 16752 #ifdef USE_CLEARCOAT 16753 clearcoatRadiance += getIBLRadiance( geometryViewDir, geometryClearcoatNormal, material.clearcoatRoughness ); 16754 #endif 16755#endif`, dx = `#if defined( RE_IndirectDiffuse ) 16756 #if defined( LAMBERT ) || defined( PHONG ) 16757 irradiance += iblIrradiance; 16758 #endif 16759 RE_IndirectDiffuse( irradiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); 16760#endif 16761#if defined( RE_IndirectSpecular ) 16762 RE_IndirectSpecular( radiance, iblIrradiance, clearcoatRadiance, geometryPosition, geometryNormal, geometryViewDir, geometryClearcoatNormal, material, reflectedLight ); 16763#endif`, fx = `#ifdef USE_LIGHT_PROBES_GRID 16764uniform highp sampler3D probesSH; 16765uniform vec3 probesMin; 16766uniform vec3 probesMax; 16767uniform vec3 probesResolution; 16768vec3 getLightProbeGridIrradiance( vec3 worldPos, vec3 worldNormal ) { 16769 vec3 res = probesResolution; 16770 vec3 gridRange = probesMax - probesMin; 16771 vec3 resMinusOne = res - 1.0; 16772 vec3 probeSpacing = gridRange / resMinusOne; 16773 vec3 samplePos = worldPos + worldNormal * probeSpacing * 0.5; 16774 vec3 uvw = clamp( ( samplePos - probesMin ) / gridRange, 0.0, 1.0 ); 16775 uvw = uvw * resMinusOne / res + 0.5 / res; 16776 float nz = res.z; 16777 float paddedSlices = nz + 2.0; 16778 float atlasDepth = 7.0 * paddedSlices; 16779 float uvZBase = uvw.z * nz + 1.0; 16780 vec4 s0 = texture( probesSH, vec3( uvw.xy, ( uvZBase ) / atlasDepth ) ); 16781 vec4 s1 = texture( probesSH, vec3( uvw.xy, ( uvZBase + paddedSlices ) / atlasDepth ) ); 16782 vec4 s2 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 2.0 * paddedSlices ) / atlasDepth ) ); 16783 vec4 s3 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 3.0 * paddedSlices ) / atlasDepth ) ); 16784 vec4 s4 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 4.0 * paddedSlices ) / atlasDepth ) ); 16785 vec4 s5 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 5.0 * paddedSlices ) / atlasDepth ) ); 16786 vec4 s6 = texture( probesSH, vec3( uvw.xy, ( uvZBase + 6.0 * paddedSlices ) / atlasDepth ) ); 16787 vec3 c0 = s0.xyz; 16788 vec3 c1 = vec3( s0.w, s1.xy ); 16789 vec3 c2 = vec3( s1.zw, s2.x ); 16790 vec3 c3 = s2.yzw; 16791 vec3 c4 = s3.xyz; 16792 vec3 c5 = vec3( s3.w, s4.xy ); 16793 vec3 c6 = vec3( s4.zw, s5.x ); 16794 vec3 c7 = s5.yzw; 16795 vec3 c8 = s6.xyz; 16796 float x = worldNormal.x, y = worldNormal.y, z = worldNormal.z; 16797 vec3 result = c0 * 0.886227; 16798 result += c1 * 2.0 * 0.511664 * y; 16799 result += c2 * 2.0 * 0.511664 * z; 16800 result += c3 * 2.0 * 0.511664 * x; 16801 result += c4 * 2.0 * 0.429043 * x * y; 16802 result += c5 * 2.0 * 0.429043 * y * z; 16803 result += c6 * ( 0.743125 * z * z - 0.247708 ); 16804 result += c7 * 2.0 * 0.429043 * x * z; 16805 result += c8 * 0.429043 * ( x * x - y * y ); 16806 return max( result, vec3( 0.0 ) ); 16807} 16808#endif`, px = `#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) 16809 gl_FragDepth = vIsPerspective == 0.0 ? gl_FragCoord.z : log2( vFragDepth ) * logDepthBufFC * 0.5; 16810#endif`, mx = `#if defined( USE_LOGARITHMIC_DEPTH_BUFFER ) 16811 uniform float logDepthBufFC; 16812 varying float vFragDepth; 16813 varying float vIsPerspective; 16814#endif`, gx = `#ifdef USE_LOGARITHMIC_DEPTH_BUFFER 16815 varying float vFragDepth; 16816 varying float vIsPerspective; 16817#endif`, vx = `#ifdef USE_LOGARITHMIC_DEPTH_BUFFER 16818 vFragDepth = 1.0 + gl_Position.w; 16819 vIsPerspective = float( isPerspectiveMatrix( projectionMatrix ) ); 16820#endif`, _x = `#ifdef USE_MAP 16821 vec4 sampledDiffuseColor = texture2D( map, vMapUv ); 16822 #ifdef DECODE_VIDEO_TEXTURE 16823 sampledDiffuseColor = sRGBTransferEOTF( sampledDiffuseColor ); 16824 #endif 16825 diffuseColor *= sampledDiffuseColor; 16826#endif`, yx = `#ifdef USE_MAP 16827 uniform sampler2D map; 16828#endif`, xx = `#if defined( USE_MAP ) || defined( USE_ALPHAMAP ) 16829 #if defined( USE_POINTS_UV ) 16830 vec2 uv = vUv; 16831 #else 16832 vec2 uv = ( uvTransform * vec3( gl_PointCoord.x, 1.0 - gl_PointCoord.y, 1 ) ).xy; 16833 #endif 16834#endif 16835#ifdef USE_MAP 16836 diffuseColor *= texture2D( map, uv ); 16837#endif 16838#ifdef USE_ALPHAMAP 16839 diffuseColor.a *= texture2D( alphaMap, uv ).g; 16840#endif`, bx = `#if defined( USE_POINTS_UV ) 16841 varying vec2 vUv; 16842#else 16843 #if defined( USE_MAP ) || defined( USE_ALPHAMAP ) 16844 uniform mat3 uvTransform; 16845 #endif 16846#endif 16847#ifdef USE_MAP 16848 uniform sampler2D map; 16849#endif 16850#ifdef USE_ALPHAMAP 16851 uniform sampler2D alphaMap; 16852#endif`, wx = `float metalnessFactor = metalness; 16853#ifdef USE_METALNESSMAP 16854 vec4 texelMetalness = texture2D( metalnessMap, vMetalnessMapUv ); 16855 metalnessFactor *= texelMetalness.b; 16856#endif`, Sx = `#ifdef USE_METALNESSMAP 16857 uniform sampler2D metalnessMap; 16858#endif`, Ex = `#ifdef USE_INSTANCING_MORPH 16859 float morphTargetInfluences[ MORPHTARGETS_COUNT ]; 16860 float morphTargetBaseInfluence = texelFetch( morphTexture, ivec2( 0, gl_InstanceID ), 0 ).r; 16861 for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { 16862 morphTargetInfluences[i] = texelFetch( morphTexture, ivec2( i + 1, gl_InstanceID ), 0 ).r; 16863 } 16864#endif`, Mx = `#if defined( USE_MORPHCOLORS ) 16865 vColor *= morphTargetBaseInfluence; 16866 for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { 16867 #if defined( USE_COLOR_ALPHA ) 16868 if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ) * morphTargetInfluences[ i ]; 16869 #elif defined( USE_COLOR ) 16870 if ( morphTargetInfluences[ i ] != 0.0 ) vColor += getMorph( gl_VertexID, i, 2 ).rgb * morphTargetInfluences[ i ]; 16871 #endif 16872 } 16873#endif`, Tx = `#ifdef USE_MORPHNORMALS 16874 objectNormal *= morphTargetBaseInfluence; 16875 for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { 16876 if ( morphTargetInfluences[ i ] != 0.0 ) objectNormal += getMorph( gl_VertexID, i, 1 ).xyz * morphTargetInfluences[ i ]; 16877 } 16878#endif`, Ax = `#ifdef USE_MORPHTARGETS 16879 #ifndef USE_INSTANCING_MORPH 16880 uniform float morphTargetBaseInfluence; 16881 uniform float morphTargetInfluences[ MORPHTARGETS_COUNT ]; 16882 #endif 16883 uniform sampler2DArray morphTargetsTexture; 16884 uniform ivec2 morphTargetsTextureSize; 16885 vec4 getMorph( const in int vertexIndex, const in int morphTargetIndex, const in int offset ) { 16886 int texelIndex = vertexIndex * MORPHTARGETS_TEXTURE_STRIDE + offset; 16887 int y = texelIndex / morphTargetsTextureSize.x; 16888 int x = texelIndex - y * morphTargetsTextureSize.x; 16889 ivec3 morphUV = ivec3( x, y, morphTargetIndex ); 16890 return texelFetch( morphTargetsTexture, morphUV, 0 ); 16891 } 16892#endif`, Rx = `#ifdef USE_MORPHTARGETS 16893 transformed *= morphTargetBaseInfluence; 16894 for ( int i = 0; i < MORPHTARGETS_COUNT; i ++ ) { 16895 if ( morphTargetInfluences[ i ] != 0.0 ) transformed += getMorph( gl_VertexID, i, 0 ).xyz * morphTargetInfluences[ i ]; 16896 } 16897#endif`, Cx = `float faceDirection = gl_FrontFacing ? 1.0 : - 1.0; 16898#ifdef FLAT_SHADED 16899 vec3 fdx = dFdx( vViewPosition ); 16900 vec3 fdy = dFdy( vViewPosition ); 16901 vec3 normal = normalize( cross( fdx, fdy ) ); 16902#else 16903 vec3 normal = normalize( vNormal ); 16904 #ifdef DOUBLE_SIDED 16905 normal *= faceDirection; 16906 #endif 16907#endif 16908#if defined( USE_NORMALMAP_TANGENTSPACE ) || defined( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) 16909 #ifdef USE_TANGENT 16910 mat3 tbn = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); 16911 #else 16912 mat3 tbn = getTangentFrame( - vViewPosition, normal, 16913 #if defined( USE_NORMALMAP ) 16914 vNormalMapUv 16915 #elif defined( USE_CLEARCOAT_NORMALMAP ) 16916 vClearcoatNormalMapUv 16917 #else 16918 vUv 16919 #endif 16920 ); 16921 #endif 16922 #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) 16923 tbn[0] *= faceDirection; 16924 tbn[1] *= faceDirection; 16925 #endif 16926#endif 16927#ifdef USE_CLEARCOAT_NORMALMAP 16928 #ifdef USE_TANGENT 16929 mat3 tbn2 = mat3( normalize( vTangent ), normalize( vBitangent ), normal ); 16930 #else 16931 mat3 tbn2 = getTangentFrame( - vViewPosition, normal, vClearcoatNormalMapUv ); 16932 #endif 16933 #if defined( DOUBLE_SIDED ) && ! defined( FLAT_SHADED ) 16934 tbn2[0] *= faceDirection; 16935 tbn2[1] *= faceDirection; 16936 #endif 16937#endif 16938vec3 nonPerturbedNormal = normal;`, Px = `#ifdef USE_NORMALMAP_OBJECTSPACE 16939 normal = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; 16940 #ifdef FLIP_SIDED 16941 normal = - normal; 16942 #endif 16943 #ifdef DOUBLE_SIDED 16944 normal = normal * faceDirection; 16945 #endif 16946 normal = normalize( normalMatrix * normal ); 16947#elif defined( USE_NORMALMAP_TANGENTSPACE ) 16948 vec3 mapN = texture2D( normalMap, vNormalMapUv ).xyz * 2.0 - 1.0; 16949 #if defined( USE_PACKED_NORMALMAP ) 16950 mapN = vec3( mapN.xy, sqrt( saturate( 1.0 - dot( mapN.xy, mapN.xy ) ) ) ); 16951 #endif 16952 mapN.xy *= normalScale; 16953 normal = normalize( tbn * mapN ); 16954#elif defined( USE_BUMPMAP )
16955 normal = perturbNormalArb( - vViewPosition, normal, dHdxy_fwd(), faceDirection ); 16956#endif`, Lx = `#ifndef FLAT_SHADED 16957 varying vec3 vNormal; 16958 #ifdef USE_TANGENT 16959 varying vec3 vTangent; 16960 varying vec3 vBitangent; 16961 #endif 16962#endif`, Nx = `#ifndef FLAT_SHADED 16963 varying vec3 vNormal; 16964 #ifdef USE_TANGENT 16965 varying vec3 vTangent; 16966 varying vec3 vBitangent; 16967 #endif 16968#endif`, Ix = `#ifndef FLAT_SHADED 16969 vNormal = normalize( transformedNormal ); 16970 #ifdef USE_TANGENT 16971 vTangent = normalize( transformedTangent ); 16972 vBitangent = normalize( cross( vNormal, vTangent ) * tangent.w ); 16973 #endif 16974#endif`, Dx = `#ifdef USE_NORMALMAP 16975 uniform sampler2D normalMap; 16976 uniform vec2 normalScale; 16977#endif 16978#ifdef USE_NORMALMAP_OBJECTSPACE 16979 uniform mat3 normalMatrix; 16980#endif 16981#if ! defined ( USE_TANGENT ) && ( defined ( USE_NORMALMAP_TANGENTSPACE ) || defined ( USE_CLEARCOAT_NORMALMAP ) || defined( USE_ANISOTROPY ) ) 16982 mat3 getTangentFrame( vec3 eye_pos, vec3 surf_norm, vec2 uv ) { 16983 vec3 q0 = dFdx( eye_pos.xyz ); 16984 vec3 q1 = dFdy( eye_pos.xyz ); 16985 vec2 st0 = dFdx( uv.st ); 16986 vec2 st1 = dFdy( uv.st ); 16987 vec3 N = surf_norm; 16988 vec3 q1perp = cross( q1, N ); 16989 vec3 q0perp = cross( N, q0 ); 16990 vec3 T = q1perp * st0.x + q0perp * st1.x; 16991 vec3 B = q1perp * st0.y + q0perp * st1.y; 16992 float det = max( dot( T, T ), dot( B, B ) ); 16993 float scale = ( det == 0.0 ) ? 0.0 : inversesqrt( det ); 16994 return mat3( T * scale, B * scale, N ); 16995 } 16996#endif`, Ux = `#ifdef USE_CLEARCOAT 16997 vec3 clearcoatNormal = nonPerturbedNormal; 16998#endif`, Ox = `#ifdef USE_CLEARCOAT_NORMALMAP 16999 vec3 clearcoatMapN = texture2D( clearcoatNormalMap, vClearcoatNormalMapUv ).xyz * 2.0 - 1.0; 17000 clearcoatMapN.xy *= clearcoatNormalScale; 17001 clearcoatNormal = normalize( tbn2 * clearcoatMapN ); 17002#endif`, kx = `#ifdef USE_CLEARCOATMAP 17003 uniform sampler2D clearcoatMap; 17004#endif 17005#ifdef USE_CLEARCOAT_NORMALMAP 17006 uniform sampler2D clearcoatNormalMap; 17007 uniform vec2 clearcoatNormalScale; 17008#endif 17009#ifdef USE_CLEARCOAT_ROUGHNESSMAP 17010 uniform sampler2D clearcoatRoughnessMap; 17011#endif`, Fx = `#ifdef USE_IRIDESCENCEMAP 17012 uniform sampler2D iridescenceMap; 17013#endif 17014#ifdef USE_IRIDESCENCE_THICKNESSMAP 17015 uniform sampler2D iridescenceThicknessMap; 17016#endif`, Bx = `#ifdef OPAQUE 17017diffuseColor.a = 1.0; 17018#endif 17019#ifdef USE_TRANSMISSION 17020diffuseColor.a *= material.transmissionAlpha; 17021#endif 17022gl_FragColor = vec4( outgoingLight, diffuseColor.a );`, zx = `vec3 packNormalToRGB( const in vec3 normal ) { 17023 return normalize( normal ) * 0.5 + 0.5; 17024} 17025vec3 unpackRGBToNormal( const in vec3 rgb ) { 17026 return 2.0 * rgb.xyz - 1.0; 17027} 17028const float PackUpscale = 256. / 255.;const float UnpackDownscale = 255. / 256.;const float ShiftRight8 = 1. / 256.; 17029const float Inv255 = 1. / 255.; 17030const vec4 PackFactors = vec4( 1.0, 256.0, 256.0 * 256.0, 256.0 * 256.0 * 256.0 ); 17031const vec2 UnpackFactors2 = vec2( UnpackDownscale, 1.0 / PackFactors.g ); 17032const vec3 UnpackFactors3 = vec3( UnpackDownscale / PackFactors.rg, 1.0 / PackFactors.b ); 17033const vec4 UnpackFactors4 = vec4( UnpackDownscale / PackFactors.rgb, 1.0 / PackFactors.a ); 17034vec4 packDepthToRGBA( const in float v ) { 17035 if( v <= 0.0 ) 17036 return vec4( 0., 0., 0., 0. ); 17037 if( v >= 1.0 ) 17038 return vec4( 1., 1., 1., 1. ); 17039 float vuf; 17040 float af = modf( v * PackFactors.a, vuf ); 17041 float bf = modf( vuf * ShiftRight8, vuf ); 17042 float gf = modf( vuf * ShiftRight8, vuf ); 17043 return vec4( vuf * Inv255, gf * PackUpscale, bf * PackUpscale, af ); 17044} 17045vec3 packDepthToRGB( const in float v ) { 17046 if( v <= 0.0 ) 17047 return vec3( 0., 0., 0. ); 17048 if( v >= 1.0 ) 17049 return vec3( 1., 1., 1. ); 17050 float vuf; 17051 float bf = modf( v * PackFactors.b, vuf ); 17052 float gf = modf( vuf * ShiftRight8, vuf ); 17053 return vec3( vuf * Inv255, gf * PackUpscale, bf ); 17054} 17055vec2 packDepthToRG( const in float v ) { 17056 if( v <= 0.0 ) 17057 return vec2( 0., 0. ); 17058 if( v >= 1.0 ) 17059 return vec2( 1., 1. ); 17060 float vuf; 17061 float gf = modf( v * 256., vuf ); 17062 return vec2( vuf * Inv255, gf ); 17063} 17064float unpackRGBAToDepth( const in vec4 v ) { 17065 return dot( v, UnpackFactors4 ); 17066} 17067float unpackRGBToDepth( const in vec3 v ) { 17068 return dot( v, UnpackFactors3 ); 17069} 17070float unpackRGToDepth( const in vec2 v ) { 17071 return v.r * UnpackFactors2.r + v.g * UnpackFactors2.g; 17072} 17073vec4 pack2HalfToRGBA( const in vec2 v ) {
17074 vec4 r = vec4( v.x, fract( v.x * 255.0 ), v.y, fract( v.y * 255.0 ) ); 17075 return vec4( r.x - r.y / 255.0, r.y, r.z - r.w / 255.0, r.w ); 17076} 17077vec2 unpackRGBATo2Half( const in vec4 v ) { 17078 return vec2( v.x + ( v.y / 255.0 ), v.z + ( v.w / 255.0 ) ); 17079} 17080float viewZToOrthographicDepth( const in float viewZ, const in float near, const in float far ) { 17081 return ( viewZ + near ) / ( near - far ); 17082} 17083float orthographicDepthToViewZ( const in float depth, const in float near, const in float far ) { 17084 #ifdef USE_REVERSED_DEPTH_BUFFER 17085 17086 return depth * ( far - near ) - far; 17087 #else 17088 return depth * ( near - far ) - near; 17089 #endif 17090} 17091float viewZToPerspectiveDepth( const in float viewZ, const in float near, const in float far ) { 17092 return ( ( near + viewZ ) * far ) / ( ( far - near ) * viewZ ); 17093} 17094float perspectiveDepthToViewZ( const in float depth, const in float near, const in float far ) { 17095 17096 #ifdef USE_REVERSED_DEPTH_BUFFER 17097 return ( near * far ) / ( ( near - far ) * depth - near ); 17098 #else 17099 return ( near * far ) / ( ( far - near ) * depth - far ); 17100 #endif 17101}`, Hx = `#ifdef PREMULTIPLIED_ALPHA 17102 gl_FragColor.rgb *= gl_FragColor.a; 17103#endif`, Gx = `vec4 mvPosition = vec4( transformed, 1.0 ); 17104#ifdef USE_BATCHING 17105 mvPosition = batchingMatrix * mvPosition; 17106#endif 17107#ifdef USE_INSTANCING 17108 mvPosition = instanceMatrix * mvPosition; 17109#endif 17110mvPosition = modelViewMatrix * mvPosition; 17111gl_Position = projectionMatrix * mvPosition;`, Vx = `#ifdef DITHERING 17112 gl_FragColor.rgb = dithering( gl_FragColor.rgb ); 17113#endif`, Wx = `#ifdef DITHERING 17114 vec3 dithering( vec3 color ) { 17115 float grid_position = rand( gl_FragCoord.xy ); 17116 vec3 dither_shift_RGB = vec3( 0.25 / 255.0, -0.25 / 255.0, 0.25 / 255.0 ); 17117 dither_shift_RGB = mix( 2.0 * dither_shift_RGB, -2.0 * dither_shift_RGB, grid_position ); 17118 return color + dither_shift_RGB; 17119 } 17120#endif`, $x = `float roughnessFactor = roughness; 17121#ifdef USE_ROUGHNESSMAP 17122 vec4 texelRoughness = texture2D( roughnessMap, vRoughnessMapUv ); 17123 roughnessFactor *= texelRoughness.g; 17124#endif`, jx = `#ifdef USE_ROUGHNESSMAP 17125 uniform sampler2D roughnessMap; 17126#endif`, Xx = `#if NUM_SPOT_LIGHT_COORDS > 0 17127 varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; 17128#endif 17129#if NUM_SPOT_LIGHT_MAPS > 0 17130 uniform sampler2D spotLightMap[ NUM_SPOT_LIGHT_MAPS ]; 17131#endif 17132#ifdef USE_SHADOWMAP 17133 #if NUM_DIR_LIGHT_SHADOWS > 0 17134 #if defined( SHADOWMAP_TYPE_PCF ) 17135 uniform sampler2DShadow directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; 17136 #else 17137 uniform sampler2D directionalShadowMap[ NUM_DIR_LIGHT_SHADOWS ]; 17138 #endif 17139 varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; 17140 struct DirectionalLightShadow { 17141 float shadowIntensity; 17142 float shadowBias; 17143 float shadowNormalBias; 17144 float shadowRadius; 17145 vec2 shadowMapSize; 17146 }; 17147 uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; 17148 #endif 17149 #if NUM_SPOT_LIGHT_SHADOWS > 0 17150 #if defined( SHADOWMAP_TYPE_PCF ) 17151 uniform sampler2DShadow spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; 17152 #else 17153 uniform sampler2D spotShadowMap[ NUM_SPOT_LIGHT_SHADOWS ]; 17154 #endif 17155 struct SpotLightShadow { 17156 float shadowIntensity; 17157 float shadowBias; 17158 float shadowNormalBias; 17159 float shadowRadius; 17160 vec2 shadowMapSize; 17161 }; 17162 uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; 17163 #endif 17164 #if NUM_POINT_LIGHT_SHADOWS > 0 17165 #if defined( SHADOWMAP_TYPE_PCF ) 17166 uniform samplerCubeShadow pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; 17167 #elif defined( SHADOWMAP_TYPE_BASIC ) 17168 uniform samplerCube pointShadowMap[ NUM_POINT_LIGHT_SHADOWS ]; 17169 #endif 17170 varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; 17171 struct PointLightShadow { 17172 float shadowIntensity; 17173 float shadowBias; 17174 float shadowNormalBias; 17175 float shadowRadius; 17176 vec2 shadowMapSize; 17177 float shadowCameraNear; 17178 float shadowCameraFar; 17179 }; 17180 uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; 17181 #endif 17182 #if defined( SHADOWMAP_TYPE_PCF ) 17183 float interleavedGradientNoise( vec2 position ) { 17184 return fract( 52.9829189 * fract( dot( position, vec2( 0.06711056, 0.00583715 ) ) ) ); 17185 } 17186 vec2 vogelDiskSample( int sampleIndex, int samplesCount, float phi ) { 17187 const float goldenAngle = 2.399963229728653; 17188 float r = sqrt( ( float( sampleIndex ) + 0.5 ) / float( samplesCount ) ); 17189 float theta = float( sampleIndex ) * goldenAngle + phi; 17190 return vec2( cos( theta ), sin( theta ) ) * r; 17191 } 17192 #endif 17193 #if defined( SHADOWMAP_TYPE_PCF ) 17194 float getShadow( sampler2DShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { 17195 float shadow = 1.0; 17196 shadowCoord.xyz /= shadowCoord.w; 17197 shadowCoord.z += shadowBias; 17198 bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; 17199 bool frustumTest = inFrustum && shadowCoord.z <= 1.0; 17200 if ( frustumTest ) { 17201 vec2 texelSize = vec2( 1.0 ) / shadowMapSize; 17202 float radius = shadowRadius * texelSize.x; 17203 float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; 17204 shadow = ( 17205 texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 0, 5, phi ) * radius, shadowCoord.z ) ) + 17206 texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 1, 5, phi ) * radius, shadowCoord.z ) ) + 17207 texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 2, 5, phi ) * radius, shadowCoord.z ) ) + 17208 texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 3, 5, phi ) * radius, shadowCoord.z ) ) + 17209 texture( shadowMap, vec3( shadowCoord.xy + vogelDiskSample( 4, 5, phi ) * radius, shadowCoord.z ) ) 17210 ) * 0.2; 17211 } 17212 return mix( 1.0, shadow, shadowIntensity ); 17213 } 17214 #elif defined( SHADOWMAP_TYPE_VSM ) 17215 float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { 17216 float shadow = 1.0; 17217 shadowCoord.xyz /= shadowCoord.w; 17218 #ifdef USE_REVERSED_DEPTH_BUFFER 17219 shadowCoord.z -= shadowBias; 17220 #else 17221 shadowCoord.z += shadowBias; 17222 #endif 17223 bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; 17224 bool frustumTest = inFrustum && shadowCoord.z <= 1.0; 17225 if ( frustumTest ) { 17226 vec2 distribution = texture2D( shadowMap, shadowCoord.xy ).rg; 17227 float mean = distribution.x; 17228 float variance = distribution.y * distribution.y; 17229 #ifdef USE_REVERSED_DEPTH_BUFFER 17230 float hard_shadow = step( mean, shadowCoord.z ); 17231 #else 17232 float hard_shadow = step( shadowCoord.z, mean ); 17233 #endif 17234 17235 if ( hard_shadow == 1.0 ) { 17236 shadow = 1.0; 17237 } else { 17238 variance = max( variance, 0.0000001 ); 17239 float d = shadowCoord.z - mean; 17240 float p_max = variance / ( variance + d * d ); 17241 p_max = clamp( ( p_max - 0.3 ) / 0.65, 0.0, 1.0 ); 17242 shadow = max( hard_shadow, p_max ); 17243 } 17244 } 17245 return mix( 1.0, shadow, shadowIntensity ); 17246 } 17247 #else 17248 float getShadow( sampler2D shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord ) { 17249 float shadow = 1.0; 17250 shadowCoord.xyz /= shadowCoord.w; 17251 #ifdef USE_REVERSED_DEPTH_BUFFER 17252 shadowCoord.z -= shadowBias; 17253 #else 17254 shadowCoord.z += shadowBias; 17255 #endif 17256 bool inFrustum = shadowCoord.x >= 0.0 && shadowCoord.x <= 1.0 && shadowCoord.y >= 0.0 && shadowCoord.y <= 1.0; 17257 bool frustumTest = inFrustum && shadowCoord.z <= 1.0; 17258 if ( frustumTest ) { 17259 float depth = texture2D( shadowMap, shadowCoord.xy ).r; 17260 #ifdef USE_REVERSED_DEPTH_BUFFER 17261 shadow = step( depth, shadowCoord.z ); 17262 #else 17263 shadow = step( shadowCoord.z, depth ); 17264 #endif 17265 } 17266 return mix( 1.0, shadow, shadowIntensity ); 17267 } 17268 #endif 17269 #if NUM_POINT_LIGHT_SHADOWS > 0 17270 #if defined( SHADOWMAP_TYPE_PCF ) 17271 float getPointShadow( samplerCubeShadow shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { 17272 float shadow = 1.0; 17273 vec3 lightToPosition = shadowCoord.xyz; 17274 vec3 bd3D = normalize( lightToPosition ); 17275 vec3 absVec = abs( lightToPosition ); 17276 float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); 17277 if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { 17278 #ifdef USE_REVERSED_DEPTH_BUFFER 17279 float dp = ( shadowCameraNear * ( shadowCameraFar - viewSpaceZ ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) );
17280 dp -= shadowBias; 17281 #else 17282 float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); 17283 dp += shadowBias; 17284 #endif 17285 float texelSize = shadowRadius / shadowMapSize.x; 17286 vec3 absDir = abs( bd3D ); 17287 vec3 tangent = absDir.x > absDir.z ? vec3( 0.0, 1.0, 0.0 ) : vec3( 1.0, 0.0, 0.0 ); 17288 tangent = normalize( cross( bd3D, tangent ) ); 17289 vec3 bitangent = cross( bd3D, tangent ); 17290 float phi = interleavedGradientNoise( gl_FragCoord.xy ) * PI2; 17291 vec2 sample0 = vogelDiskSample( 0, 5, phi ); 17292 vec2 sample1 = vogelDiskSample( 1, 5, phi ); 17293 vec2 sample2 = vogelDiskSample( 2, 5, phi ); 17294 vec2 sample3 = vogelDiskSample( 3, 5, phi ); 17295 vec2 sample4 = vogelDiskSample( 4, 5, phi ); 17296 shadow = ( 17297 texture( shadowMap, vec4( bd3D + ( tangent * sample0.x + bitangent * sample0.y ) * texelSize, dp ) ) + 17298 texture( shadowMap, vec4( bd3D + ( tangent * sample1.x + bitangent * sample1.y ) * texelSize, dp ) ) + 17299 texture( shadowMap, vec4( bd3D + ( tangent * sample2.x + bitangent * sample2.y ) * texelSize, dp ) ) + 17300 texture( shadowMap, vec4( bd3D + ( tangent * sample3.x + bitangent * sample3.y ) * texelSize, dp ) ) + 17301 texture( shadowMap, vec4( bd3D + ( tangent * sample4.x + bitangent * sample4.y ) * texelSize, dp ) ) 17302 ) * 0.2; 17303 } 17304 return mix( 1.0, shadow, shadowIntensity ); 17305 } 17306 #elif defined( SHADOWMAP_TYPE_BASIC ) 17307 float getPointShadow( samplerCube shadowMap, vec2 shadowMapSize, float shadowIntensity, float shadowBias, float shadowRadius, vec4 shadowCoord, float shadowCameraNear, float shadowCameraFar ) { 17308 float shadow = 1.0; 17309 vec3 lightToPosition = shadowCoord.xyz; 17310 vec3 absVec = abs( lightToPosition ); 17311 float viewSpaceZ = max( max( absVec.x, absVec.y ), absVec.z ); 17312 if ( viewSpaceZ - shadowCameraFar <= 0.0 && viewSpaceZ - shadowCameraNear >= 0.0 ) { 17313 float dp = ( shadowCameraFar * ( viewSpaceZ - shadowCameraNear ) ) / ( viewSpaceZ * ( shadowCameraFar - shadowCameraNear ) ); 17314 dp += shadowBias; 17315 vec3 bd3D = normalize( lightToPosition ); 17316 float depth = textureCube( shadowMap, bd3D ).r; 17317 #ifdef USE_REVERSED_DEPTH_BUFFER 17318 depth = 1.0 - depth; 17319 #endif 17320 shadow = step( dp, depth ); 17321 } 17322 return mix( 1.0, shadow, shadowIntensity ); 17323 } 17324 #endif 17325 #endif 17326#endif`, qx = `#if NUM_SPOT_LIGHT_COORDS > 0 17327 uniform mat4 spotLightMatrix[ NUM_SPOT_LIGHT_COORDS ]; 17328 varying vec4 vSpotLightCoord[ NUM_SPOT_LIGHT_COORDS ]; 17329#endif 17330#ifdef USE_SHADOWMAP 17331 #if NUM_DIR_LIGHT_SHADOWS > 0 17332 uniform mat4 directionalShadowMatrix[ NUM_DIR_LIGHT_SHADOWS ]; 17333 varying vec4 vDirectionalShadowCoord[ NUM_DIR_LIGHT_SHADOWS ]; 17334 struct DirectionalLightShadow { 17335 float shadowIntensity; 17336 float shadowBias; 17337 float shadowNormalBias; 17338 float shadowRadius; 17339 vec2 shadowMapSize; 17340 }; 17341 uniform DirectionalLightShadow directionalLightShadows[ NUM_DIR_LIGHT_SHADOWS ]; 17342 #endif 17343 #if NUM_SPOT_LIGHT_SHADOWS > 0 17344 struct SpotLightShadow { 17345 float shadowIntensity; 17346 float shadowBias; 17347 float shadowNormalBias; 17348 float shadowRadius; 17349 vec2 shadowMapSize; 17350 }; 17351 uniform SpotLightShadow spotLightShadows[ NUM_SPOT_LIGHT_SHADOWS ]; 17352 #endif 17353 #if NUM_POINT_LIGHT_SHADOWS > 0 17354 uniform mat4 pointShadowMatrix[ NUM_POINT_LIGHT_SHADOWS ]; 17355 varying vec4 vPointShadowCoord[ NUM_POINT_LIGHT_SHADOWS ]; 17356 struct PointLightShadow { 17357 float shadowIntensity; 17358 float shadowBias; 17359 float shadowNormalBias; 17360 float shadowRadius; 17361 vec2 shadowMapSize; 17362 float shadowCameraNear; 17363 float shadowCameraFar; 17364 }; 17365 uniform PointLightShadow pointLightShadows[ NUM_POINT_LIGHT_SHADOWS ]; 17366 #endif 17367#endif`, Yx = `#if ( defined( USE_SHADOWMAP ) && ( NUM_DIR_LIGHT_SHADOWS > 0 || NUM_POINT_LIGHT_SHADOWS > 0 ) ) || ( NUM_SPOT_LIGHT_COORDS > 0 ) 17368 #ifdef HAS_NORMAL 17369 vec3 shadowWorldNormal = inverseTransformDirection( transformedNormal, viewMatrix ); 17370 #else 17371 vec3 shadowWorldNormal = vec3( 0.0 ); 17372 #endif 17373 vec4 shadowWorldPosition; 17374#endif 17375#if defined( USE_SHADOWMAP ) 17376 #if NUM_DIR_LIGHT_SHADOWS > 0 17377 #pragma unroll_loop_start 17378 for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { 17379 shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * directionalLightShadows[ i ].shadowNormalBias, 0 ); 17380 vDirectionalShadowCoord[ i ] = directionalShadowMatrix[ i ] * shadowWorldPosition; 17381 } 17382 #pragma unroll_loop_end 17383 #endif 17384 #if NUM_POINT_LIGHT_SHADOWS > 0 17385 #pragma unroll_loop_start 17386 for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { 17387 shadowWorldPosition = worldPosition + vec4( shadowWorldNormal * pointLightShadows[ i ].shadowNormalBias, 0 ); 17388 vPointShadowCoord[ i ] = pointShadowMatrix[ i ] * shadowWorldPosition; 17389 } 17390 #pragma unroll_loop_end 17391 #endif 17392#endif
17393#if NUM_SPOT_LIGHT_COORDS > 0 17394 #pragma unroll_loop_start 17395 for ( int i = 0; i < NUM_SPOT_LIGHT_COORDS; i ++ ) { 17396 shadowWorldPosition = worldPosition; 17397 #if ( defined( USE_SHADOWMAP ) && UNROLLED_LOOP_INDEX < NUM_SPOT_LIGHT_SHADOWS ) 17398 shadowWorldPosition.xyz += shadowWorldNormal * spotLightShadows[ i ].shadowNormalBias; 17399 #endif 17400 vSpotLightCoord[ i ] = spotLightMatrix[ i ] * shadowWorldPosition; 17401 } 17402 #pragma unroll_loop_end 17403#endif`, Kx = `float getShadowMask() { 17404 float shadow = 1.0; 17405 #ifdef USE_SHADOWMAP 17406 #if NUM_DIR_LIGHT_SHADOWS > 0 17407 DirectionalLightShadow directionalLight; 17408 #pragma unroll_loop_start 17409 for ( int i = 0; i < NUM_DIR_LIGHT_SHADOWS; i ++ ) { 17410 directionalLight = directionalLightShadows[ i ]; 17411 shadow *= receiveShadow ? getShadow( directionalShadowMap[ i ], directionalLight.shadowMapSize, directionalLight.shadowIntensity, directionalLight.shadowBias, directionalLight.shadowRadius, vDirectionalShadowCoord[ i ] ) : 1.0; 17412 } 17413 #pragma unroll_loop_end 17414 #endif 17415 #if NUM_SPOT_LIGHT_SHADOWS > 0 17416 SpotLightShadow spotLight; 17417 #pragma unroll_loop_start 17418 for ( int i = 0; i < NUM_SPOT_LIGHT_SHADOWS; i ++ ) { 17419 spotLight = spotLightShadows[ i ]; 17420 shadow *= receiveShadow ? getShadow( spotShadowMap[ i ], spotLight.shadowMapSize, spotLight.shadowIntensity, spotLight.shadowBias, spotLight.shadowRadius, vSpotLightCoord[ i ] ) : 1.0; 17421 } 17422 #pragma unroll_loop_end 17423 #endif 17424 #if NUM_POINT_LIGHT_SHADOWS > 0 && ( defined( SHADOWMAP_TYPE_PCF ) || defined( SHADOWMAP_TYPE_BASIC ) ) 17425 PointLightShadow pointLight; 17426 #pragma unroll_loop_start 17427 for ( int i = 0; i < NUM_POINT_LIGHT_SHADOWS; i ++ ) { 17428 pointLight = pointLightShadows[ i ]; 17429 shadow *= receiveShadow ? getPointShadow( pointShadowMap[ i ], pointLight.shadowMapSize, pointLight.shadowIntensity, pointLight.shadowBias, pointLight.shadowRadius, vPointShadowCoord[ i ], pointLight.shadowCameraNear, pointLight.shadowCameraFar ) : 1.0; 17430 } 17431 #pragma unroll_loop_end 17432 #endif 17433 #endif 17434 return shadow; 17435}`, Jx = `#ifdef USE_SKINNING 17436 mat4 boneMatX = getBoneMatrix( skinIndex.x ); 17437 mat4 boneMatY = getBoneMatrix( skinIndex.y ); 17438 mat4 boneMatZ = getBoneMatrix( skinIndex.z ); 17439 mat4 boneMatW = getBoneMatrix( skinIndex.w ); 17440#endif`, Zx = `#ifdef USE_SKINNING 17441 uniform mat4 bindMatrix; 17442 uniform mat4 bindMatrixInverse; 17443 uniform highp sampler2D boneTexture; 17444 mat4 getBoneMatrix( const in float i ) { 17445 int size = textureSize( boneTexture, 0 ).x; 17446 int j = int( i ) * 4; 17447 int x = j % size; 17448 int y = j / size; 17449 vec4 v1 = texelFetch( boneTexture, ivec2( x, y ), 0 ); 17450 vec4 v2 = texelFetch( boneTexture, ivec2( x + 1, y ), 0 ); 17451 vec4 v3 = texelFetch( boneTexture, ivec2( x + 2, y ), 0 ); 17452 vec4 v4 = texelFetch( boneTexture, ivec2( x + 3, y ), 0 ); 17453 return mat4( v1, v2, v3, v4 ); 17454 } 17455#endif`, Qx = `#ifdef USE_SKINNING 17456 vec4 skinVertex = bindMatrix * vec4( transformed, 1.0 ); 17457 vec4 skinned = vec4( 0.0 ); 17458 skinned += boneMatX * skinVertex * skinWeight.x; 17459 skinned += boneMatY * skinVertex * skinWeight.y; 17460 skinned += boneMatZ * skinVertex * skinWeight.z; 17461 skinned += boneMatW * skinVertex * skinWeight.w; 17462 transformed = ( bindMatrixInverse * skinned ).xyz; 17463#endif`, eb = `#ifdef USE_SKINNING 17464 mat4 skinMatrix = mat4( 0.0 ); 17465 skinMatrix += skinWeight.x * boneMatX; 17466 skinMatrix += skinWeight.y * boneMatY; 17467 skinMatrix += skinWeight.z * boneMatZ; 17468 skinMatrix += skinWeight.w * boneMatW; 17469 skinMatrix = bindMatrixInverse * skinMatrix * bindMatrix; 17470 objectNormal = vec4( skinMatrix * vec4( objectNormal, 0.0 ) ).xyz; 17471 #ifdef USE_TANGENT 17472 objectTangent = vec4( skinMatrix * vec4( objectTangent, 0.0 ) ).xyz; 17473 #endif 17474#endif`, tb = `float specularStrength; 17475#ifdef USE_SPECULARMAP 17476 vec4 texelSpecular = texture2D( specularMap, vSpecularMapUv ); 17477 specularStrength = texelSpecular.r; 17478#else 17479 specularStrength = 1.0; 17480#endif`, nb = `#ifdef USE_SPECULARMAP 17481 uniform sampler2D specularMap; 17482#endif`, ib = `#if defined( TONE_MAPPING ) 17483 gl_FragColor.rgb = toneMapping( gl_FragColor.rgb ); 17484#endif`, rb = `#ifndef saturate 17485#define saturate( a ) clamp( a, 0.0, 1.0 ) 17486#endif 17487uniform float toneMappingExposure; 17488vec3 LinearToneMapping( vec3 color ) { 17489 return saturate( toneMappingExposure * color ); 17490} 17491vec3 ReinhardToneMapping( vec3 color ) { 17492 color *= toneMappingExposure; 17493 return saturate( color / ( vec3( 1.0 ) + color ) ); 17494} 17495vec3 CineonToneMapping( vec3 color ) { 17496 color *= toneMappingExposure; 17497 color = max( vec3( 0.0 ), color - 0.004 ); 17498 return pow( ( color * ( 6.2 * color + 0.5 ) ) / ( color * ( 6.2 * color + 1.7 ) + 0.06 ), vec3( 2.2 ) ); 17499} 17500vec3 RRTAndODTFit( vec3 v ) { 17501 vec3 a = v * ( v + 0.0245786 ) - 0.000090537; 17502 vec3 b = v * ( 0.983729 * v + 0.4329510 ) + 0.238081; 17503 return a / b; 17504} 17505vec3 ACESFilmicToneMapping( vec3 color ) { 17506 const mat3 ACESInputMat = mat3( 17507 vec3( 0.59719, 0.07600, 0.02840 ), vec3( 0.35458, 0.90834, 0.13383 ), 17508 vec3( 0.04823, 0.01566, 0.83777 ) 17509 ); 17510 const mat3 ACESOutputMat = mat3( 17511 vec3( 1.60475, -0.10208, -0.00327 ), vec3( -0.53108, 1.10813, -0.07276 ), 17512 vec3( -0.07367, -0.00605, 1.07602 ) 17513 ); 17514 color *= toneMappingExposure / 0.6; 17515 color = ACESInputMat * color; 17516 color = RRTAndODTFit( color ); 17517 color = ACESOutputMat * color; 17518 return saturate( color ); 17519} 17520const mat3 LINEAR_REC2020_TO_LINEAR_SRGB = mat3( 17521 vec3( 1.6605, - 0.1246, - 0.0182 ), 17522 vec3( - 0.5876, 1.1329, - 0.1006 ), 17523 vec3( - 0.0728, - 0.0083, 1.1187 ) 17524); 17525const mat3 LINEAR_SRGB_TO_LINEAR_REC2020 = mat3( 17526 vec3( 0.6274, 0.0691, 0.0164 ), 17527 vec3( 0.3293, 0.9195, 0.0880 ), 17528 vec3( 0.0433, 0.0113, 0.8956 ) 17529); 17530vec3 agxDefaultContrastApprox( vec3 x ) { 17531 vec3 x2 = x * x; 17532 vec3 x4 = x2 * x2; 17533 return + 15.5 * x4 * x2 17534 - 40.14 * x4 * x 17535 + 31.96 * x4 17536 - 6.868 * x2 * x 17537 + 0.4298 * x2 17538 + 0.1191 * x 17539 - 0.00232; 17540} 17541vec3 AgXToneMapping( vec3 color ) { 17542 const mat3 AgXInsetMatrix = mat3( 17543 vec3( 0.856627153315983, 0.137318972929847, 0.11189821299995 ), 17544 vec3( 0.0951212405381588, 0.761241990602591, 0.0767994186031903 ), 17545 vec3( 0.0482516061458583, 0.101439036467562, 0.811302368396859 ) 17546 );
17547 const mat3 AgXOutsetMatrix = mat3( 17548 vec3( 1.1271005818144368, - 0.1413297634984383, - 0.14132976349843826 ), 17549 vec3( - 0.11060664309660323, 1.157823702216272, - 0.11060664309660294 ), 17550 vec3( - 0.016493938717834573, - 0.016493938717834257, 1.2519364065950405 ) 17551 ); 17552 const float AgxMinEv = - 12.47393; const float AgxMaxEv = 4.026069; 17553 color *= toneMappingExposure; 17554 color = LINEAR_SRGB_TO_LINEAR_REC2020 * color; 17555 color = AgXInsetMatrix * color; 17556 color = max( color, 1e-10 ); color = log2( color ); 17557 color = ( color - AgxMinEv ) / ( AgxMaxEv - AgxMinEv ); 17558 color = clamp( color, 0.0, 1.0 ); 17559 color = agxDefaultContrastApprox( color ); 17560 color = AgXOutsetMatrix * color; 17561 color = pow( max( vec3( 0.0 ), color ), vec3( 2.2 ) ); 17562 color = LINEAR_REC2020_TO_LINEAR_SRGB * color; 17563 color = clamp( color, 0.0, 1.0 ); 17564 return color; 17565} 17566vec3 NeutralToneMapping( vec3 color ) { 17567 const float StartCompression = 0.8 - 0.04; 17568 const float Desaturation = 0.15; 17569 color *= toneMappingExposure; 17570 float x = min( color.r, min( color.g, color.b ) ); 17571 float offset = x < 0.08 ? x - 6.25 * x * x : 0.04; 17572 color -= offset; 17573 float peak = max( color.r, max( color.g, color.b ) ); 17574 if ( peak < StartCompression ) return color; 17575 float d = 1. - StartCompression; 17576 float newPeak = 1. - d * d / ( peak + d - StartCompression ); 17577 color *= newPeak / peak; 17578 float g = 1. - 1. / ( Desaturation * ( peak - newPeak ) + 1. ); 17579 return mix( color, vec3( newPeak ), g ); 17580} 17581vec3 CustomToneMapping( vec3 color ) { return color; }`, sb = `#ifdef USE_TRANSMISSION 17582 material.transmission = transmission; 17583 material.transmissionAlpha = 1.0; 17584 material.thickness = thickness; 17585 material.attenuationDistance = attenuationDistance; 17586 material.attenuationColor = attenuationColor; 17587 #ifdef USE_TRANSMISSIONMAP 17588 material.transmission *= texture2D( transmissionMap, vTransmissionMapUv ).r; 17589 #endif 17590 #ifdef USE_THICKNESSMAP 17591 material.thickness *= texture2D( thicknessMap, vThicknessMapUv ).g; 17592 #endif 17593 vec3 pos = vWorldPosition; 17594 vec3 v = normalize( cameraPosition - pos ); 17595 vec3 n = inverseTransformDirection( normal, viewMatrix ); 17596 vec4 transmitted = getIBLVolumeRefraction( 17597 n, v, material.roughness, material.diffuseContribution, material.specularColorBlended, material.specularF90, 17598 pos, modelMatrix, viewMatrix, projectionMatrix, material.dispersion, material.ior, material.thickness, 17599 material.attenuationColor, material.attenuationDistance ); 17600 material.transmissionAlpha = mix( material.transmissionAlpha, transmitted.a, material.transmission ); 17601 totalDiffuse = mix( totalDiffuse, transmitted.rgb, material.transmission ); 17602#endif`, ab = `#ifdef USE_TRANSMISSION 17603 uniform float transmission; 17604 uniform float thickness; 17605 uniform float attenuationDistance; 17606 uniform vec3 attenuationColor; 17607 #ifdef USE_TRANSMISSIONMAP 17608 uniform sampler2D transmissionMap; 17609 #endif 17610 #ifdef USE_THICKNESSMAP 17611 uniform sampler2D thicknessMap; 17612 #endif 17613 uniform vec2 transmissionSamplerSize; 17614 uniform sampler2D transmissionSamplerMap; 17615 uniform mat4 modelMatrix; 17616 uniform mat4 projectionMatrix; 17617 varying vec3 vWorldPosition; 17618 float w0( float a ) { 17619 return ( 1.0 / 6.0 ) * ( a * ( a * ( - a + 3.0 ) - 3.0 ) + 1.0 ); 17620 } 17621 float w1( float a ) { 17622 return ( 1.0 / 6.0 ) * ( a * a * ( 3.0 * a - 6.0 ) + 4.0 ); 17623 } 17624 float w2( float a ){ 17625 return ( 1.0 / 6.0 ) * ( a * ( a * ( - 3.0 * a + 3.0 ) + 3.0 ) + 1.0 ); 17626 } 17627 float w3( float a ) { 17628 return ( 1.0 / 6.0 ) * ( a * a * a ); 17629 } 17630 float g0( float a ) { 17631 return w0( a ) + w1( a ); 17632 } 17633 float g1( float a ) { 17634 return w2( a ) + w3( a ); 17635 } 17636 float h0( float a ) { 17637 return - 1.0 + w1( a ) / ( w0( a ) + w1( a ) ); 17638 } 17639 float h1( float a ) { 17640 return 1.0 + w3( a ) / ( w2( a ) + w3( a ) ); 17641 } 17642 vec4 bicubic( sampler2D tex, vec2 uv, vec4 texelSize, float lod ) { 17643 uv = uv * texelSize.zw + 0.5; 17644 vec2 iuv = floor( uv ); 17645 vec2 fuv = fract( uv ); 17646 float g0x = g0( fuv.x ); 17647 float g1x = g1( fuv.x ); 17648 float h0x = h0( fuv.x ); 17649 float h1x = h1( fuv.x ); 17650 float h0y = h0( fuv.y ); 17651 float h1y = h1( fuv.y ); 17652 vec2 p0 = ( vec2( iuv.x + h0x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; 17653 vec2 p1 = ( vec2( iuv.x + h1x, iuv.y + h0y ) - 0.5 ) * texelSize.xy; 17654 vec2 p2 = ( vec2( iuv.x + h0x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; 17655 vec2 p3 = ( vec2( iuv.x + h1x, iuv.y + h1y ) - 0.5 ) * texelSize.xy; 17656 return g0( fuv.y ) * ( g0x * textureLod( tex, p0, lod ) + g1x * textureLod( tex, p1, lod ) ) + 17657 g1( fuv.y ) * ( g0x * textureLod( tex, p2, lod ) + g1x * textureLod( tex, p3, lod ) ); 17658 } 17659 vec4 textureBicubic( sampler2D sampler, vec2 uv, float lod ) { 17660 vec2 fLodSize = vec2( textureSize( sampler, int( lod ) ) ); 17661 vec2 cLodSize = vec2( textureSize( sampler, int( lod + 1.0 ) ) ); 17662 vec2 fLodSizeInv = 1.0 / fLodSize; 17663 vec2 cLodSizeInv = 1.0 / cLodSize; 17664 vec4 fSample = bicubic( sampler, uv, vec4( fLodSizeInv, fLodSize ), floor( lod ) ); 17665 vec4 cSample = bicubic( sampler, uv, vec4( cLodSizeInv, cLodSize ), ceil( lod ) ); 17666 return mix( fSample, cSample, fract( lod ) ); 17667 } 17668 vec3 getVolumeTransmissionRay( const in vec3 n, const in vec3 v, const in float thickness, const in float ior, const in mat4 modelMatrix ) { 17669 vec3 refractionVector = refract( - v, normalize( n ), 1.0 / ior ); 17670 vec3 modelScale; 17671 modelScale.x = length( vec3( modelMatrix[ 0 ].xyz ) ); 17672 modelScale.y = length( vec3( modelMatrix[ 1 ].xyz ) ); 17673 modelScale.z = length( vec3( modelMatrix[ 2 ].xyz ) ); 17674 return normalize( refractionVector ) * thickness * modelScale; 17675 } 17676 float applyIorToRoughness( const in float roughness, const in float ior ) { 17677 return roughness * clamp( ior * 2.0 - 2.0, 0.0, 1.0 ); 17678 } 17679 vec4 getTransmissionSample( const in vec2 fragCoord, const in float roughness, const in float ior ) { 17680 float lod = log2( transmissionSamplerSize.x ) * applyIorToRoughness( roughness, ior ); 17681 return textureBicubic( transmissionSamplerMap, fragCoord.xy, lod ); 17682 } 17683 vec3 volumeAttenuation( const in float transmissionDistance, const in vec3 attenuationColor, const in float attenuationDistance ) { 17684 if ( isinf( attenuationDistance ) ) { 17685 return vec3( 1.0 ); 17686 } else { 17687 vec3 attenuationCoefficient = -log( attenuationColor ) / attenuationDistance; 17688 vec3 transmittance = exp( - attenuationCoefficient * transmissionDistance ); return transmittance; 17689 } 17690 } 17691 vec4 getIBLVolumeRefraction( const in vec3 n, const in vec3 v, const in float roughness, const in vec3 diffuseColor, 17692 const in vec3 specularColor, const in float specularF90, const in vec3 position, const in mat4 modelMatrix, 17693 const in mat4 viewMatrix, const in mat4 projMatrix, const in float dispersion, const in float ior, const in float thickness, 17694 const in vec3 attenuationColor, const in float attenuationDistance ) { 17695 vec4 transmittedLight; 17696 vec3 transmittance; 17697 #ifdef USE_DISPERSION 17698 float halfSpread = ( ior - 1.0 ) * 0.025 * dispersion; 17699 vec3 iors = vec3( ior - halfSpread, ior, ior + halfSpread ); 17700 for ( int i = 0; i < 3; i ++ ) { 17701 vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, iors[ i ], modelMatrix ); 17702 vec3 refractedRayExit = position + transmissionRay; 17703 vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); 17704 vec2 refractionCoords = ndcPos.xy / ndcPos.w; 17705 refractionCoords += 1.0; 17706 refractionCoords /= 2.0; 17707 vec4 transmissionSample = getTransmissionSample( refractionCoords, roughness, iors[ i ] ); 17708 transmittedLight[ i ] = transmissionSample[ i ]; 17709 transmittedLight.a += transmissionSample.a; 17710 transmittance[ i ] = diffuseColor[ i ] * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance )[ i ]; 17711 } 17712 transmittedLight.a /= 3.0; 17713 #else 17714 vec3 transmissionRay = getVolumeTransmissionRay( n, v, thickness, ior, modelMatrix ); 17715 vec3 refractedRayExit = position + transmissionRay; 17716 vec4 ndcPos = projMatrix * viewMatrix * vec4( refractedRayExit, 1.0 ); 17717 vec2 refractionCoords = ndcPos.xy / ndcPos.w; 17718 refractionCoords += 1.0; 17719 refractionCoords /= 2.0; 17720 transmittedLight = getTransmissionSample( refractionCoords, roughness, ior ); 17721 transmittance = diffuseColor * volumeAttenuation( length( transmissionRay ), attenuationColor, attenuationDistance ); 17722 #endif 17723 vec3 attenuatedColor = transmittance * transmittedLight.rgb; 17724 vec3 F = EnvironmentBRDF( n, v, specularColor, specularF90, roughness ); 17725 float transmittanceFactor = ( transmittance.r + transmittance.g + transmittance.b ) / 3.0; 17726 return vec4( ( 1.0 - F ) * attenuatedColor, 1.0 - ( 1.0 - transmittedLight.a ) * transmittanceFactor ); 17727 } 17728#endif`, ob = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) 17729 varying vec2 vUv; 17730#endif 17731#ifdef USE_MAP 17732 varying vec2 vMapUv; 17733#endif 17734#ifdef USE_ALPHAMAP
17735 varying vec2 vAlphaMapUv; 17736#endif 17737#ifdef USE_LIGHTMAP 17738 varying vec2 vLightMapUv; 17739#endif 17740#ifdef USE_AOMAP 17741 varying vec2 vAoMapUv; 17742#endif 17743#ifdef USE_BUMPMAP 17744 varying vec2 vBumpMapUv; 17745#endif 17746#ifdef USE_NORMALMAP 17747 varying vec2 vNormalMapUv; 17748#endif 17749#ifdef USE_EMISSIVEMAP 17750 varying vec2 vEmissiveMapUv; 17751#endif 17752#ifdef USE_METALNESSMAP 17753 varying vec2 vMetalnessMapUv; 17754#endif 17755#ifdef USE_ROUGHNESSMAP 17756 varying vec2 vRoughnessMapUv; 17757#endif 17758#ifdef USE_ANISOTROPYMAP 17759 varying vec2 vAnisotropyMapUv; 17760#endif 17761#ifdef USE_CLEARCOATMAP 17762 varying vec2 vClearcoatMapUv; 17763#endif 17764#ifdef USE_CLEARCOAT_NORMALMAP 17765 varying vec2 vClearcoatNormalMapUv; 17766#endif 17767#ifdef USE_CLEARCOAT_ROUGHNESSMAP 17768 varying vec2 vClearcoatRoughnessMapUv; 17769#endif 17770#ifdef USE_IRIDESCENCEMAP 17771 varying vec2 vIridescenceMapUv; 17772#endif 17773#ifdef USE_IRIDESCENCE_THICKNESSMAP 17774 varying vec2 vIridescenceThicknessMapUv; 17775#endif 17776#ifdef USE_SHEEN_COLORMAP 17777 varying vec2 vSheenColorMapUv; 17778#endif 17779#ifdef USE_SHEEN_ROUGHNESSMAP 17780 varying vec2 vSheenRoughnessMapUv; 17781#endif 17782#ifdef USE_SPECULARMAP 17783 varying vec2 vSpecularMapUv; 17784#endif 17785#ifdef USE_SPECULAR_COLORMAP 17786 varying vec2 vSpecularColorMapUv; 17787#endif 17788#ifdef USE_SPECULAR_INTENSITYMAP 17789 varying vec2 vSpecularIntensityMapUv; 17790#endif 17791#ifdef USE_TRANSMISSIONMAP 17792 uniform mat3 transmissionMapTransform; 17793 varying vec2 vTransmissionMapUv; 17794#endif 17795#ifdef USE_THICKNESSMAP 17796 uniform mat3 thicknessMapTransform; 17797 varying vec2 vThicknessMapUv; 17798#endif`, lb = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) 17799 varying vec2 vUv; 17800#endif 17801#ifdef USE_MAP 17802 uniform mat3 mapTransform; 17803 varying vec2 vMapUv; 17804#endif 17805#ifdef USE_ALPHAMAP 17806 uniform mat3 alphaMapTransform; 17807 varying vec2 vAlphaMapUv; 17808#endif 17809#ifdef USE_LIGHTMAP 17810 uniform mat3 lightMapTransform; 17811 varying vec2 vLightMapUv; 17812#endif 17813#ifdef USE_AOMAP 17814 uniform mat3 aoMapTransform; 17815 varying vec2 vAoMapUv; 17816#endif 17817#ifdef USE_BUMPMAP 17818 uniform mat3 bumpMapTransform; 17819 varying vec2 vBumpMapUv; 17820#endif 17821#ifdef USE_NORMALMAP 17822 uniform mat3 normalMapTransform; 17823 varying vec2 vNormalMapUv; 17824#endif 17825#ifdef USE_DISPLACEMENTMAP 17826 uniform mat3 displacementMapTransform; 17827 varying vec2 vDisplacementMapUv; 17828#endif 17829#ifdef USE_EMISSIVEMAP 17830 uniform mat3 emissiveMapTransform; 17831 varying vec2 vEmissiveMapUv; 17832#endif 17833#ifdef USE_METALNESSMAP 17834 uniform mat3 metalnessMapTransform; 17835 varying vec2 vMetalnessMapUv; 17836#endif 17837#ifdef USE_ROUGHNESSMAP 17838 uniform mat3 roughnessMapTransform; 17839 varying vec2 vRoughnessMapUv; 17840#endif 17841#ifdef USE_ANISOTROPYMAP 17842 uniform mat3 anisotropyMapTransform; 17843 varying vec2 vAnisotropyMapUv; 17844#endif 17845#ifdef USE_CLEARCOATMAP 17846 uniform mat3 clearcoatMapTransform; 17847 varying vec2 vClearcoatMapUv; 17848#endif 17849#ifdef USE_CLEARCOAT_NORMALMAP 17850 uniform mat3 clearcoatNormalMapTransform; 17851 varying vec2 vClearcoatNormalMapUv; 17852#endif 17853#ifdef USE_CLEARCOAT_ROUGHNESSMAP 17854 uniform mat3 clearcoatRoughnessMapTransform; 17855 varying vec2 vClearcoatRoughnessMapUv; 17856#endif 17857#ifdef USE_SHEEN_COLORMAP 17858 uniform mat3 sheenColorMapTransform; 17859 varying vec2 vSheenColorMapUv; 17860#endif 17861#ifdef USE_SHEEN_ROUGHNESSMAP 17862 uniform mat3 sheenRoughnessMapTransform; 17863 varying vec2 vSheenRoughnessMapUv; 17864#endif 17865#ifdef USE_IRIDESCENCEMAP 17866 uniform mat3 iridescenceMapTransform; 17867 varying vec2 vIridescenceMapUv; 17868#endif 17869#ifdef USE_IRIDESCENCE_THICKNESSMAP 17870 uniform mat3 iridescenceThicknessMapTransform; 17871 varying vec2 vIridescenceThicknessMapUv; 17872#endif 17873#ifdef USE_SPECULARMAP 17874 uniform mat3 specularMapTransform; 17875 varying vec2 vSpecularMapUv; 17876#endif 17877#ifdef USE_SPECULAR_COLORMAP 17878 uniform mat3 specularColorMapTransform; 17879 varying vec2 vSpecularColorMapUv; 17880#endif 17881#ifdef USE_SPECULAR_INTENSITYMAP 17882 uniform mat3 specularIntensityMapTransform; 17883 varying vec2 vSpecularIntensityMapUv; 17884#endif 17885#ifdef USE_TRANSMISSIONMAP 17886 uniform mat3 transmissionMapTransform; 17887 varying vec2 vTransmissionMapUv; 17888#endif 17889#ifdef USE_THICKNESSMAP 17890 uniform mat3 thicknessMapTransform; 17891 varying vec2 vThicknessMapUv; 17892#endif`, cb = `#if defined( USE_UV ) || defined( USE_ANISOTROPY ) 17893 vUv = vec3( uv, 1 ).xy; 17894#endif 17895#ifdef USE_MAP 17896 vMapUv = ( mapTransform * vec3( MAP_UV, 1 ) ).xy; 17897#endif 17898#ifdef USE_ALPHAMAP 17899 vAlphaMapUv = ( alphaMapTransform * vec3( ALPHAMAP_UV, 1 ) ).xy; 17900#endif 17901#ifdef USE_LIGHTMAP 17902 vLightMapUv = ( lightMapTransform * vec3( LIGHTMAP_UV, 1 ) ).xy; 17903#endif 17904#ifdef USE_AOMAP 17905 vAoMapUv = ( aoMapTransform * vec3( AOMAP_UV, 1 ) ).xy; 17906#endif 17907#ifdef USE_BUMPMAP 17908 vBumpMapUv = ( bumpMapTransform * vec3( BUMPMAP_UV, 1 ) ).xy; 17909#endif 17910#ifdef USE_NORMALMAP 17911 vNormalMapUv = ( normalMapTransform * vec3( NORMALMAP_UV, 1 ) ).xy; 17912#endif 17913#ifdef USE_DISPLACEMENTMAP 17914 vDisplacementMapUv = ( displacementMapTransform * vec3( DISPLACEMENTMAP_UV, 1 ) ).xy; 17915#endif 17916#ifdef USE_EMISSIVEMAP 17917 vEmissiveMapUv = ( emissiveMapTransform * vec3( EMISSIVEMAP_UV, 1 ) ).xy; 17918#endif 17919#ifdef USE_METALNESSMAP 17920 vMetalnessMapUv = ( metalnessMapTransform * vec3( METALNESSMAP_UV, 1 ) ).xy; 17921#endif 17922#ifdef USE_ROUGHNESSMAP 17923 vRoughnessMapUv = ( roughnessMapTransform * vec3( ROUGHNESSMAP_UV, 1 ) ).xy; 17924#endif 17925#ifdef USE_ANISOTROPYMAP 17926 vAnisotropyMapUv = ( anisotropyMapTransform * vec3( ANISOTROPYMAP_UV, 1 ) ).xy; 17927#endif 17928#ifdef USE_CLEARCOATMAP 17929 vClearcoatMapUv = ( clearcoatMapTransform * vec3( CLEARCOATMAP_UV, 1 ) ).xy; 17930#endif 17931#ifdef USE_CLEARCOAT_NORMALMAP 17932 vClearcoatNormalMapUv = ( clearcoatNormalMapTransform * vec3( CLEARCOAT_NORMALMAP_UV, 1 ) ).xy; 17933#endif 17934#ifdef USE_CLEARCOAT_ROUGHNESSMAP 17935 vClearcoatRoughnessMapUv = ( clearcoatRoughnessMapTransform * vec3( CLEARCOAT_ROUGHNESSMAP_UV, 1 ) ).xy; 17936#endif
17937#ifdef USE_IRIDESCENCEMAP 17938 vIridescenceMapUv = ( iridescenceMapTransform * vec3( IRIDESCENCEMAP_UV, 1 ) ).xy; 17939#endif 17940#ifdef USE_IRIDESCENCE_THICKNESSMAP 17941 vIridescenceThicknessMapUv = ( iridescenceThicknessMapTransform * vec3( IRIDESCENCE_THICKNESSMAP_UV, 1 ) ).xy; 17942#endif 17943#ifdef USE_SHEEN_COLORMAP 17944 vSheenColorMapUv = ( sheenColorMapTransform * vec3( SHEEN_COLORMAP_UV, 1 ) ).xy; 17945#endif 17946#ifdef USE_SHEEN_ROUGHNESSMAP 17947 vSheenRoughnessMapUv = ( sheenRoughnessMapTransform * vec3( SHEEN_ROUGHNESSMAP_UV, 1 ) ).xy; 17948#endif 17949#ifdef USE_SPECULARMAP 17950 vSpecularMapUv = ( specularMapTransform * vec3( SPECULARMAP_UV, 1 ) ).xy; 17951#endif 17952#ifdef USE_SPECULAR_COLORMAP 17953 vSpecularColorMapUv = ( specularColorMapTransform * vec3( SPECULAR_COLORMAP_UV, 1 ) ).xy; 17954#endif 17955#ifdef USE_SPECULAR_INTENSITYMAP 17956 vSpecularIntensityMapUv = ( specularIntensityMapTransform * vec3( SPECULAR_INTENSITYMAP_UV, 1 ) ).xy; 17957#endif 17958#ifdef USE_TRANSMISSIONMAP 17959 vTransmissionMapUv = ( transmissionMapTransform * vec3( TRANSMISSIONMAP_UV, 1 ) ).xy; 17960#endif 17961#ifdef USE_THICKNESSMAP 17962 vThicknessMapUv = ( thicknessMapTransform * vec3( THICKNESSMAP_UV, 1 ) ).xy; 17963#endif`, ub = `#if defined( USE_ENVMAP ) || defined( DISTANCE ) || defined ( USE_SHADOWMAP ) || defined ( USE_TRANSMISSION ) || NUM_SPOT_LIGHT_COORDS > 0 17964 vec4 worldPosition = vec4( transformed, 1.0 ); 17965 #ifdef USE_BATCHING 17966 worldPosition = batchingMatrix * worldPosition; 17967 #endif 17968 #ifdef USE_INSTANCING 17969 worldPosition = instanceMatrix * worldPosition; 17970 #endif 17971 worldPosition = modelMatrix * worldPosition; 17972#endif`; 17973const hb = `varying vec2 vUv; 17974uniform mat3 uvTransform; 17975void main() { 17976 vUv = ( uvTransform * vec3( uv, 1 ) ).xy; 17977 gl_Position = vec4( position.xy, 1.0, 1.0 ); 17978}`, db = `uniform sampler2D t2D; 17979uniform float backgroundIntensity; 17980varying vec2 vUv; 17981void main() { 17982 vec4 texColor = texture2D( t2D, vUv ); 17983 #ifdef DECODE_VIDEO_TEXTURE 17984 texColor = vec4( mix( pow( texColor.rgb * 0.9478672986 + vec3( 0.0521327014 ), vec3( 2.4 ) ), texColor.rgb * 0.0773993808, vec3( lessThanEqual( texColor.rgb, vec3( 0.04045 ) ) ) ), texColor.w ); 17985 #endif 17986 texColor.rgb *= backgroundIntensity; 17987 gl_FragColor = texColor; 17988 #include <tonemapping_fragment> 17989 #include <colorspace_fragment> 17990}`, fb = `varying vec3 vWorldDirection; 17991#include <common> 17992void main() { 17993 vWorldDirection = transformDirection( position, modelMatrix ); 17994 #include <begin_vertex> 17995 #include <project_vertex> 17996 gl_Position.z = gl_Position.w; 17997}`, pb = `#ifdef ENVMAP_TYPE_CUBE 17998 uniform samplerCube envMap; 17999#elif defined( ENVMAP_TYPE_CUBE_UV ) 18000 uniform sampler2D envMap; 18001#endif 18002uniform float backgroundBlurriness; 18003uniform float backgroundIntensity; 18004uniform mat3 backgroundRotation; 18005varying vec3 vWorldDirection; 18006#include <cube_uv_reflection_fragment> 18007void main() { 18008 #ifdef ENVMAP_TYPE_CUBE 18009 vec4 texColor = textureCube( envMap, backgroundRotation * vWorldDirection ); 18010 #elif defined( ENVMAP_TYPE_CUBE_UV ) 18011 vec4 texColor = textureCubeUV( envMap, backgroundRotation * vWorldDirection, backgroundBlurriness ); 18012 #else 18013 vec4 texColor = vec4( 0.0, 0.0, 0.0, 1.0 ); 18014 #endif 18015 texColor.rgb *= backgroundIntensity; 18016 gl_FragColor = texColor; 18017 #include <tonemapping_fragment> 18018 #include <colorspace_fragment> 18019}`, mb = `varying vec3 vWorldDirection; 18020#include <common> 18021void main() { 18022 vWorldDirection = transformDirection( position, modelMatrix ); 18023 #include <begin_vertex> 18024 #include <project_vertex> 18025 gl_Position.z = gl_Position.w; 18026}`, gb = `uniform samplerCube tCube; 18027uniform float tFlip; 18028uniform float opacity; 18029varying vec3 vWorldDirection; 18030void main() { 18031 vec4 texColor = textureCube( tCube, vec3( tFlip * vWorldDirection.x, vWorldDirection.yz ) ); 18032 gl_FragColor = texColor; 18033 gl_FragColor.a *= opacity; 18034 #include <tonemapping_fragment> 18035 #include <colorspace_fragment> 18036}`, vb = `#include <common> 18037#include <batching_pars_vertex> 18038#include <uv_pars_vertex> 18039#include <displacementmap_pars_vertex> 18040#include <morphtarget_pars_vertex> 18041#include <skinning_pars_vertex> 18042#include <logdepthbuf_pars_vertex> 18043#include <clipping_planes_pars_vertex> 18044varying vec2 vHighPrecisionZW; 18045void main() { 18046 #include <uv_vertex> 18047 #include <batching_vertex> 18048 #include <skinbase_vertex> 18049 #include <morphinstance_vertex> 18050 #ifdef USE_DISPLACEMENTMAP 18051 #include <beginnormal_vertex> 18052 #include <morphnormal_vertex> 18053 #include <skinnormal_vertex> 18054 #endif 18055 #include <begin_vertex> 18056 #include <morphtarget_vertex> 18057 #include <skinning_vertex> 18058 #include <displacementmap_vertex> 18059 #include <project_vertex> 18060 #include <logdepthbuf_vertex> 18061 #include <clipping_planes_vertex> 18062 vHighPrecisionZW = gl_Position.zw; 18063}`, _b = `#if DEPTH_PACKING == 3200 18064 uniform float opacity; 18065#endif 18066#include <common> 18067#include <packing> 18068#include <uv_pars_fragment> 18069#include <map_pars_fragment> 18070#include <alphamap_pars_fragment> 18071#include <alphatest_pars_fragment> 18072#include <alphahash_pars_fragment> 18073#include <logdepthbuf_pars_fragment> 18074#include <clipping_planes_pars_fragment> 18075varying vec2 vHighPrecisionZW; 18076void main() { 18077 vec4 diffuseColor = vec4( 1.0 ); 18078 #include <clipping_planes_fragment> 18079 #if DEPTH_PACKING == 3200 18080 diffuseColor.a = opacity; 18081 #endif 18082 #include <map_fragment> 18083 #include <alphamap_fragment> 18084 #include <alphatest_fragment> 18085 #include <alphahash_fragment> 18086 #include <logdepthbuf_fragment> 18087 #ifdef USE_REVERSED_DEPTH_BUFFER 18088 float fragCoordZ = vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ]; 18089 #else 18090 float fragCoordZ = 0.5 * vHighPrecisionZW[ 0 ] / vHighPrecisionZW[ 1 ] + 0.5; 18091 #endif 18092 #if DEPTH_PACKING == 3200 18093 gl_FragColor = vec4( vec3( 1.0 - fragCoordZ ), opacity ); 18094 #elif DEPTH_PACKING == 3201 18095 gl_FragColor = packDepthToRGBA( fragCoordZ ); 18096 #elif DEPTH_PACKING == 3202 18097 gl_FragColor = vec4( packDepthToRGB( fragCoordZ ), 1.0 ); 18098 #elif DEPTH_PACKING == 3203 18099 gl_FragColor = vec4( packDepthToRG( fragCoordZ ), 0.0, 1.0 ); 18100 #endif 18101}`, yb = `#define DISTANCE 18102varying vec3 vWorldPosition; 18103#include <common> 18104#include <batching_pars_vertex> 18105#include <uv_pars_vertex> 18106#include <displacementmap_pars_vertex> 18107#include <morphtarget_pars_vertex> 18108#include <skinning_pars_vertex> 18109#include <clipping_planes_pars_vertex> 18110void main() { 18111 #include <uv_vertex> 18112 #include <batching_vertex> 18113 #include <skinbase_vertex> 18114 #include <morphinstance_vertex> 18115 #ifdef USE_DISPLACEMENTMAP 18116 #include <beginnormal_vertex> 18117 #include <morphnormal_vertex> 18118 #include <skinnormal_vertex> 18119 #endif 18120 #include <begin_vertex> 18121 #include <morphtarget_vertex> 18122 #include <skinning_vertex> 18123 #include <displacementmap_vertex> 18124 #include <project_vertex> 18125 #include <worldpos_vertex> 18126 #include <clipping_planes_vertex> 18127 vWorldPosition = worldPosition.xyz; 18128}`, xb = `#define DISTANCE 18129uniform vec3 referencePosition; 18130uniform float nearDistance; 18131uniform float farDistance; 18132varying vec3 vWorldPosition; 18133#include <common> 18134#include <uv_pars_fragment> 18135#include <map_pars_fragment> 18136#include <alphamap_pars_fragment> 18137#include <alphatest_pars_fragment> 18138#include <alphahash_pars_fragment> 18139#include <clipping_planes_pars_fragment> 18140void main () { 18141 vec4 diffuseColor = vec4( 1.0 ); 18142 #include <clipping_planes_fragment> 18143 #include <map_fragment> 18144 #include <alphamap_fragment> 18145 #include <alphatest_fragment> 18146 #include <alphahash_fragment> 18147 float dist = length( vWorldPosition - referencePosition ); 18148 dist = ( dist - nearDistance ) / ( farDistance - nearDistance ); 18149 dist = saturate( dist ); 18150 gl_FragColor = vec4( dist, 0.0, 0.0, 1.0 ); 18151}`, bb = `varying vec3 vWorldDirection; 18152#include <common> 18153void main() { 18154 vWorldDirection = transformDirection( position, modelMatrix ); 18155 #include <begin_vertex> 18156 #include <project_vertex> 18157}`, wb = `uniform sampler2D tEquirect; 18158varying vec3 vWorldDirection; 18159#include <common> 18160void main() { 18161 vec3 direction = normalize( vWorldDirection ); 18162 vec2 sampleUV = equirectUv( direction ); 18163 gl_FragColor = texture2D( tEquirect, sampleUV ); 18164 #include <tonemapping_fragment> 18165 #include <colorspace_fragment> 18166}`, Sb = `uniform float scale; 18167attribute float lineDistance; 18168varying float vLineDistance; 18169#include <common> 18170#include <uv_pars_vertex> 18171#include <color_pars_vertex> 18172#include <fog_pars_vertex> 18173#include <morphtarget_pars_vertex> 18174#include <logdepthbuf_pars_vertex> 18175#include <clipping_planes_pars_vertex> 18176void main() { 18177 vLineDistance = scale * lineDistance; 18178 #include <uv_vertex> 18179 #include <color_vertex> 18180 #include <morphinstance_vertex> 18181 #include <morphcolor_vertex> 18182 #include <begin_vertex> 18183 #include <morphtarget_vertex> 18184 #include <project_vertex> 18185 #include <logdepthbuf_vertex> 18186 #include <clipping_planes_vertex> 18187 #include <fog_vertex> 18188}`, Eb = `uniform vec3 diffuse; 18189uniform float opacity; 18190uniform float dashSize; 18191uniform float totalSize; 18192varying float vLineDistance; 18193#include <common> 18194#include <color_pars_fragment> 18195#include <uv_pars_fragment> 18196#include <map_pars_fragment> 18197#include <fog_pars_fragment> 18198#include <logdepthbuf_pars_fragment> 18199#include <clipping_planes_pars_fragment> 18200void main() { 18201 vec4 diffuseColor = vec4( diffuse, opacity ); 18202 #include <clipping_planes_fragment> 18203 if ( mod( vLineDistance, totalSize ) > dashSize ) { 18204 discard; 18205 } 18206 vec3 outgoingLight = vec3( 0.0 ); 18207 #include <logdepthbuf_fragment> 18208 #include <map_fragment> 18209 #include <color_fragment> 18210 outgoingLight = diffuseColor.rgb; 18211 #include <opaque_fragment> 18212 #include <tonemapping_fragment> 18213 #include <colorspace_fragment> 18214 #include <fog_fragment> 18215 #include <premultiplied_alpha_fragment> 18216}`, Mb = `#include <common> 18217#include <batching_pars_vertex> 18218#include <uv_pars_vertex> 18219#include <envmap_pars_vertex> 18220#include <color_pars_vertex> 18221#include <fog_pars_vertex> 18222#include <morphtarget_pars_vertex> 18223#include <skinning_pars_vertex> 18224#include <logdepthbuf_pars_vertex> 18225#include <clipping_planes_pars_vertex> 18226void main() { 18227 #include <uv_vertex> 18228 #include <color_vertex> 18229 #include <morphinstance_vertex> 18230 #include <morphcolor_vertex> 18231 #include <batching_vertex> 18232 #if defined ( USE_ENVMAP ) || defined ( USE_SKINNING ) 18233 #include <beginnormal_vertex> 18234 #include <morphnormal_vertex> 18235 #include <skinbase_vertex> 18236 #include <skinnormal_vertex> 18237 #include <defaultnormal_vertex> 18238 #endif 18239 #include <begin_vertex> 18240 #include <morphtarget_vertex> 18241 #include <skinning_vertex> 18242 #include <project_vertex> 18243 #include <logdepthbuf_vertex> 18244 #include <clipping_planes_vertex> 18245 #include <worldpos_vertex> 18246 #include <envmap_vertex> 18247 #include <fog_vertex> 18248}`, Tb = `uniform vec3 diffuse; 18249uniform float opacity; 18250#ifndef FLAT_SHADED 18251 varying vec3 vNormal; 18252#endif 18253#include <common> 18254#include <dithering_pars_fragment> 18255#include <color_pars_fragment> 18256#include <uv_pars_fragment> 18257#include <map_pars_fragment> 18258#include <alphamap_pars_fragment> 18259#include <alphatest_pars_fragment> 18260#include <alphahash_pars_fragment> 18261#include <aomap_pars_fragment> 18262#include <lightmap_pars_fragment> 18263#include <envmap_common_pars_fragment> 18264#include <envmap_pars_fragment> 18265#include <fog_pars_fragment> 18266#include <specularmap_pars_fragment> 18267#include <logdepthbuf_pars_fragment> 18268#include <clipping_planes_pars_fragment> 18269void main() { 18270 vec4 diffuseColor = vec4( diffuse, opacity ); 18271 #include <clipping_planes_fragment> 18272 #include <logdepthbuf_fragment> 18273 #include <map_fragment> 18274 #include <color_fragment> 18275 #include <alphamap_fragment> 18276 #include <alphatest_fragment> 18277 #include <alphahash_fragment> 18278 #include <specularmap_fragment> 18279 ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); 18280 #ifdef USE_LIGHTMAP 18281 vec4 lightMapTexel = texture2D( lightMap, vLightMapUv ); 18282 reflectedLight.indirectDiffuse += lightMapTexel.rgb * lightMapIntensity * RECIPROCAL_PI; 18283 #else 18284 reflectedLight.indirectDiffuse += vec3( 1.0 ); 18285 #endif 18286 #include <aomap_fragment> 18287 reflectedLight.indirectDiffuse *= diffuseColor.rgb; 18288 vec3 outgoingLight = reflectedLight.indirectDiffuse; 18289 #include <envmap_fragment> 18290 #include <opaque_fragment> 18291 #include <tonemapping_fragment> 18292 #include <colorspace_fragment> 18293 #include <fog_fragment> 18294 #include <premultiplied_alpha_fragment> 18295 #include <dithering_fragment> 18296}`, Ab = `#define LAMBERT 18297varying vec3 vViewPosition; 18298#include <common> 18299#include <batching_pars_vertex> 18300#include <uv_pars_vertex> 18301#include <displacementmap_pars_vertex> 18302#include <envmap_pars_vertex> 18303#include <color_pars_vertex> 18304#include <fog_pars_vertex> 18305#include <normal_pars_vertex> 18306#include <morphtarget_pars_vertex> 18307#include <skinning_pars_vertex> 18308#include <shadowmap_pars_vertex> 18309#include <logdepthbuf_pars_vertex> 18310#include <clipping_planes_pars_vertex> 18311void main() { 18312 #include <uv_vertex> 18313 #include <color_vertex> 18314 #include <morphinstance_vertex> 18315 #include <morphcolor_vertex> 18316 #include <batching_vertex> 18317 #include <beginnormal_vertex> 18318 #include <morphnormal_vertex> 18319 #include <skinbase_vertex> 18320 #include <skinnormal_vertex> 18321 #include <defaultnormal_vertex> 18322 #include <normal_vertex> 18323 #include <begin_vertex> 18324 #include <morphtarget_vertex> 18325 #include <skinning_vertex> 18326 #include <displacementmap_vertex> 18327 #include <project_vertex> 18328 #include <logdepthbuf_vertex> 18329 #include <clipping_planes_vertex> 18330 vViewPosition = - mvPosition.xyz; 18331 #include <worldpos_vertex> 18332 #include <envmap_vertex> 18333 #include <shadowmap_vertex> 18334 #include <fog_vertex> 18335}`, Rb = `#define LAMBERT 18336uniform vec3 diffuse; 18337uniform vec3 emissive; 18338uniform float opacity; 18339#include <common> 18340#include <dithering_pars_fragment> 18341#include <color_pars_fragment> 18342#include <uv_pars_fragment> 18343#include <map_pars_fragment> 18344#include <alphamap_pars_fragment> 18345#include <alphatest_pars_fragment> 18346#include <alphahash_pars_fragment> 18347#include <aomap_pars_fragment> 18348#include <lightmap_pars_fragment> 18349#include <emissivemap_pars_fragment> 18350#include <cube_uv_reflection_fragment> 18351#include <envmap_common_pars_fragment> 18352#include <envmap_pars_fragment> 18353#include <envmap_physical_pars_fragment> 18354#include <fog_pars_fragment> 18355#include <bsdfs> 18356#include <lights_pars_begin> 18357#include <normal_pars_fragment> 18358#include <lights_lambert_pars_fragment> 18359#include <shadowmap_pars_fragment> 18360#include <bumpmap_pars_fragment> 18361#include <normalmap_pars_fragment> 18362#include <specularmap_pars_fragment> 18363#include <logdepthbuf_pars_fragment> 18364#include <clipping_planes_pars_fragment> 18365void main() { 18366 vec4 diffuseColor = vec4( diffuse, opacity ); 18367 #include <clipping_planes_fragment> 18368 ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); 18369 vec3 totalEmissiveRadiance = emissive; 18370 #include <logdepthbuf_fragment> 18371 #include <map_fragment> 18372 #include <color_fragment> 18373 #include <alphamap_fragment> 18374 #include <alphatest_fragment> 18375 #include <alphahash_fragment> 18376 #include <specularmap_fragment> 18377 #include <normal_fragment_begin> 18378 #include <normal_fragment_maps> 18379 #include <emissivemap_fragment> 18380 #include <lights_lambert_fragment> 18381 #include <lights_fragment_begin> 18382 #include <lights_fragment_maps> 18383 #include <lights_fragment_end> 18384 #include <aomap_fragment> 18385 vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; 18386 #include <envmap_fragment> 18387 #include <opaque_fragment> 18388 #include <tonemapping_fragment> 18389 #include <colorspace_fragment> 18390 #include <fog_fragment> 18391 #include <premultiplied_alpha_fragment> 18392 #include <dithering_fragment> 18393}`, Cb = `#define MATCAP 18394varying vec3 vViewPosition; 18395#include <common> 18396#include <batching_pars_vertex> 18397#include <uv_pars_vertex> 18398#include <color_pars_vertex> 18399#include <displacementmap_pars_vertex> 18400#include <fog_pars_vertex> 18401#include <normal_pars_vertex> 18402#include <morphtarget_pars_vertex> 18403#include <skinning_pars_vertex> 18404#include <logdepthbuf_pars_vertex> 18405#include <clipping_planes_pars_vertex> 18406void main() { 18407 #include <uv_vertex> 18408 #include <color_vertex> 18409 #include <morphinstance_vertex> 18410 #include <morphcolor_vertex> 18411 #include <batching_vertex> 18412 #include <beginnormal_vertex> 18413 #include <morphnormal_vertex> 18414 #include <skinbase_vertex> 18415 #include <skinnormal_vertex> 18416 #include <defaultnormal_vertex> 18417 #include <normal_vertex> 18418 #include <begin_vertex> 18419 #include <morphtarget_vertex> 18420 #include <skinning_vertex> 18421 #include <displacementmap_vertex> 18422 #include <project_vertex> 18423 #include <logdepthbuf_vertex> 18424 #include <clipping_planes_vertex> 18425 #include <fog_vertex> 18426 vViewPosition = - mvPosition.xyz; 18427}`, Pb = `#define MATCAP 18428uniform vec3 diffuse; 18429uniform float opacity; 18430uniform sampler2D matcap; 18431varying vec3 vViewPosition; 18432#include <common> 18433#include <dithering_pars_fragment> 18434#include <color_pars_fragment> 18435#include <uv_pars_fragment> 18436#include <map_pars_fragment> 18437#include <alphamap_pars_fragment> 18438#include <alphatest_pars_fragment> 18439#include <alphahash_pars_fragment> 18440#include <fog_pars_fragment> 18441#include <normal_pars_fragment> 18442#
18442include <bumpmap_pars_fragment> 18443#include <normalmap_pars_fragment> 18444#include <logdepthbuf_pars_fragment> 18445#include <clipping_planes_pars_fragment> 18446void main() { 18447 vec4 diffuseColor = vec4( diffuse, opacity ); 18448 #include <clipping_planes_fragment> 18449 #include <logdepthbuf_fragment> 18450 #include <map_fragment> 18451 #include <color_fragment> 18452 #include <alphamap_fragment> 18453 #include <alphatest_fragment> 18454 #include <alphahash_fragment> 18455 #include <normal_fragment_begin> 18456 #include <normal_fragment_maps> 18457 vec3 viewDir = normalize( vViewPosition ); 18458 vec3 x = normalize( vec3( viewDir.z, 0.0, - viewDir.x ) ); 18459 vec3 y = cross( viewDir, x ); 18460 vec2 uv = vec2( dot( x, normal ), dot( y, normal ) ) * 0.495 + 0.5; 18461 #ifdef USE_MATCAP 18462 vec4 matcapColor = texture2D( matcap, uv ); 18463 #else 18464 vec4 matcapColor = vec4( vec3( mix( 0.2, 0.8, uv.y ) ), 1.0 ); 18465 #endif 18466 vec3 outgoingLight = diffuseColor.rgb * matcapColor.rgb; 18467 #include <opaque_fragment> 18468 #include <tonemapping_fragment> 18469 #include <colorspace_fragment> 18470 #include <fog_fragment> 18471 #include <premultiplied_alpha_fragment> 18472 #include <dithering_fragment> 18473}`, Lb = `#define NORMAL 18474#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) 18475 varying vec3 vViewPosition; 18476#endif 18477#include <common> 18478#include <batching_pars_vertex> 18479#include <uv_pars_vertex> 18480#include <displacementmap_pars_vertex> 18481#include <normal_pars_vertex> 18482#include <morphtarget_pars_vertex> 18483#include <skinning_pars_vertex> 18484#include <logdepthbuf_pars_vertex> 18485#include <clipping_planes_pars_vertex> 18486void main() { 18487 #include <uv_vertex> 18488 #include <batching_vertex> 18489 #include <beginnormal_vertex> 18490 #include <morphinstance_vertex> 18491 #include <morphnormal_vertex> 18492 #include <skinbase_vertex> 18493 #include <skinnormal_vertex> 18494 #include <defaultnormal_vertex> 18495 #include <normal_vertex> 18496 #include <begin_vertex> 18497 #include <morphtarget_vertex> 18498 #include <skinning_vertex> 18499 #include <displacementmap_vertex> 18500 #include <project_vertex> 18501 #include <logdepthbuf_vertex> 18502 #include <clipping_planes_vertex> 18503#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) 18504 vViewPosition = - mvPosition.xyz; 18505#endif 18506}`, Nb = `#define NORMAL 18507uniform float opacity; 18508#if defined( FLAT_SHADED ) || defined( USE_BUMPMAP ) || defined( USE_NORMALMAP_TANGENTSPACE ) 18509 varying vec3 vViewPosition; 18510#endif 18511#include <uv_pars_fragment> 18512#include <normal_pars_fragment> 18513#include <bumpmap_pars_fragment> 18514#include <normalmap_pars_fragment> 18515#include <logdepthbuf_pars_fragment> 18516#include <clipping_planes_pars_fragment> 18517void main() { 18518 vec4 diffuseColor = vec4( 0.0, 0.0, 0.0, opacity ); 18519 #include <clipping_planes_fragment> 18520 #include <logdepthbuf_fragment> 18521 #include <normal_fragment_begin> 18522 #include <normal_fragment_maps> 18523 gl_FragColor = vec4( normalize( normal ) * 0.5 + 0.5, diffuseColor.a ); 18524 #ifdef OPAQUE 18525 gl_FragColor.a = 1.0; 18526 #endif 18527}`, Ib = `#define PHONG 18528varying vec3 vViewPosition; 18529#include <common> 18530#include <batching_pars_vertex> 18531#include <uv_pars_vertex> 18532#include <displacementmap_pars_vertex> 18533#include <envmap_pars_vertex> 18534#include <color_pars_vertex> 18535#include <fog_pars_vertex> 18536#include <normal_pars_vertex> 18537#include <morphtarget_pars_vertex> 18538#include <skinning_pars_vertex> 18539#include <shadowmap_pars_vertex> 18540#include <logdepthbuf_pars_vertex> 18541#include <clipping_planes_pars_vertex> 18542void main() { 18543 #include <uv_vertex> 18544 #include <color_vertex> 18545 #include <morphcolor_vertex> 18546 #include <batching_vertex> 18547 #include <beginnormal_vertex> 18548 #include <morphinstance_vertex> 18549 #include <morphnormal_vertex> 18550 #include <skinbase_vertex> 18551 #include <skinnormal_vertex> 18552 #include <defaultnormal_vertex> 18553 #include <normal_vertex> 18554 #include <begin_vertex> 18555 #include <morphtarget_vertex> 18556 #include <skinning_vertex> 18557 #include <displacementmap_vertex> 18558 #include <project_vertex> 18559 #include <logdepthbuf_vertex> 18560 #include <clipping_planes_vertex> 18561 vViewPosition = - mvPosition.xyz; 18562 #include <worldpos_vertex> 18563 #include <envmap_vertex> 18564 #include <shadowmap_vertex> 18565 #include <fog_vertex> 18566}`, Db = `#define PHONG 18567uniform vec3 diffuse; 18568uniform vec3 emissive; 18569uniform vec3 specular; 18570uniform float shininess; 18571uniform float opacity; 18572#include <common> 18573#include <dithering_pars_fragment> 18574#include <color_pars_fragment> 18575#include <uv_pars_fragment> 18576#include <map_pars_fragment> 18577#include <alphamap_pars_fragment> 18578#include <alphatest_pars_fragment> 18579#include <alphahash_pars_fragment> 18580#include <aomap_pars_fragment> 18581#include <lightmap_pars_fragment> 18582#include <emissivemap_pars_fragment> 18583#include <cube_uv_reflection_fragment> 18584#include <envmap_common_pars_fragment> 18585#include <envmap_pars_fragment> 18586#include <envmap_physical_pars_fragment> 18587#include <fog_pars_fragment> 18588#include <bsdfs> 18589#include <lights_pars_begin> 18590#include <normal_pars_fragment> 18591#include <lights_phong_pars_fragment> 18592#include <shadowmap_pars_fragment> 18593#include <bumpmap_pars_fragment> 18594#include <normalmap_pars_fragment> 18595#include <specularmap_pars_fragment> 18596#include <logdepthbuf_pars_fragment> 18597#include <clipping_planes_pars_fragment> 18598void main() { 18599 vec4 diffuseColor = vec4( diffuse, opacity ); 18600 #include <clipping_planes_fragment> 18601 ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); 18602 vec3 totalEmissiveRadiance = emissive; 18603 #include <logdepthbuf_fragment> 18604 #include <map_fragment> 18605 #include <color_fragment> 18606 #include <alphamap_fragment> 18607 #include <alphatest_fragment> 18608 #include <alphahash_fragment> 18609 #include <specularmap_fragment> 18610 #include <normal_fragment_begin> 18611 #include <normal_fragment_maps> 18612 #include <emissivemap_fragment> 18613 #include <lights_phong_fragment> 18614 #include <lights_fragment_begin> 18615 #include <lights_fragment_maps> 18616 #include <lights_fragment_end> 18617 #include <aomap_fragment> 18618 vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + reflectedLight.directSpecular + reflectedLight.indirectSpecular + totalEmissiveRadiance; 18619 #include <envmap_fragment> 18620 #include <opaque_fragment> 18621 #include <tonemapping_fragment> 18622 #include <colorspace_fragment> 18623 #include <fog_fragment> 18624 #include <premultiplied_alpha_fragment> 18625 #include <dithering_fragment> 18626}`, Ub = `#define STANDARD 18627varying vec3 vViewPosition; 18628#ifdef USE_TRANSMISSION 18629 varying vec3 vWorldPosition; 18630#endif 18631#include <common> 18632#include <batching_pars_vertex> 18633#include <uv_pars_vertex> 18634#include <displacementmap_pars_vertex> 18635#include <color_pars_vertex> 18636#include <fog_pars_vertex> 18637#include <normal_pars_vertex> 18638#include <morphtarget_pars_vertex> 18639#include <skinning_pars_vertex> 18640#include <shadowmap_pars_vertex> 18641#include <logdepthbuf_pars_vertex> 18642#include <clipping_planes_pars_vertex> 18643void main() { 18644 #include <uv_vertex> 18645 #include <color_vertex> 18646 #include <morphinstance_vertex> 18647 #include <morphcolor_vertex> 18648 #include <batching_vertex> 18649 #include <beginnormal_vertex> 18650 #include <morphnormal_vertex> 18651 #include <skinbase_vertex> 18652 #include <skinnormal_vertex> 18653 #include <defaultnormal_vertex> 18654 #include <normal_vertex> 18655 #include <begin_vertex> 18656 #include <morphtarget_vertex> 18657 #include <skinning_vertex> 18658 #include <displacementmap_vertex> 18659 #include <project_vertex> 18660 #include <logdepthbuf_vertex> 18661 #include <clipping_planes_vertex> 18662 vViewPosition = - mvPosition.xyz; 18663 #include <worldpos_vertex> 18664 #include <shadowmap_vertex> 18665 #include <fog_vertex> 18666#ifdef USE_TRANSMISSION 18667 vWorldPosition = worldPosition.xyz; 18668#endif 18669}`, Ob = `#define STANDARD 18670#ifdef PHYSICAL 18671 #define IOR 18672 #define USE_SPECULAR 18673#endif 18674uniform vec3 diffuse; 18675uniform vec3 emissive; 18676uniform float roughness; 18677uniform float metalness; 18678uniform float opacity; 18679#ifdef IOR 18680 uniform float ior; 18681#endif 18682#ifdef USE_SPECULAR 18683 uniform float specularIntensity; 18684 uniform vec3 specularColor; 18685 #ifdef USE_SPECULAR_COLORMAP 18686 uniform sampler2D specularColorMap; 18687 #endif 18688 #ifdef USE_SPECULAR_INTENSITYMAP 18689 uniform sampler2D specularIntensityMap; 18690 #endif 18691#endif 18692#ifdef USE_CLEARCOAT 18693 uniform float clearcoat; 18694 uniform float clearcoatRoughness; 18695#endif 18696#ifdef USE_DISPERSION 18697 uniform float dispersion; 18698#endif
18699#ifdef USE_IRIDESCENCE 18700 uniform float iridescence; 18701 uniform float iridescenceIOR; 18702 uniform float iridescenceThicknessMinimum; 18703 uniform float iridescenceThicknessMaximum; 18704#endif 18705#ifdef USE_SHEEN 18706 uniform vec3 sheenColor; 18707 uniform float sheenRoughness; 18708 #ifdef USE_SHEEN_COLORMAP 18709 uniform sampler2D sheenColorMap; 18710 #endif 18711 #ifdef USE_SHEEN_ROUGHNESSMAP 18712 uniform sampler2D sheenRoughnessMap; 18713 #endif 18714#endif 18715#ifdef USE_ANISOTROPY 18716 uniform vec2 anisotropyVector; 18717 #ifdef USE_ANISOTROPYMAP 18718 uniform sampler2D anisotropyMap; 18719 #endif 18720#endif 18721varying vec3 vViewPosition; 18722#include <common> 18723#include <dithering_pars_fragment> 18724#include <color_pars_fragment> 18725#include <uv_pars_fragment> 18726#include <map_pars_fragment> 18727#include <alphamap_pars_fragment> 18728#include <alphatest_pars_fragment> 18729#include <alphahash_pars_fragment> 18730#include <aomap_pars_fragment> 18731#include <lightmap_pars_fragment> 18732#include <emissivemap_pars_fragment> 18733#include <iridescence_fragment> 18734#include <cube_uv_reflection_fragment> 18735#include <envmap_common_pars_fragment> 18736#include <envmap_physical_pars_fragment> 18737#include <fog_pars_fragment> 18738#include <lights_pars_begin> 18739#include <normal_pars_fragment> 18740#include <lights_physical_pars_fragment> 18741#include <transmission_pars_fragment> 18742#include <shadowmap_pars_fragment> 18743#include <bumpmap_pars_fragment> 18744#include <normalmap_pars_fragment> 18745#include <clearcoat_pars_fragment> 18746#include <iridescence_pars_fragment> 18747#include <roughnessmap_pars_fragment> 18748#include <metalnessmap_pars_fragment> 18749#include <logdepthbuf_pars_fragment> 18750#include <clipping_planes_pars_fragment> 18751void main() { 18752 vec4 diffuseColor = vec4( diffuse, opacity ); 18753 #include <clipping_planes_fragment> 18754 ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); 18755 vec3 totalEmissiveRadiance = emissive; 18756 #include <logdepthbuf_fragment> 18757 #include <map_fragment> 18758 #include <color_fragment> 18759 #include <alphamap_fragment> 18760 #include <alphatest_fragment> 18761 #include <alphahash_fragment> 18762 #include <roughnessmap_fragment> 18763 #include <metalnessmap_fragment> 18764 #include <normal_fragment_begin> 18765 #include <normal_fragment_maps> 18766 #include <clearcoat_normal_fragment_begin> 18767 #include <clearcoat_normal_fragment_maps> 18768 #include <emissivemap_fragment> 18769 #include <lights_physical_fragment> 18770 #include <lights_fragment_begin> 18771 #include <lights_fragment_maps> 18772 #include <lights_fragment_end> 18773 #include <aomap_fragment> 18774 vec3 totalDiffuse = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse; 18775 vec3 totalSpecular = reflectedLight.directSpecular + reflectedLight.indirectSpecular; 18776 #include <transmission_fragment> 18777 vec3 outgoingLight = totalDiffuse + totalSpecular + totalEmissiveRadiance; 18778 #ifdef USE_SHEEN 18779 18780 outgoingLight = outgoingLight + sheenSpecularDirect + sheenSpecularIndirect; 18781 18782 #endif 18783 #ifdef USE_CLEARCOAT 18784 float dotNVcc = saturate( dot( geometryClearcoatNormal, geometryViewDir ) ); 18785 vec3 Fcc = F_Schlick( material.clearcoatF0, material.clearcoatF90, dotNVcc ); 18786 outgoingLight = outgoingLight * ( 1.0 - material.clearcoat * Fcc ) + ( clearcoatSpecularDirect + clearcoatSpecularIndirect ) * material.clearcoat; 18787 #endif 18788 #include <opaque_fragment> 18789 #include <tonemapping_fragment> 18790 #include <colorspace_fragment> 18791 #include <fog_fragment> 18792 #include <premultiplied_alpha_fragment> 18793 #include <dithering_fragment> 18794}`, kb = `#define TOON 18795varying vec3 vViewPosition; 18796#include <common> 18797#include <batching_pars_vertex> 18798#include <uv_pars_vertex> 18799#include <displacementmap_pars_vertex> 18800#include <color_pars_vertex> 18801#include <fog_pars_vertex> 18802#include <normal_pars_vertex> 18803#include <morphtarget_pars_vertex> 18804#include <skinning_pars_vertex> 18805#include <shadowmap_pars_vertex> 18806#include <logdepthbuf_pars_vertex> 18807#include <clipping_planes_pars_vertex> 18808void main() { 18809 #include <uv_vertex> 18810 #include <color_vertex> 18811 #include <morphinstance_vertex> 18812 #include <morphcolor_vertex> 18813 #include <batching_vertex> 18814 #include <beginnormal_vertex> 18815 #include <morphnormal_vertex> 18816 #include <skinbase_vertex> 18817 #include <skinnormal_vertex> 18818 #include <defaultnormal_vertex> 18819 #include <normal_vertex> 18820 #include <begin_vertex> 18821 #include <morphtarget_vertex> 18822 #include <skinning_vertex> 18823 #include <displacementmap_vertex> 18824 #include <project_vertex> 18825 #include <logdepthbuf_vertex> 18826 #include <clipping_planes_vertex> 18827 vViewPosition = - mvPosition.xyz; 18828 #include <worldpos_vertex> 18829 #include <shadowmap_vertex> 18830 #include <fog_vertex> 18831}`, Fb = `#define TOON 18832uniform vec3 diffuse; 18833uniform vec3 emissive; 18834uniform float opacity; 18835#include <common> 18836#include <dithering_pars_fragment> 18837#include <color_pars_fragment> 18838#include <uv_pars_fragment> 18839#include <map_pars_fragment> 18840#include <alphamap_pars_fragment> 18841#include <alphatest_pars_fragment> 18842#include <alphahash_pars_fragment> 18843#include <aomap_pars_fragment> 18844#include <lightmap_pars_fragment> 18845#include <emissivemap_pars_fragment> 18846#include <gradientmap_pars_fragment> 18847#include <fog_pars_fragment> 18848#include <bsdfs> 18849#include <lights_pars_begin> 18850#include <normal_pars_fragment> 18851#include <lights_toon_pars_fragment> 18852#include <shadowmap_pars_fragment> 18853#include <bumpmap_pars_fragment> 18854#include <normalmap_pars_fragment> 18855#include <logdepthbuf_pars_fragment> 18856#include <clipping_planes_pars_fragment> 18857void main() { 18858 vec4 diffuseColor = vec4( diffuse, opacity ); 18859 #include <clipping_planes_fragment> 18860 ReflectedLight reflectedLight = ReflectedLight( vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ), vec3( 0.0 ) ); 18861 vec3 totalEmissiveRadiance = emissive; 18862 #include <logdepthbuf_fragment> 18863 #include <map_fragment> 18864 #include <color_fragment> 18865 #include <alphamap_fragment> 18866 #include <alphatest_fragment> 18867 #include <alphahash_fragment> 18868 #include <normal_fragment_begin> 18869 #include <normal_fragment_maps> 18870 #include <emissivemap_fragment> 18871 #include <lights_toon_fragment> 18872 #include <lights_fragment_begin> 18873 #include <lights_fragment_maps> 18874 #include <lights_fragment_end> 18875 #include <aomap_fragment> 18876 vec3 outgoingLight = reflectedLight.directDiffuse + reflectedLight.indirectDiffuse + totalEmissiveRadiance; 18877 #include <opaque_fragment> 18878 #include <tonemapping_fragment> 18879 #include <colorspace_fragment> 18880 #include <fog_fragment> 18881 #include <premultiplied_alpha_fragment> 18882 #include <dithering_fragment> 18883}`, Bb = `uniform float size; 18884uniform float scale; 18885#include <common> 18886#include <color_pars_vertex> 18887#include <fog_pars_vertex> 18888#include <morphtarget_pars_vertex> 18889#include <logdepthbuf_pars_vertex> 18890#include <clipping_planes_pars_vertex> 18891#ifdef USE_POINTS_UV 18892 varying vec2 vUv; 18893 uniform mat3 uvTransform; 18894#endif 18895void main() { 18896 #ifdef USE_POINTS_UV 18897 vUv = ( uvTransform * vec3( uv, 1 ) ).xy; 18898 #endif 18899 #include <color_vertex> 18900 #include <morphinstance_vertex> 18901 #include <morphcolor_vertex> 18902 #include <begin_vertex> 18903 #include <morphtarget_vertex> 18904 #include <project_vertex> 18905 gl_PointSize = size; 18906 #ifdef USE_SIZEATTENUATION 18907 bool isPerspective = isPerspectiveMatrix( projectionMatrix ); 18908 if ( isPerspective ) gl_PointSize *= ( scale / - mvPosition.z ); 18909 #endif 18910 #include <logdepthbuf_vertex> 18911 #include <clipping_planes_vertex> 18912 #include <worldpos_vertex> 18913 #include <fog_vertex> 18914}`, zb = `uniform vec3 diffuse; 18915uniform float opacity; 18916#include <common> 18917#include <color_pars_fragment> 18918#include <map_particle_pars_fragment> 18919#include <alphatest_pars_fragment> 18920#include <alphahash_pars_fragment> 18921#include <fog_pars_fragment> 18922#include <logdepthbuf_pars_fragment> 18923#include <clipping_planes_pars_fragment> 18924void main() { 18925 vec4 diffuseColor = vec4( diffuse, opacity ); 18926 #include <clipping_planes_fragment> 18927 vec3 outgoingLight = vec3( 0.0 ); 18928 #include <logdepthbuf_fragment> 18929 #include <map_particle_fragment> 18930 #include <color_fragment> 18931 #include <alphatest_fragment> 18932 #include <alphahash_fragment> 18933 outgoingLight = diffuseColor.rgb; 18934 #include <opaque_fragment> 18935 #include <tonemapping_fragment> 18936 #include <colorspace_fragment> 18937 #include <fog_fragment> 18938 #include <premultiplied_alpha_fragment> 18939}`, Hb = `#include <common> 18940#include <batching_pars_vertex> 18941#include <fog_pars_vertex> 18942#include <morphtarget_pars_vertex> 18943#include <skinning_pars_vertex> 18944#include <logdepthbuf_pars_vertex> 18945#include <shadowmap_pars_vertex> 18946void main() { 18947 #include <batching_vertex> 18948 #include <beginnormal_vertex> 18949 #include <morphinstance_vertex> 18950 #include <morphnormal_vertex> 18951 #include <skinbase_vertex> 18952 #include <skinnormal_vertex> 18953 #include <defaultnormal_vertex> 18954 #include <begin_vertex> 18955 #include <morphtarget_vertex> 18956 #include <skinning_vertex> 18957 #include <project_vertex> 18958 #include <logdepthbuf_vertex> 18959 #include <worldpos_vertex> 18960 #include <shadowmap_vertex> 18961 #include <fog_vertex> 18962}`, Gb = `uniform vec3 color; 18963uniform float opacity; 18964#include <common> 18965#include <fog_pars_fragment> 18966#include <bsdfs> 18967#include <lights_pars_begin> 18968#include <logdepthbuf_pars_fragment> 18969#include <shadowmap_pars_fragment> 18970#include <shadowmask_pars_fragment> 18971void main() { 18972 #include <logdepthbuf_fragment> 18973 gl_FragColor = vec4( color, opacity * ( 1.0 - getShadowMask() ) ); 18974 #include <tonemapping_fragment> 18975 #include <colorspace_fragment> 18976 #include <fog_fragment> 18977 #include <premultiplied_alpha_fragment> 18978}`, Vb = `uniform float rotation; 18979uniform vec2 center; 18980#include <common> 18981#include <uv_pars_vertex> 18982#include <fog_pars_vertex> 18983#include <logdepthbuf_pars_vertex> 18984#include <clipping_planes_pars_vertex> 18985void main() { 18986 #include <uv_vertex> 18987 vec4 mvPosition = modelViewMatrix[ 3 ]; 18988 vec2 scale = vec2( length( modelMatrix[ 0 ].xyz ), length( modelMatrix[ 1 ].xyz ) ); 18989 #ifndef USE_SIZEATTENUATION 18990 bool isPerspective = isPerspectiveMatrix( projectionMatrix ); 18991 if ( isPerspective ) scale *= - mvPosition.z; 18992 #endif 18993 vec2 alignedPosition = ( position.xy - ( center - vec2( 0.5 ) ) ) * scale; 18994 vec2 rotatedPosition; 18995 rotatedPosition.x = cos( rotation ) * alignedPosition.x - sin( rotation ) * alignedPosition.y; 18996 rotatedPosition.y = sin( rotation ) * alignedPosition.x + cos( rotation ) * alignedPosition.y; 18997 mvPosition.xy += rotatedPosition; 18998 gl_Position = projectionMatrix * mvPosition; 18999 #include <logdepthbuf_vertex> 19000 #include <clipping_planes_vertex> 19001 #include <fog_vertex> 19002}`, Wb = `uniform vec3 diffuse; 19003uniform float opacity; 19004#include <common> 19005#include <uv_pars_fragment> 19006#include <map_pars_fragment> 19007#include <alphamap_pars_fragment> 19008#include <alphatest_pars_fragment> 19009#include <alphahash_pars_fragment> 19010#include <fog_pars_fragment> 19011#include <logdepthbuf_pars_fragment> 19012#include <clipping_planes_pars_fragment> 19013void main() { 19014 vec4 diffuseColor = vec4( diffuse, opacity ); 19015 #include <clipping_planes_fragment> 19016 vec3 outgoingLight = vec3( 0.0 ); 19017 #include <logdepthbuf_fragment> 19018 #include <map_fragment> 19019 #include <alphamap_fragment> 19020 #include <alphatest_fragment> 19021 #include <alphahash_fragment> 19022 outgoingLight = diffuseColor.rgb; 19023 #include <opaque_fragment> 19024 #include <tonemapping_fragment> 19025 #include <colorspace_fragment> 19026 #include <fog_fragment> 19027}`, ct = { 19028 alphahash_fragment: hy, 19029 alphahash_pars_fragment: dy, 19030 alphamap_fragment: fy, 19031 alphamap_pars_fragment: py, 19032 alphatest_fragment: my, 19033 alphatest_pars_fragment: gy, 19034 aomap_fragment: vy, 19035 aomap_pars_fragment: _y, 19036 batching_pars_vertex: yy,
19037 batching_vertex: xy, 19038 begin_vertex: by, 19039 beginnormal_vertex: wy, 19040 bsdfs: Sy, 19041 iridescence_fragment: Ey, 19042 bumpmap_pars_fragment: My, 19043 clipping_planes_fragment: Ty, 19044 clipping_planes_pars_fragment: Ay, 19045 clipping_planes_pars_vertex: Ry, 19046 clipping_planes_vertex: Cy, 19047 color_fragment: Py, 19048 color_pars_fragment: Ly, 19049 color_pars_vertex: Ny, 19050 color_vertex: Iy, 19051 common: Dy, 19052 cube_uv_reflection_fragment: Uy, 19053 defaultnormal_vertex: Oy, 19054 displacementmap_pars_vertex: ky, 19055 displacementmap_vertex: Fy, 19056 emissivemap_fragment: By, 19057 emissivemap_pars_fragment: zy, 19058 colorspace_fragment: Hy, 19059 colorspace_pars_fragment: Gy, 19060 envmap_fragment: Vy, 19061 envmap_common_pars_fragment: Wy, 19062 envmap_pars_fragment: $y, 19063 envmap_pars_vertex: jy, 19064 envmap_physical_pars_fragment: ix, 19065 envmap_vertex: Xy, 19066 fog_vertex: qy, 19067 fog_pars_vertex: Yy, 19068 fog_fragment: Ky, 19069 fog_pars_fragment: Jy, 19070 gradientmap_pars_fragment: Zy, 19071 lightmap_pars_fragment: Qy, 19072 lights_lambert_fragment: ex, 19073 lights_lambert_pars_fragment: tx, 19074 lights_pars_begin: nx, 19075 lights_toon_fragment: rx, 19076 lights_toon_pars_fragment: sx, 19077 lights_phong_fragment: ax, 19078 lights_phong_pars_fragment: ox, 19079 lights_physical_fragment: lx, 19080 lights_physical_pars_fragment: cx, 19081 lights_fragment_begin: ux, 19082 lights_fragment_maps: hx, 19083 lights_fragment_end: dx, 19084 lightprobes_pars_fragment: fx, 19085 logdepthbuf_fragment: px, 19086 logdepthbuf_pars_fragment: mx, 19087 logdepthbuf_pars_vertex: gx, 19088 logdepthbuf_vertex: vx, 19089 map_fragment: _x, 19090 map_pars_fragment: yx, 19091 map_particle_fragment: xx, 19092 map_particle_pars_fragment: bx, 19093 metalnessmap_fragment: wx, 19094 metalnessmap_pars_fragment: Sx, 19095 morphinstance_vertex: Ex, 19096 morphcolor_vertex: Mx, 19097 morphnormal_vertex: Tx, 19098 morphtarget_pars_vertex: Ax, 19099 morphtarget_vertex: Rx, 19100 normal_fragment_begin: Cx, 19101 normal_fragment_maps: Px, 19102 normal_pars_fragment: Lx, 19103 normal_pars_vertex: Nx, 19104 normal_vertex: Ix, 19105 normalmap_pars_fragment: Dx, 19106 clearcoat_normal_fragment_begin: Ux, 19107 clearcoat_normal_fragment_maps: Ox, 19108 clearcoat_pars_fragment: kx, 19109 iridescence_pars_fragment: Fx, 19110 opaque_fragment: Bx, 19111 packing: zx, 19112 premultiplied_alpha_fragment: Hx, 19113 project_vertex: Gx, 19114 dithering_fragment: Vx, 19115 dithering_pars_fragment: Wx, 19116 roughnessmap_fragment: $x, 19117 roughnessmap_pars_fragment: jx, 19118 shadowmap_pars_fragment: Xx, 19119 shadowmap_pars_vertex: qx, 19120 shadowmap_vertex: Yx, 19121 shadowmask_pars_fragment: Kx, 19122 skinbase_vertex: Jx, 19123 skinning_pars_vertex: Zx, 19124 skinning_vertex: Qx, 19125 skinnormal_vertex: eb, 19126 specularmap_fragment: tb, 19127 specularmap_pars_fragment: nb, 19128 tonemapping_fragment: ib, 19129 tonemapping_pars_fragment: rb, 19130 transmission_fragment: sb, 19131 transmission_pars_fragment: ab, 19132 uv_pars_fragment: ob, 19133 uv_pars_vertex: lb, 19134 uv_vertex: cb, 19135 worldpos_vertex: ub, 19136 background_vert: hb, 19137 background_frag: db, 19138 backgroundCube_vert: fb, 19139 backgroundCube_frag: pb, 19140 cube_vert: mb, 19141 cube_frag: gb, 19142 depth_vert: vb, 19143 depth_frag: _b, 19144 distance_vert: yb, 19145 distance_frag: xb, 19146 equirect_vert: bb, 19147 equirect_frag: wb, 19148 linedashed_vert: Sb, 19149 linedashed_frag: Eb, 19150 meshbasic_vert: Mb, 19151 meshbasic_frag: Tb, 19152 meshlambert_vert: Ab, 19153 meshlambert_frag: Rb, 19154 meshmatcap_vert: Cb, 19155 meshmatcap_frag: Pb, 19156 meshnormal_vert: Lb, 19157 meshnormal_frag: Nb, 19158 meshphong_vert: Ib, 19159 meshphong_frag: Db, 19160 meshphysical_vert: Ub, 19161 meshphysical_frag: Ob, 19162 meshtoon_vert: kb, 19163 meshtoon_frag: Fb, 19164 points_vert: Bb, 19165 points_frag: zb, 19166 shadow_vert: Hb, 19167 shadow_frag: Gb, 19168 sprite_vert: Vb, 19169 sprite_frag: Wb 19170}, Pe = { 19171 common: { 19172 diffuse: { value: /* @__PURE__ */ new Et(16777215) }, 19173 opacity: { value: 1 }, 19174 map: { value: null }, 19175 mapTransform: { value: /* @__PURE__ */ new ot() },
vendor: 4,058 bytes, lines 19176-19318
19176 alphaMap: { value: null }, 19177 alphaMapTransform: { value: /* @__PURE__ */ new ot() }, 19178 alphaTest: { value: 0 } 19179 }, 19180 specularmap: { 19181 specularMap: { value: null }, 19182 specularMapTransform: { value: /* @__PURE__ */ new ot() } 19183 }, 19184 envmap: { 19185 envMap: { value: null }, 19186 envMapRotation: { value: /* @__PURE__ */ new ot() }, 19187 reflectivity: { value: 1 }, 19188 // basic, lambert, phong 19189 ior: { value: 1.5 }, 19190 // physical 19191 refractionRatio: { value: 0.98 }, 19192 // basic, lambert, phong 19193 dfgLUT: { value: null } 19194 // DFG LUT for physically-based rendering 19195 }, 19196 aomap: { 19197 aoMap: { value: null }, 19198 aoMapIntensity: { value: 1 }, 19199 aoMapTransform: { value: /* @__PURE__ */ new ot() } 19200 }, 19201 lightmap: { 19202 lightMap: { value: null }, 19203 lightMapIntensity: { value: 1 }, 19204 lightMapTransform: { value: /* @__PURE__ */ new ot() } 19205 }, 19206 bumpmap: { 19207 bumpMap: { value: null }, 19208 bumpMapTransform: { value: /* @__PURE__ */ new ot() }, 19209 bumpScale: { value: 1 } 19210 }, 19211 normalmap: { 19212 normalMap: { value: null }, 19213 normalMapTransform: { value: /* @__PURE__ */ new ot() }, 19214 normalScale: { value: /* @__PURE__ */ new wt(1, 1) } 19215 }, 19216 displacementmap: { 19217 displacementMap: { value: null }, 19218 displacementMapTransform: { value: /* @__PURE__ */ new ot() }, 19219 displacementScale: { value: 1 }, 19220 displacementBias: { value: 0 } 19221 }, 19222 emissivemap: { 19223 emissiveMap: { value: null }, 19224 emissiveMapTransform: { value: /* @__PURE__ */ new ot() } 19225 }, 19226 metalnessmap: { 19227 metalnessMap: { value: null }, 19228 metalnessMapTransform: { value: /* @__PURE__ */ new ot() } 19229 }, 19230 roughnessmap: { 19231 roughnessMap: { value: null }, 19232 roughnessMapTransform: { value: /* @__PURE__ */ new ot() } 19233 }, 19234 gradientmap: { 19235 gradientMap: { value: null } 19236 }, 19237 fog: { 19238 fogDensity: { value: 25e-5 }, 19239 fogNear: { value: 1 }, 19240 fogFar: { value: 2e3 }, 19241 fogColor: { value: /* @__PURE__ */ new Et(16777215) } 19242 }, 19243 lights: { 19244 ambientLightColor: { value: [] }, 19245 lightProbe: { value: [] }, 19246 directionalLights: { value: [], properties: { 19247 direction: {}, 19248 color: {} 19249 } }, 19250 directionalLightShadows: { value: [], properties: { 19251 shadowIntensity: 1, 19252 shadowBias: {}, 19253 shadowNormalBias: {}, 19254 shadowRadius: {}, 19255 shadowMapSize: {} 19256 } }, 19257 directionalShadowMatrix: { value: [] }, 19258 spotLights: { value: [], properties: { 19259 color: {}, 19260 position: {}, 19261 direction: {}, 19262 distance: {}, 19263 coneCos: {}, 19264 penumbraCos: {}, 19265 decay: {} 19266 } }, 19267 spotLightShadows: { value: [], properties: { 19268 shadowIntensity: 1, 19269 shadowBias: {}, 19270 shadowNormalBias: {}, 19271 shadowRadius: {}, 19272 shadowMapSize: {} 19273 } }, 19274 spotLightMap: { value: [] }, 19275 spotLightMatrix: { value: [] }, 19276 pointLights: { value: [], properties: { 19277 color: {}, 19278 position: {}, 19279 decay: {}, 19280 distance: {} 19281 } }, 19282 pointLightShadows: { value: [], properties: { 19283 shadowIntensity: 1, 19284 shadowBias: {}, 19285 shadowNormalBias: {}, 19286 shadowRadius: {}, 19287 shadowMapSize: {}, 19288 shadowCameraNear: {}, 19289 shadowCameraFar: {} 19290 } }, 19291 pointShadowMatrix: { value: [] }, 19292 hemisphereLights: { value: [], properties: { 19293 direction: {}, 19294 skyColor: {}, 19295 groundColor: {} 19296 } }, 19297 // TODO (abelnation): RectAreaLight BRDF data needs to be moved from example to main src 19298 rectAreaLights: { value: [], properties: { 19299 color: {}, 19300 position: {}, 19301 width: {}, 19302 height: {} 19303 } }, 19304 ltc_1: { value: null }, 19305 ltc_2: { value: null }, 19306 probesSH: { value: null }, 19307 probesMin: { value: /* @__PURE__ */ new W() }, 19308 probesMax: { value: /* @__PURE__ */ new W() }, 19309 probesResolution: { value: /* @__PURE__ */ new W() } 19310 }, 19311 points: { 19312 diffuse: { value: /* @__PURE__ */ new Et(16777215) }, 19313 opacity: { value: 1 }, 19314 size: { value: 1 }, 19315 scale: { value: 1 }, 19316 map: { value: null }, 19317 alphaMap: { value: null }, 19318 alphaMapTransform: { value: /* @__PURE__ */ new ot() },
vendor: 25,838 bytes, lines 19319-20081
19319 alphaTest: { value: 0 }, 19320 uvTransform: { value: /* @__PURE__ */ new ot() } 19321 }, 19322 sprite: { 19323 diffuse: { value: /* @__PURE__ */ new Et(16777215) }, 19324 opacity: { value: 1 }, 19325 center: { value: /* @__PURE__ */ new wt(0.5, 0.5) }, 19326 rotation: { value: 0 }, 19327 map: { value: null }, 19328 mapTransform: { value: /* @__PURE__ */ new ot() }, 19329 alphaMap: { value: null }, 19330 alphaMapTransform: { value: /* @__PURE__ */ new ot() }, 19331 alphaTest: { value: 0 } 19332 } 19333}, li = { 19334 basic: { 19335 uniforms: /* @__PURE__ */ pn([ 19336 Pe.common, 19337 Pe.specularmap, 19338 Pe.envmap, 19339 Pe.aomap, 19340 Pe.lightmap, 19341 Pe.fog 19342 ]), 19343 vertexShader: ct.meshbasic_vert, 19344 fragmentShader: ct.meshbasic_frag 19345 }, 19346 lambert: { 19347 uniforms: /* @__PURE__ */ pn([ 19348 Pe.common, 19349 Pe.specularmap, 19350 Pe.envmap, 19351 Pe.aomap, 19352 Pe.lightmap, 19353 Pe.emissivemap, 19354 Pe.bumpmap, 19355 Pe.normalmap, 19356 Pe.displacementmap, 19357 Pe.fog, 19358 Pe.lights, 19359 { 19360 emissive: { value: /* @__PURE__ */ new Et(0) }, 19361 envMapIntensity: { value: 1 } 19362 } 19363 ]), 19364 vertexShader: ct.meshlambert_vert, 19365 fragmentShader: ct.meshlambert_frag 19366 }, 19367 phong: { 19368 uniforms: /* @__PURE__ */ pn([ 19369 Pe.common, 19370 Pe.specularmap, 19371 Pe.envmap, 19372 Pe.aomap, 19373 Pe.lightmap, 19374 Pe.emissivemap, 19375 Pe.bumpmap, 19376 Pe.normalmap, 19377 Pe.displacementmap, 19378 Pe.fog, 19379 Pe.lights, 19380 { 19381 emissive: { value: /* @__PURE__ */ new Et(0) }, 19382 specular: { value: /* @__PURE__ */ new Et(1118481) }, 19383 shininess: { value: 30 }, 19384 envMapIntensity: { value: 1 } 19385 } 19386 ]), 19387 vertexShader: ct.meshphong_vert, 19388 fragmentShader: ct.meshphong_frag 19389 }, 19390 standard: { 19391 uniforms: /* @__PURE__ */ pn([ 19392 Pe.common, 19393 Pe.envmap, 19394 Pe.aomap, 19395 Pe.lightmap, 19396 Pe.emissivemap, 19397 Pe.bumpmap, 19398 Pe.normalmap, 19399 Pe.displacementmap, 19400 Pe.roughnessmap, 19401 Pe.metalnessmap, 19402 Pe.fog, 19403 Pe.lights, 19404 { 19405 emissive: { value: /* @__PURE__ */ new Et(0) }, 19406 roughness: { value: 1 }, 19407 metalness: { value: 0 }, 19408 envMapIntensity: { value: 1 } 19409 } 19410 ]), 19411 vertexShader: ct.meshphysical_vert, 19412 fragmentShader: ct.meshphysical_frag 19413 }, 19414 toon: { 19415 uniforms: /* @__PURE__ */ pn([ 19416 Pe.common, 19417 Pe.aomap, 19418 Pe.lightmap, 19419 Pe.emissivemap, 19420 Pe.bumpmap, 19421 Pe.normalmap, 19422 Pe.displacementmap, 19423 Pe.gradientmap, 19424 Pe.fog, 19425 Pe.lights, 19426 { 19427 emissive: { value: /* @__PURE__ */ new Et(0) } 19428 } 19429 ]), 19430 vertexShader: ct.meshtoon_vert, 19431 fragmentShader: ct.meshtoon_frag 19432 }, 19433 matcap: { 19434 uniforms: /* @__PURE__ */ pn([ 19435 Pe.common, 19436 Pe.bumpmap, 19437 Pe.normalmap, 19438 Pe.displacementmap, 19439 Pe.fog, 19440 { 19441 matcap: { value: null } 19442 } 19443 ]), 19444 vertexShader: ct.meshmatcap_vert, 19445 fragmentShader: ct.meshmatcap_frag 19446 }, 19447 points: { 19448 uniforms: /* @__PURE__ */ pn([ 19449 Pe.points, 19450 Pe.fog 19451 ]), 19452 vertexShader: ct.points_vert, 19453 fragmentShader: ct.points_frag 19454 }, 19455 dashed: { 19456 uniforms: /* @__PURE__ */ pn([ 19457 Pe.common, 19458 Pe.fog, 19459 { 19460 scale: { value: 1 }, 19461 dashSize: { value: 1 }, 19462 totalSize: { value: 2 } 19463 } 19464 ]), 19465 vertexShader: ct.linedashed_vert, 19466 fragmentShader: ct.linedashed_frag 19467 }, 19468 depth: { 19469 uniforms: /* @__PURE__ */ pn([ 19470 Pe.common, 19471 Pe.displacementmap 19472 ]), 19473 vertexShader: ct.depth_vert, 19474 fragmentShader: ct.depth_frag 19475 }, 19476 normal: { 19477 uniforms: /* @__PURE__ */ pn([ 19478 Pe.common, 19479 Pe.bumpmap, 19480 Pe.normalmap, 19481 Pe.displacementmap, 19482 { 19483 opacity: { value: 1 } 19484 } 19485 ]), 19486 vertexShader: ct.meshnormal_vert, 19487 fragmentShader: ct.meshnormal_frag 19488 }, 19489 sprite: { 19490 uniforms: /* @__PURE__ */ pn([ 19491 Pe.sprite, 19492 Pe.fog 19493 ]), 19494 vertexShader: ct.sprite_vert, 19495 fragmentShader: ct.sprite_frag 19496 }, 19497 background: { 19498 uniforms: { 19499 uvTransform: { value: /* @__PURE__ */ new ot() }, 19500 t2D: { value: null }, 19501 backgroundIntensity: { value: 1 } 19502 }, 19503 vertexShader: ct.background_vert, 19504 fragmentShader: ct.background_frag 19505 }, 19506 backgroundCube: { 19507 uniforms: { 19508 envMap: { value: null }, 19509 backgroundBlurriness: { value: 0 }, 19510 backgroundIntensity: { value: 1 }, 19511 backgroundRotation: { value: /* @__PURE__ */ new ot() } 19512 }, 19513 vertexShader: ct.backgroundCube_vert, 19514 fragmentShader: ct.backgroundCube_frag 19515 }, 19516 cube: { 19517 uniforms: { 19518 tCube: { value: null }, 19519 tFlip: { value: -1 }, 19520 opacity: { value: 1 } 19521 }, 19522 vertexShader: ct.cube_vert, 19523 fragmentShader: ct.cube_frag 19524 }, 19525 equirect: { 19526 uniforms: { 19527 tEquirect: { value: null } 19528 }, 19529 vertexShader: ct.equirect_vert, 19530 fragmentShader: ct.equirect_frag 19531 }, 19532 distance: { 19533 uniforms: /* @__PURE__ */ pn([ 19534 Pe.common, 19535 Pe.displacementmap, 19536 { 19537 referencePosition: { value: /* @__PURE__ */ new W() }, 19538 nearDistance: { value: 1 }, 19539 farDistance: { value: 1e3 } 19540 } 19541 ]), 19542 vertexShader: ct.distance_vert, 19543 fragmentShader: ct.distance_frag 19544 }, 19545 shadow: { 19546 uniforms: /* @__PURE__ */ pn([ 19547 Pe.lights, 19548 Pe.fog, 19549 { 19550 color: { value: /* @__PURE__ */ new Et(0) }, 19551 opacity: { value: 1 } 19552 } 19553 ]), 19554 vertexShader: ct.shadow_vert, 19555 fragmentShader: ct.shadow_frag 19556 } 19557}; 19558li.physical = { 19559 uniforms: /* @__PURE__ */ pn([ 19560 li.standard.uniforms, 19561 { 19562 clearcoat: { value: 0 }, 19563 clearcoatMap: { value: null }, 19564 clearcoatMapTransform: { value: /* @__PURE__ */ new ot() }, 19565 clearcoatNormalMap: { value: null }, 19566 clearcoatNormalMapTransform: { value: /* @__PURE__ */ new ot() }, 19567 clearcoatNormalScale: { value: /* @__PURE__ */ new wt(1, 1) }, 19568 clearcoatRoughness: { value: 0 }, 19569 clearcoatRoughnessMap: { value: null }, 19570 clearcoatRoughnessMapTransform: { value: /* @__PURE__ */ new ot() }, 19571 dispersion: { value: 0 }, 19572 iridescence: { value: 0 }, 19573 iridescenceMap: { value: null }, 19574 iridescenceMapTransform: { value: /* @__PURE__ */ new ot() }, 19575 iridescenceIOR: { value: 1.3 }, 19576 iridescenceThicknessMinimum: { value: 100 }, 19577 iridescenceThicknessMaximum: { value: 400 }, 19578 iridescenceThicknessMap: { value: null }, 19579 iridescenceThicknessMapTransform: { value: /* @__PURE__ */ new ot() }, 19580 sheen: { value: 0 }, 19581 sheenColor: { value: /* @__PURE__ */ new Et(0) }, 19582 sheenColorMap: { value: null }, 19583 sheenColorMapTransform: { value: /* @__PURE__ */ new ot() }, 19584 sheenRoughness: { value: 1 }, 19585 sheenRoughnessMap: { value: null }, 19586 sheenRoughnessMapTransform: { value: /* @__PURE__ */ new ot() }, 19587 transmission: { value: 0 }, 19588 transmissionMap: { value: null }, 19589 transmissionMapTransform: { value: /* @__PURE__ */ new ot() }, 19590 transmissionSamplerSize: { value: /* @__PURE__ */ new wt() }, 19591 transmissionSamplerMap: { value: null }, 19592 thickness: { value: 0 }, 19593 thicknessMap: { value: null }, 19594 thicknessMapTransform: { value: /* @__PURE__ */ new ot() }, 19595 attenuationDistance: { value: 0 }, 19596 attenuationColor: { value: /* @__PURE__ */ new Et(0) }, 19597 specularColor: { value: /* @__PURE__ */ new Et(1, 1, 1) }, 19598 specularColorMap: { value: null }, 19599 specularColorMapTransform: { value: /* @__PURE__ */ new ot() }, 19600 specularIntensity: { value: 1 }, 19601 specularIntensityMap: { value: null }, 19602 specularIntensityMapTransform: { value: /* @__PURE__ */ new ot() }, 19603 anisotropyVector: { value: /* @__PURE__ */ new wt() }, 19604 anisotropyMap: { value: null }, 19605 anisotropyMapTransform: { value: /* @__PURE__ */ new ot() } 19606 } 19607 ]), 19608 vertexShader: ct.meshphysical_vert, 19609 fragmentShader: ct.meshphysical_frag 19610}; 19611const to = { r: 0, b: 0, g: 0 }, $b = /* @__PURE__ */ new kt(), Yp = /* @__PURE__ */ new ot(); 19612Yp.set(-1, 0, 0, 0, 1, 0, 0, 0, 1); 19613function jb(n, e, t, i, r, s) { 19614 const a = new Et(0); 19615 let l = r === !0 ? 0 : 1, o, c, u = null, h = 0, d = null; 19616 function f(_) { 19617 let x = _.isScene === !0 ? _.background : null; 19618 if (x && x.isTexture) { 19619 const E = _.backgroundBlurriness > 0; 19620 x = e.get(x, E); 19621 } 19622 return x; 19623 } 19624 function p(_) { 19625 let x = !1; 19626 const E = f(_); 19627 E === null ? m(a, l) : E && E.isColor && (m(E, 1), x = !0); 19628 const R = n.xr.getEnvironmentBlendMode(); 19629 R === "additive" ? t.buffers.color.setClear(0, 0, 0, 1, s) : R === "alpha-blend" && t.buffers.color.setClear(0, 0, 0, 0, s), (n.autoClear || x) && (t.buffers.depth.setTest(!0), t.buffers.depth.setMask(!0), t.buffers.color.setMask(!0), n.clear(n.autoClearColor, n.autoClearDepth, n.autoClearStencil)); 19630 } 19631 function v(_, x) { 19632 const E = f(x); 19633 E && (E.isCubeTexture || E.mapping === $o) ? (c === void 0 && (c = new _n( 19634 new Sa(1, 1, 1), 19635 new yn({ 19636 name: "BackgroundCubeMaterial", 19637 uniforms: _s(li.backgroundCube.uniforms), 19638 vertexShader: li.backgroundCube.vertexShader, 19639 fragmentShader: li.backgroundCube.fragmentShader, 19640 side: Mn, 19641 depthTest: !1, 19642 depthWrite: !1, 19643 fog: !1, 19644 allowOverride: !1 19645 }) 19646 ), c.geometry.deleteAttribute("normal"), c.geometry.deleteAttribute("uv"), c.onBeforeRender = function(R, T, w) { 19647 this.matrixWorld.copyPosition(w.matrixWorld); 19648 }, Object.defineProperty(c.material, "envMap", { 19649 get: function() { 19650 return this.uniforms.envMap.value; 19651 } 19652 }), i.update(c)), c.material.uniforms.envMap.value = E, c.material.uniforms.backgroundBlurriness.value = x.backgroundBlurriness, c.material.uniforms.backgroundIntensity.value = x.backgroundIntensity, c.material.uniforms.backgroundRotation.value.setFromMatrix4($b.makeRotationFromEuler(x.backgroundRotation)).transpose(), E.isCubeTexture && E.isRenderTargetTexture === !1 && c.material.uniforms.backgroundRotation.value.premultiply(Yp), c.material.toneMapped = _t.getTransfer(E.colorSpace) !== Nt, (u !== E || h !== E.version || d !== n.toneMapping) && (c.material.needsUpdate = !0, u = E, h = E.version, d = n.toneMapping), c.layers.enableAll(), _.unshift(c, c.geometry, c.material, 0, 0, null)) : E && E.isTexture && (o === void 0 && (o = new _n( 19653 new qo(2, 2), 19654 new yn({ 19655 name: "BackgroundMaterial", 19656 uniforms: _s(li.background.uniforms), 19657 vertexShader: li.background.vertexShader, 19658 fragmentShader: li.background.fragmentShader, 19659 side: sr, 19660 depthTest: !1, 19661 depthWrite: !1, 19662 fog: !1, 19663 allowOverride: !1 19664 }) 19665 ), o.geometry.deleteAttribute("normal"), Object.defineProperty(o.material, "map", { 19666 get: function() { 19667 return this.uniforms.t2D.value; 19668 } 19669 }), i.update(o)), o.material.uniforms.t2D.value = E, o.material.uniforms.backgroundIntensity.value = x.backgroundIntensity, o.material.toneMapped = _t.getTransfer(E.colorSpace) !== Nt, E.matrixAutoUpdate === !0 && E.updateMatrix(), o.material.uniforms.uvTransform.value.copy(E.matrix), (u !== E || h !== E.version || d !== n.toneMapping) && (o.material.needsUpdate = !0, u = E, h = E.version, d = n.toneMapping), o.layers.enableAll(), _.unshift(o, o.geometry, o.material, 0, 0, null)); 19670 } 19671 function m(_, x) { 19672 _.getRGB(to, Wp(n)), t.buffers.color.setClear(to.r, to.g, to.b, x, s); 19673 } 19674 function g() { 19675 c !== void 0 && (c.geometry.dispose(), c.material.dispose(), c = void 0), o !== void 0 && (o.geometry.dispose(), o.material.dispose(), o = void 0); 19676 } 19677 return { 19678 getClearColor: function() { 19679 return a; 19680 }, 19681 setClearColor: function(_, x = 1) { 19682 a.set(_), l = x, m(a, l); 19683 }, 19684 getClearAlpha: function() { 19685 return l; 19686 }, 19687 setClearAlpha: function(_) { 19688 l = _, m(a, l); 19689 }, 19690 render: p, 19691 addToRenderList: v, 19692 dispose: g 19693 }; 19694} 19695function Xb(n, e) { 19696 const t = n.getParameter(n.MAX_VERTEX_ATTRIBS), i = {}, r = d(null); 19697 let s = r, a = !1; 19698 function l(C, U, V, F, I) { 19699 let k = !1; 19700 const H = h(C, F, V, U); 19701 s !== H && (s = H, c(s.object)), k = f(C, F, V, I), k && p(C, F, V, I), I !== null && e.update(I, n.ELEMENT_ARRAY_BUFFER), (k || a) && (a = !1, E(C, U, V, F), I !== null && n.bindBuffer(n.ELEMENT_ARRAY_BUFFER, e.get(I).buffer)); 19702 } 19703 function o() { 19704 return n.createVertexArray(); 19705 } 19706 function c(C) { 19707 return n.bindVertexArray(C); 19708 } 19709 function u(C) { 19710 return n.deleteVertexArray(C); 19711 } 19712 function h(C, U, V, F) { 19713 const I = F.wireframe === !0; 19714 let k = i[U.id]; 19715 k === void 0 && (k = {}, i[U.id] = k); 19716 const H = C.isInstancedMesh === !0 ? C.id : 0; 19717 let X = k[H]; 19718 X === void 0 && (X = {}, k[H] = X); 19719 let K = X[V.id]; 19720 K === void 0 && (K = {}, X[V.id] = K); 19721 let ae = K[I]; 19722 return ae === void 0 && (ae = d(o()), K[I] = ae), ae; 19723 } 19724 function d(C) { 19725 const U = [], V = [], F = []; 19726 for (let I = 0; I < t; I++) 19727 U[I] = 0, V[I] = 0, F[I] = 0; 19728 return { 19729 // for backward compatibility on non-VAO support browser 19730 geometry: null, 19731 program: null, 19732 wireframe: !1, 19733 newAttributes: U, 19734 enabledAttributes: V, 19735 attributeDivisors: F, 19736 object: C, 19737 attributes: {}, 19738 index: null 19739 }; 19740 } 19741 function f(C, U, V, F) { 19742 const I = s.attributes, k = U.attributes; 19743 let H = 0; 19744 const X = V.getAttributes(); 19745 for (const K in X) 19746 if (X[K].location >= 0) { 19747 const se = I[K]; 19748 let he = k[K]; 19749 if (he === void 0 && (K === "instanceMatrix" && C.instanceMatrix && (he = C.instanceMatrix), K === "instanceColor" && C.instanceColor && (he = C.instanceColor)), se === void 0 || se.attribute !== he || he && se.data !== he.data) return !0; 19750 H++; 19751 } 19752 return s.attributesNum !== H || s.index !== F; 19753 } 19754 function p(C, U, V, F) { 19755 const I = {}, k = U.attributes; 19756 let H = 0; 19757 const X = V.getAttributes(); 19758 for (const K in X) 19759 if (X[K].location >= 0) { 19760 let se = k[K]; 19761 se === void 0 && (K === "instanceMatrix" && C.instanceMatrix && (se = C.instanceMatrix), K === "instanceColor" && C.instanceColor && (se = C.instanceColor)); 19762 const he = {}; 19763 he.attribute = se, se && se.data && (he.data = se.data), I[K] = he, H++; 19764 } 19765 s.attributes = I, s.attributesNum = H, s.index = F; 19766 } 19767 function v() { 19768 const C = s.newAttributes; 19769 for (let U = 0, V = C.length; U < V; U++) 19770 C[U] = 0; 19771 } 19772 function m(C) { 19773 g(C, 0); 19774 } 19775 function g(C, U) { 19776 const V = s.newAttributes, F = s.enabledAttributes, I = s.attributeDivisors; 19777 V[C] = 1, F[C] === 0 && (n.enableVertexAttribArray(C), F[C] = 1), I[C] !== U && (n.vertexAttribDivisor(C, U), I[C] = U); 19778 } 19779 function _() { 19780 const C = s.newAttributes, U = s.enabledAttributes; 19781 for (let V = 0, F = U.length; V < F; V++) 19782 U[V] !== C[V] && (n.disableVertexAttribArray(V), U[V] = 0); 19783 } 19784 function x(C, U, V, F, I, k, H) { 19785 H === !0 ? n.vertexAttribIPointer(C, U, V, I, k) : n.vertexAttribPointer(C, U, V, F, I, k); 19786 } 19787 function E(C, U, V, F) { 19788 v(); 19789 const I = F.attributes, k = V.getAttributes(), H = U.defaultAttributeValues; 19790 for (const X in k) { 19791 const K = k[X]; 19792 if (K.location >= 0) { 19793 let ae = I[X]; 19794 if (ae === void 0 && (X === "instanceMatrix" && C.instanceMatrix && (ae = C.instanceMatrix), X === "instanceColor" && C.instanceColor && (ae = C.instanceColor)), ae !== void 0) { 19795 const se = ae.normalized, he = ae.itemSize, Ce = e.get(ae); 19796 if (Ce === void 0) continue; 19797 const Ie = Ce.buffer, Ee = Ce.type, J = Ce.bytesPerElement, le = Ee === n.INT || Ee === n.UNSIGNED_INT || ae.gpuType === Iu; 19798 if (ae.isInterleavedBufferAttribute) { 19799 const te = ae.data, ie = te.stride, fe = ae.offset; 19800 if (te.isInstancedInterleavedBuffer) { 19801 for (let Se = 0; Se < K.locationSize; Se++) 19802 g(K.location + Se, te.meshPerAttribute); 19803 C.isInstancedMesh !== !0 && F._maxInstanceCount === void 0 && (F._maxInstanceCount = te.meshPerAttribute * te.count); 19804 } else 19805 for (let Se = 0; Se < K.locationSize; Se++) 19806 m(K.location + Se); 19807 n.bindBuffer(n.ARRAY_BUFFER, Ie); 19808 for (let Se = 0; Se < K.locationSize; Se++) 19809 x( 19810 K.location + Se, 19811 he / K.locationSize, 19812 Ee, 19813 se, 19814 ie * J, 19815 (fe + he / K.locationSize * Se) * J, 19816 le 19817 ); 19818 } else { 19819 if (ae.isInstancedBufferAttribute) { 19820 for (let te = 0; te < K.locationSize; te++) 19821 g(K.location + te, ae.meshPerAttribute); 19822 C.isInstancedMesh !== !0 && F._maxInstanceCount === void 0 && (F._maxInstanceCount = ae.meshPerAttribute * ae.count); 19823 } else 19824 for (let te = 0; te < K.locationSize; te++) 19825 m(K.location + te); 19826 n.bindBuffer(n.ARRAY_BUFFER, Ie); 19827 for (let te = 0; te < K.locationSize; te++) 19828 x( 19829 K.location + te, 19830 he / K.locationSize, 19831 Ee, 19832 se, 19833 he * J, 19834 he / K.locationSize * te * J, 19835 le 19836 ); 19837 } 19838 } else if (H !== void 0) { 19839 const se = H[X]; 19840 if (se !== void 0) 19841 switch (se.length) { 19842 case 2: 19843 n.vertexAttrib2fv(K.location, se); 19844 break; 19845 case 3: 19846 n.vertexAttrib3fv(K.location, se); 19847 break; 19848 case 4: 19849 n.vertexAttrib4fv(K.location, se); 19850 break; 19851 default: 19852 n.vertexAttrib1fv(K.location, se); 19853 } 19854 } 19855 } 19856 } 19857 _(); 19858 } 19859 function R() { 19860 M(); 19861 for (const C in i) { 19862 const U = i[C]; 19863 for (const V in U) { 19864 const F = U[V]; 19865 for (const I in F) { 19866 const k = F[I]; 19867 for (const H in k) 19868 u(k[H].object), delete k[H]; 19869 delete F[I]; 19870 } 19871 } 19872 delete i[C]; 19873 } 19874 } 19875 function T(C) { 19876 if (i[C.id] === void 0) return; 19877 const U = i[C.id]; 19878 for (const V in U) { 19879 const F = U[V]; 19880 for (const I in F) { 19881 const k = F[I]; 19882 for (const H in k) 19883 u(k[H].object), delete k[H]; 19884 delete F[I]; 19885 } 19886 } 19887 delete i[C.id]; 19888 } 19889 function w(C) { 19890 for (const U in i) { 19891 const V = i[U]; 19892 for (const F in V) { 19893 const I = V[F]; 19894 if (I[C.id] === void 0) continue; 19895 const k = I[C.id]; 19896 for (const H in k) 19897 u(k[H].object), delete k[H]; 19898 delete I[C.id]; 19899 } 19900 } 19901 } 19902 function y(C) { 19903 for (const U in i) { 19904 const V = i[U], F = C.isInstancedMesh === !0 ? C.id : 0, I = V[F]; 19905 if (I !== void 0) { 19906 for (const k in I) { 19907 const H = I[k]; 19908 for (const X in H) 19909 u(H[X].object), delete H[X]; 19910 delete I[k]; 19911 } 19912 delete V[F], Object.keys(V).length === 0 && delete i[U]; 19913 } 19914 } 19915 } 19916 function M() { 19917 L(), a = !0, s !== r && (s = r, c(s.object)); 19918 } 19919 function L() { 19920 r.geometry = null, r.program = null, r.wireframe = !1; 19921 } 19922 return { 19923 setup: l, 19924 reset: M, 19925 resetDefaultState: L, 19926 dispose: R, 19927 releaseStatesOfGeometry: T, 19928 releaseStatesOfObject: y, 19929 releaseStatesOfProgram: w, 19930 initAttributes: v, 19931 enableAttribute: m, 19932 disableUnusedAttributes: _ 19933 }; 19934} 19935function qb(n, e, t) { 19936 let i; 19937 function r(o) { 19938 i = o; 19939 } 19940 function s(o, c) { 19941 n.drawArrays(i, o, c), t.update(c, i, 1); 19942 } 19943 function a(o, c, u) { 19944 u !== 0 && (n.drawArraysInstanced(i, o, c, u), t.update(c, i, u)); 19945 } 19946 function l(o, c, u) { 19947 if (u === 0) return; 19948 e.get("WEBGL_multi_draw").multiDrawArraysWEBGL(i, o, 0, c, 0, u); 19949 let d = 0; 19950 for (let f = 0; f < u; f++) 19951 d += c[f]; 19952 t.update(d, i, 1); 19953 } 19954 this.setMode = r, this.render = s, this.renderInstances = a, this.renderMultiDraw = l; 19955} 19956function Yb(n, e, t, i) { 19957 let r; 19958 function s() { 19959 if (r !== void 0) return r; 19960 if (e.has("EXT_texture_filter_anisotropic") === !0) { 19961 const w = e.get("EXT_texture_filter_anisotropic"); 19962 r = n.getParameter(w.MAX_TEXTURE_MAX_ANISOTROPY_EXT); 19963 } else 19964 r = 0; 19965 return r; 19966 } 19967 function a(w) { 19968 return !(w !== ni && i.convert(w) !== n.getParameter(n.IMPLEMENTATION_COLOR_READ_FORMAT)); 19969 } 19970 function l(w) { 19971 const y = w === ki && (e.has("EXT_color_buffer_half_float") || e.has("EXT_color_buffer_float")); 19972 return !(w !== Pn && i.convert(w) !== n.getParameter(n.IMPLEMENTATION_COLOR_READ_TYPE) && // Edge and Chrome Mac < 52 (#9513) 19973 w !== ti && !y); 19974 } 19975 function o(w) { 19976 if (w === "highp") { 19977 if (n.getShaderPrecisionFormat(n.VERTEX_SHADER, n.HIGH_FLOAT).precision > 0 && n.getShaderPrecisionFormat(n.FRAGMENT_SHADER, n.HIGH_FLOAT).precision > 0) 19978 return "highp"; 19979 w = "mediump"; 19980 } 19981 return w === "mediump" && n.getShaderPrecisionFormat(n.VERTEX_SHADER, n.MEDIUM_FLOAT).precision > 0 && n.getShaderPrecisionFormat(n.FRAGMENT_SHADER, n.MEDIUM_FLOAT).precision > 0 ? "mediump" : "lowp"; 19982 } 19983 let c = t.precision !== void 0 ? t.precision : "highp"; 19984 const u = o(c); 19985 u !== c && (tt("WebGLRenderer:", c, "not supported, using", u, "instead."), c = u); 19986 const h = t.logarithmicDepthBuffer === !0, d = t.reversedDepthBuffer === !0 && e.has("EXT_clip_control"); 19987 t.reversedDepthBuffer === !0 && d === !1 && tt("WebGLRenderer: Unable to use reversed depth buffer due to missing EXT_clip_control extension. Fallback to default depth buffer."); 19988 const f = n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS), p = n.getParameter(n.MAX_VERTEX_TEXTURE_IMAGE_UNITS), v = n.getParameter(n.MAX_TEXTURE_SIZE), m = n.getParameter(n.MAX_CUBE_MAP_TEXTURE_SIZE), g = n.getParameter(n.MAX_VERTEX_ATTRIBS), _ = n.getParameter(n.MAX_VERTEX_UNIFORM_VECTORS), x = n.getParameter(n.MAX_VARYING_VECTORS), E = n.getParameter(n.MAX_FRAGMENT_UNIFORM_VECTORS), R = n.getParameter(n.MAX_SAMPLES), T = n.getParameter(n.SAMPLES); 19989 return { 19990 isWebGL2: !0, 19991 // keeping this for backwards compatibility 19992 getMaxAnisotropy: s, 19993 getMaxPrecision: o, 19994 textureFormatReadable: a, 19995 textureTypeReadable: l, 19996 precision: c, 19997 logarithmicDepthBuffer: h, 19998 reversedDepthBuffer: d, 19999 maxTextures: f, 20000 maxVertexTextures: p, 20001 maxTextureSize: v, 20002 maxCubemapSize: m, 20003 maxAttributes: g, 20004 maxVertexUniforms: _, 20005 maxVaryings: x, 20006 maxFragmentUniforms: E, 20007 maxSamples: R, 20008 samples: T 20009 }; 20010} 20011function Kb(n) { 20012 const e = this; 20013 let t = null, i = 0, r = !1, s = !1; 20014 const a = new xr(), l = new ot(), o = { value: null, needsUpdate: !1 }; 20015 this.uniform = o, this.numPlanes = 0, this.numIntersection = 0, this.init = function(h, d) { 20016 const f = h.length !== 0 || d || // enable state of previous frame - the clipping code has to 20017 // run another frame in order to reset the state: 20018 i !== 0 || r; 20019 return r = d, i = h.length, f; 20020 }, this.beginShadows = function() { 20021 s = !0, u(null); 20022 }, this.endShadows = function() { 20023 s = !1; 20024 }, this.setGlobalState = function(h, d) { 20025 t = u(h, d, 0); 20026 }, this.setState = function(h, d, f) { 20027 const p = h.clippingPlanes, v = h.clipIntersection, m = h.clipShadows, g = n.get(h); 20028 if (!r || p === null || p.length === 0 || s && !m) 20029 s ? u(null) : c(); 20030 else { 20031 const _ = s ? 0 : i, x = _ * 4; 20032 let E = g.clippingState || null; 20033 o.value = E, E = u(p, d, x, f); 20034 for (let R = 0; R !== x; ++R) 20035 E[R] = t[R]; 20036 g.clippingState = E, this.numIntersection = v ? this.numPlanes : 0, this.numPlanes += _; 20037 } 20038 }; 20039 function c() { 20040 o.value !== t && (o.value = t, o.needsUpdate = i > 0), e.numPlanes = i, e.numIntersection = 0; 20041 } 20042 function u(h, d, f, p) { 20043 const v = h !== null ? h.length : 0; 20044 let m = null; 20045 if (v !== 0) { 20046 if (m = o.value, p !== !0 || m === null) { 20047 const g = f + v * 4, _ = d.matrixWorldInverse; 20048 l.getNormalMatrix(_), (m === null || m.length < g) && (m = new Float32Array(g)); 20049 for (let x = 0, E = f; x !== v; ++x, E += 4) 20050 a.copy(h[x]).applyMatrix4(_, l), a.normal.toArray(m, E), m[E + 3] = a.constant; 20051 } 20052 o.value = m, o.needsUpdate = !0; 20053 } 20054 return e.numPlanes = v, e.numIntersection = 0, m; 20055 } 20056} 20057const tr = 4, wd = [0.125, 0.215, 0.35, 0.446, 0.526, 0.582], Sr = 20, Jb = 256, zs = /* @__PURE__ */ new qu(), Sd = /* @__PURE__ */ new Et(); 20058let Fl = null, Bl = 0, zl = 0, Hl = !1; 20059const Zb = /* @__PURE__ */ new W(); 20060class Ed { 20061 /** 20062 * Constructs a new PMREM generator. 20063 * 20064 * @param {WebGLRenderer} renderer - The renderer. 20065 */ 20066 constructor(e) { 20067 this._renderer = e, this._pingPongRenderTarget = null, this._lodMax = 0, this._cubeSize = 0, this._sizeLods = [], this._sigmas = [], this._lodMeshes = [], this._backgroundBox = null, this._cubemapMaterial = null, this._equirectMaterial = null, this._blurMaterial = null, this._ggxMaterial = null; 20068 } 20069 /** 20070 * Generates a PMREM from a supplied Scene, which can be faster than using an 20071 * image if networking bandwidth is low. Optional sigma specifies a blur radius 20072 * in radians to be applied to the scene before PMREM generation. Optional near 20073 * and far planes ensure the scene is rendered in its entirety. 20074 * 20075 * @param {Scene} scene - The scene to be captured. 20076 * @param {number} [sigma=0] - The blur radius in radians. 20077 * @param {number} [near=0.1] - The near plane distance. 20078 * @param {number} [far=100] - The far plane distance. 20079 * @param {Object} [options={}] - The configuration options. 20080 * @param {number} [options.size=256] - The texture size of the PMREM. 20081 * @param {Vector3}
20081 [options.position=origin] - The position of the internal cube camera that renders the scene. 20082 * @return {WebGLRenderTarget} The resulting PMREM. 20083 */ 20084 fromScene(e, t = 0, i = 0.1, r = 100, s = {}) { 20085 const { 20086 size: a = 256, 20087 position: l = Zb 20088 } = s; 20089 Fl = this._renderer.getRenderTarget(), Bl = this._renderer.getActiveCubeFace(), zl = this._renderer.getActiveMipmapLevel(), Hl = this._renderer.xr.enabled, this._renderer.xr.enabled = !1, this._setSize(a); 20090 const o = this._allocateTargets(); 20091 return o.depthBuffer = !0, this._sceneToCubeUV(e, i, r, o, l), t > 0 && this._blur(o, 0, 0, t), this._applyPMREM(o), this._cleanup(o), o; 20092 } 20093 /** 20094 * Generates a PMREM from an equirectangular texture, which can be either LDR 20095 * or HDR. The ideal input image size is 1k (1024 x 512), 20096 * as this matches best with the 256 x 256 cubemap output. 20097 * 20098 * @param {Texture} equirectangular - The equirectangular texture to be converted. 20099 * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use. 20100 * @return {WebGLRenderTarget} The resulting PMREM. 20101 */ 20102 fromEquirectangular(e, t = null) { 20103 return this._fromTexture(e, t); 20104 } 20105 /** 20106 * Generates a PMREM from an cubemap texture, which can be either LDR 20107 * or HDR. The ideal input cube size is 256 x 256, 20108 * as this matches best with the 256 x 256 cubemap output. 20109 * 20110 * @param {Texture} cubemap - The cubemap texture to be converted. 20111 * @param {?WebGLRenderTarget} [renderTarget=null] - The render target to use. 20112 * @return {WebGLRenderTarget} The resulting PMREM. 20113 */ 20114 fromCubemap(e, t = null) { 20115 return this._fromTexture(e, t); 20116 } 20117 /** 20118 * Pre-compiles the cubemap shader. You can get faster start-up by invoking this method during 20119 * your texture's network fetch for increased concurrency. 20120 */ 20121 compileCubemapShader() { 20122 this._cubemapMaterial === null && (this._cubemapMaterial = Ad(), this._compileMaterial(this._cubemapMaterial)); 20123 } 20124 /** 20125 * Pre-compiles the equirectangular shader. You can get faster start-up by invoking this method during 20126 * your texture's network fetch for increased concurrency. 20127 */ 20128 compileEquirectangularShader() { 20129 this._equirectMaterial === null && (this._equirectMaterial = Td(), this._compileMaterial(this._equirectMaterial)); 20130 } 20131 /** 20132 * Disposes of the PMREMGenerator's internal memory. Note that PMREMGenerator is a static class, 20133 * so you should not need more than one PMREMGenerator object. If you do, calling dispose() on 20134 * one of them will cause any others to also become unusable. 20135 */ 20136 dispose() { 20137 this._dispose(), this._cubemapMaterial !== null && this._cubemapMaterial.dispose(), this._equirectMaterial !== null && this._equirectMaterial.dispose(), this._backgroundBox !== null && (this._backgroundBox.geometry.dispose(), this._backgroundBox.material.dispose()); 20138 } 20139 // private interface 20140 _setSize(e) { 20141 this._lodMax = Math.floor(Math.log2(e)), this._cubeSize = Math.pow(2, this._lodMax); 20142 } 20143 _dispose() { 20144 this._blurMaterial !== null && this._blurMaterial.dispose(), this._ggxMaterial !== null && this._ggxMaterial.dispose(), this._pingPongRenderTarget !== null && this._pingPongRenderTarget.dispose(); 20145 for (let e = 0; e < this._lodMeshes.length; e++) 20146 this._lodMeshes[e].geometry.dispose(); 20147 } 20148 _cleanup(e) { 20149 this._renderer.setRenderTarget(Fl, Bl, zl), this._renderer.xr.enabled = Hl, e.scissorTest = !1, Jr(e, 0, 0, e.width, e.height); 20150 } 20151 _fromTexture(e, t) { 20152 e.mapping === Cr || e.mapping === gs ? this._setSize(e.image.length === 0 ? 16 : e.image[0].width || e.image[0].image.width) : this._setSize(e.image.width / 4), Fl = this._renderer.getRenderTarget(), Bl = this._renderer.getActiveCubeFace(), zl = this._renderer.getActiveMipmapLevel(), Hl = this._renderer.xr.enabled, this._renderer.xr.enabled = !1; 20153 const i = t || this._allocateTargets(); 20154 return this._textureToCubeUV(e, i), this._applyPMREM(i), this._cleanup(i), i; 20155 } 20156 _allocateTargets() { 20157 const e = 3 * Math.max(this._cubeSize, 112), t = 4 * this._cubeSize, i = { 20158 magFilter: fn, 20159 minFilter: fn, 20160 generateMipmaps: !1, 20161 type: ki, 20162 format: ni, 20163 colorSpace: Po, 20164 depthBuffer: !1 20165 }, r = Md(e, t, i); 20166 if (this._pingPongRenderTarget === null || this._pingPongRenderTarget.width !== e || this._pingPongRenderTarget.height !== t) { 20167 this._pingPongRenderTarget !== null && this._dispose(), this._pingPongRenderTarget = Md(e, t, i); 20168 const { _lodMax: s } = this; 20169 ({ lodMeshes: this._lodMeshes, sizeLods: this._sizeLods, sigmas: this._sigmas } = Qb(s)), this._blurMaterial = tw(s, e, t), this._ggxMaterial = ew(s, e, t); 20170 } 20171 return r; 20172 } 20173 _compileMaterial(e) { 20174 const t = new _n(new xn(), e); 20175 this._renderer.compile(t, zs); 20176 } 20177 _sceneToCubeUV(e, t, i, r, s) { 20178 const o = new mn(90, 1, t, i), c = [1, -1, 1, 1, 1, 1], u = [1, 1, 1, -1, -1, -1], h = this._renderer, d = h.autoClear, f = h.toneMapping; 20179 h.getClearColor(Sd), h.toneMapping = di, h.autoClear = !1, h.state.buffers.depth.getReversed() && (h.setRenderTarget(r), h.clearDepth(), h.setRenderTarget(null)), this._backgroundBox === null && (this._backgroundBox = new _n( 20180 new Sa(), 20181 new zp({
vendor: 9,281 bytes, lines 20182-20432
20182 name: "PMREM.Background", 20183 side: Mn, 20184 depthWrite: !1, 20185 depthTest: !1 20186 }) 20187 )); 20188 const v = this._backgroundBox, m = v.material; 20189 let g = !1; 20190 const _ = e.background; 20191 _ ? _.isColor && (m.color.copy(_), e.background = null, g = !0) : (m.color.copy(Sd), g = !0); 20192 for (let x = 0; x < 6; x++) { 20193 const E = x % 3; 20194 E === 0 ? (o.up.set(0, c[x], 0), o.position.set(s.x, s.y, s.z), o.lookAt(s.x + u[x], s.y, s.z)) : E === 1 ? (o.up.set(0, 0, c[x]), o.position.set(s.x, s.y, s.z), o.lookAt(s.x, s.y + u[x], s.z)) : (o.up.set(0, c[x], 0), o.position.set(s.x, s.y, s.z), o.lookAt(s.x, s.y, s.z + u[x])); 20195 const R = this._cubeSize; 20196 Jr(r, E * R, x > 2 ? R : 0, R, R), h.setRenderTarget(r), g && h.render(v, o), h.render(e, o); 20197 } 20198 h.toneMapping = f, h.autoClear = d, e.background = _; 20199 } 20200 _textureToCubeUV(e, t) { 20201 const i = this._renderer, r = e.mapping === Cr || e.mapping === gs; 20202 r ? (this._cubemapMaterial === null && (this._cubemapMaterial = Ad()), this._cubemapMaterial.uniforms.flipEnvMap.value = e.isRenderTargetTexture === !1 ? -1 : 1) : this._equirectMaterial === null && (this._equirectMaterial = Td()); 20203 const s = r ? this._cubemapMaterial : this._equirectMaterial, a = this._lodMeshes[0]; 20204 a.material = s; 20205 const l = s.uniforms; 20206 l.envMap.value = e; 20207 const o = this._cubeSize; 20208 Jr(t, 0, 0, 3 * o, 2 * o), i.setRenderTarget(t), i.render(a, zs); 20209 } 20210 _applyPMREM(e) { 20211 const t = this._renderer, i = t.autoClear; 20212 t.autoClear = !1; 20213 const r = this._lodMeshes.length; 20214 for (let s = 1; s < r; s++) 20215 this._applyGGXFilter(e, s - 1, s); 20216 t.autoClear = i; 20217 } 20218 /** 20219 * Applies GGX VNDF importance sampling filter to generate a prefiltered environment map. 20220 * Uses Monte Carlo integration with VNDF importance sampling to accurately represent the 20221 * GGX BRDF for physically-based rendering. Reads from the previous LOD level and 20222 * applies incremental roughness filtering to avoid over-blurring. 20223 * 20224 * @private 20225 * @param {WebGLRenderTarget} cubeUVRenderTarget 20226 * @param {number} lodIn - Source LOD level to read from 20227 * @param {number} lodOut - Target LOD level to write to 20228 */ 20229 _applyGGXFilter(e, t, i) { 20230 const r = this._renderer, s = this._pingPongRenderTarget, a = this._ggxMaterial, l = this._lodMeshes[i]; 20231 l.material = a; 20232 const o = a.uniforms, c = i / (this._lodMeshes.length - 1), u = t / (this._lodMeshes.length - 1), h = Math.sqrt(c * c - u * u), d = 0 + c * 1.25, f = h * d, { _lodMax: p } = this, v = this._sizeLods[i], m = 3 * v * (i > p - tr ? i - p + tr : 0), g = 4 * (this._cubeSize - v); 20233 o.envMap.value = e.texture, o.roughness.value = f, o.mipInt.value = p - t, Jr(s, m, g, 3 * v, 2 * v), r.setRenderTarget(s), r.render(l, zs), o.envMap.value = s.texture, o.roughness.value = 0, o.mipInt.value = p - i, Jr(e, m, g, 3 * v, 2 * v), r.setRenderTarget(e), r.render(l, zs); 20234 } 20235 /** 20236 * This is a two-pass Gaussian blur for a cubemap. Normally this is done 20237 * vertically and horizontally, but this breaks down on a cube. Here we apply 20238 * the blur latitudinally (around the poles), and then longitudinally (towards 20239 * the poles) to approximate the orthogonally-separable blur. It is least 20240 * accurate at the poles, but still does a decent job. 20241 * 20242 * Used for initial scene blur in fromScene() method when sigma > 0. 20243 * 20244 * @private 20245 * @param {WebGLRenderTarget} cubeUVRenderTarget 20246 * @param {number} lodIn 20247 * @param {number} lodOut 20248 * @param {number} sigma 20249 * @param {Vector3} [poleAxis] 20250 */ 20251 _blur(e, t, i, r, s) { 20252 const a = this._pingPongRenderTarget; 20253 this._halfBlur( 20254 e, 20255 a, 20256 t, 20257 i, 20258 r, 20259 "latitudinal", 20260 s 20261 ), this._halfBlur( 20262 a, 20263 e, 20264 i, 20265 i, 20266 r, 20267 "longitudinal", 20268 s 20269 ); 20270 } 20271 _halfBlur(e, t, i, r, s, a, l) { 20272 const o = this._renderer, c = this._blurMaterial; 20273 a !== "latitudinal" && a !== "longitudinal" && xt( 20274 "blur direction must be either latitudinal or longitudinal!" 20275 ); 20276 const u = 3, h = this._lodMeshes[r]; 20277 h.material = c; 20278 const d = c.uniforms, f = this._sizeLods[i] - 1, p = isFinite(s) ? Math.PI / (2 * f) : 2 * Math.PI / (2 * Sr - 1), v = s / p, m = isFinite(s) ? 1 + Math.floor(u * v) : Sr; 20279 m > Sr && tt(`sigmaRadians, ${s}, is too large and will clip, as it requested ${m} samples when the maximum is set to ${Sr}`); 20280 const g = []; 20281 let _ = 0; 20282 for (let w = 0; w < Sr; ++w) { 20283 const y = w / v, M = Math.exp(-y * y / 2); 20284 g.push(M), w === 0 ? _ += M : w < m && (_ += 2 * M); 20285 } 20286 for (let w = 0; w < g.length; w++) 20287 g[w] = g[w] / _; 20288 d.envMap.value = e.texture, d.samples.value = m, d.weights.value = g, d.latitudinal.value = a === "latitudinal", l && (d.poleAxis.value = l); 20289 const { _lodMax: x } = this; 20290 d.dTheta.value = p, d.mipInt.value = x - i; 20291 const E = this._sizeLods[r], R = 3 * E * (r > x - tr ? r - x + tr : 0), T = 4 * (this._cubeSize - E); 20292 Jr(t, R, T, 3 * E, 2 * E), o.setRenderTarget(t), o.render(h, zs); 20293 } 20294} 20295function Qb(n) { 20296 const e = [], t = [], i = []; 20297 let r = n; 20298 const s = n - tr + 1 + wd.length; 20299 for (let a = 0; a < s; a++) { 20300 const l = Math.pow(2, r); 20301 e.push(l); 20302 let o = 1 / l; 20303 a > n - tr ? o = wd[a - n + tr - 1] : a === 0 && (o = 0), t.push(o); 20304 const c = 1 / (l - 2), u = -c, h = 1 + c, d = [u, u, h, u, h, h, u, u, h, h, u, h], f = 6, p = 6, v = 3, m = 2, g = 1, _ = new Float32Array(v * p * f), x = new Float32Array(m * p * f), E = new Float32Array(g * p * f); 20305 for (let T = 0; T < f; T++) { 20306 const w = T % 3 * 2 / 3 - 1, y = T > 2 ? 0 : -1, M = [ 20307 w, 20308 y, 20309 0, 20310 w + 2 / 3, 20311 y, 20312 0, 20313 w + 2 / 3, 20314 y + 1, 20315 0, 20316 w, 20317 y, 20318 0, 20319 w + 2 / 3, 20320 y + 1, 20321 0, 20322 w, 20323 y + 1, 20324 0 20325 ]; 20326 _.set(M, v * p * T), x.set(d, m * p * T); 20327 const L = [T, T, T, T, T, T]; 20328 E.set(L, g * p * T); 20329 } 20330 const R = new xn(); 20331 R.setAttribute("position", new on(_, v)), R.setAttribute("uv", new on(x, m)), R.setAttribute("faceIndex", new on(E, g)), i.push(new _n(R, null)), r > tr && r--; 20332 } 20333 return { lodMeshes: i, sizeLods: e, sigmas: t }; 20334} 20335function Md(n, e, t) { 20336 const i = new fi(n, e, t); 20337 return i.texture.mapping = $o, i.texture.name = "PMREM.cubeUv", i.scissorTest = !0, i; 20338} 20339function Jr(n, e, t, i, r) { 20340 n.viewport.set(e, t, i, r), n.scissor.set(e, t, i, r); 20341} 20342function ew(n, e, t) { 20343 return new yn({ 20344 name: "PMREMGGXConvolution", 20345 defines: { 20346 GGX_SAMPLES: Jb, 20347 CUBEUV_TEXEL_WIDTH: 1 / e, 20348 CUBEUV_TEXEL_HEIGHT: 1 / t, 20349 CUBEUV_MAX_MIP: `${n}.0` 20350 }, 20351 uniforms: { 20352 envMap: { value: null }, 20353 roughness: { value: 0 }, 20354 mipInt: { value: 0 } 20355 }, 20356 vertexShader: Yo(), 20357 fragmentShader: ( 20358 /* glsl */ 20359 ` 20360 20361 precision highp float; 20362 precision highp int; 20363 20364 varying vec3 vOutputDirection; 20365 20366 uniform sampler2D envMap; 20367 uniform float roughness; 20368 uniform float mipInt; 20369 20370 #define ENVMAP_TYPE_CUBE_UV 20371 #include <cube_uv_reflection_fragment> 20372 20373 #define PI 3.14159265359 20374 20375 // Van der Corput radical inverse 20376 float radicalInverse_VdC(uint bits) { 20377 bits = (bits << 16u) | (bits >> 16u); 20378 bits = ((bits & 0x55555555u) << 1u) | ((bits & 0xAAAAAAAAu) >> 1u); 20379 bits = ((bits & 0x33333333u) << 2u) | ((bits & 0xCCCCCCCCu) >> 2u); 20380 bits = ((bits & 0x0F0F0F0Fu) << 4u) | ((bits & 0xF0F0F0F0u) >> 4u); 20381 bits = ((bits & 0x00FF00FFu) << 8u) | ((bits & 0xFF00FF00u) >> 8u); 20382 return float(bits) * 2.3283064365386963e-10; // / 0x100000000 20383 } 20384 20385 // Hammersley sequence 20386 vec2 hammersley(uint i, uint N) { 20387 return vec2(float(i) / float(N), radicalInverse_VdC(i)); 20388 } 20389 20390 // GGX VNDF importance sampling (Eric Heitz 2018) 20391 // "Sampling the GGX Distribution of Visible Normals" 20392 // https://jcgt.org/published/0007/04/01/ 20393 vec3 importanceSampleGGX_VNDF(vec2 Xi, vec3 V, float roughness) { 20394 float alpha = roughness * roughness; 20395 20396 // Section 4.1: Orthonormal basis 20397 vec3 T1 = vec3(1.0, 0.0, 0.0); 20398 vec3 T2 = cross(V, T1); 20399 20400 // Section 4.2: Parameterization of projected area 20401 float r = sqrt(Xi.x); 20402 float phi = 2.0 * PI * Xi.y; 20403 float t1 = r * cos(phi); 20404 float t2 = r * sin(phi); 20405 float s = 0.5 * (1.0 + V.z); 20406 t2 = (1.0 - s) * sqrt(1.0 - t1 * t1) + s * t2; 20407 20408 // Section 4.3: Reprojection onto hemisphere 20409 vec3 Nh = t1 * T1 + t2 * T2 + sqrt(max(0.0, 1.0 - t1 * t1 - t2 * t2)) * V; 20410 20411 // Section 3.4: Transform back to ellipsoid configuration 20412 return normalize(vec3(alpha * Nh.x, alpha * Nh.y, max(0.0, Nh.z))); 20413 } 20414 20415 void main() { 20416 vec3 N = normalize(vOutputDirection); 20417 vec3 V = N; // Assume view direction equals normal for pre-filtering 20418 20419 vec3 prefilteredColor = vec3(0.0); 20420 float totalWeight = 0.0; 20421 20422 // For very low roughness, just sample the environment directly 20423 if (roughness < 0.001) { 20424 gl_FragColor = vec4(bilinearCubeUV(envMap, N, mipInt), 1.0); 20425 return; 20426 } 20427 20428 // Tangent space basis for VNDF sampling 20429 vec3 up = abs(N.z) < 0.999 ? vec3(0.0, 0.0, 1.0) : vec3(1.0, 0.0, 0.0); 20430 vec3 tangent = normalize(cross(up, N)); 20431 vec3 bitangent = cross(N, tangent); 20432
20433 for(uint i = 0u; i < uint(GGX_SAMPLES); i++) { 20434 vec2 Xi = hammersley(i, uint(GGX_SAMPLES)); 20435 20436 // For PMREM, V = N, so in tangent space V is always (0, 0, 1) 20437 vec3 H_tangent = importanceSampleGGX_VNDF(Xi, vec3(0.0, 0.0, 1.0), roughness); 20438 20439 // Transform H back to world space 20440 vec3 H = normalize(tangent * H_tangent.x + bitangent * H_tangent.y + N * H_tangent.z); 20441 vec3 L = normalize(2.0 * dot(V, H) * H - V); 20442 20443 float NdotL = max(dot(N, L), 0.0); 20444 20445 if(NdotL > 0.0) { 20446 // Sample environment at fixed mip level 20447 // VNDF importance sampling handles the distribution filtering 20448 vec3 sampleColor = bilinearCubeUV(envMap, L, mipInt); 20449 20450 // Weight by NdotL for the split-sum approximation 20451 // VNDF PDF naturally accounts for the visible microfacet distribution 20452 prefilteredColor += sampleColor * NdotL; 20453 totalWeight += NdotL; 20454 } 20455 } 20456 20457 if (totalWeight > 0.0) { 20458 prefilteredColor = prefilteredColor / totalWeight; 20459 } 20460 20461 gl_FragColor = vec4(prefilteredColor, 1.0); 20462 } 20463 ` 20464 ), 20465 blending: Ui, 20466 depthTest: !1, 20467 depthWrite: !1 20468 }); 20469} 20470function tw(n, e, t) { 20471 const i = new Float32Array(Sr), r = new W(0, 1, 0); 20472 return new yn({ 20473 name: "SphericalGaussianBlur", 20474 defines: { 20475 n: Sr, 20476 CUBEUV_TEXEL_WIDTH: 1 / e, 20477 CUBEUV_TEXEL_HEIGHT: 1 / t, 20478 CUBEUV_MAX_MIP: `${n}.0` 20479 }, 20480 uniforms: { 20481 envMap: { value: null }, 20482 samples: { value: 1 }, 20483 weights: { value: i }, 20484 latitudinal: { value: !1 }, 20485 dTheta: { value: 0 }, 20486 mipInt: { value: 0 }, 20487 poleAxis: { value: r } 20488 }, 20489 vertexShader: Yo(), 20490 fragmentShader: ( 20491 /* glsl */ 20492 ` 20493 20494 precision mediump float; 20495 precision mediump int; 20496 20497 varying vec3 vOutputDirection; 20498 20499 uniform sampler2D envMap; 20500 uniform int samples; 20501 uniform float weights[ n ]; 20502 uniform bool latitudinal; 20503 uniform float dTheta; 20504 uniform float mipInt; 20505 uniform vec3 poleAxis; 20506 20507 #define ENVMAP_TYPE_CUBE_UV 20508 #include <cube_uv_reflection_fragment> 20509 20510 vec3 getSample( float theta, vec3 axis ) { 20511 20512 float cosTheta = cos( theta ); 20513 // Rodrigues' axis-angle rotation 20514 vec3 sampleDirection = vOutputDirection * cosTheta 20515 + cross( axis, vOutputDirection ) * sin( theta ) 20516 + axis * dot( axis, vOutputDirection ) * ( 1.0 - cosTheta ); 20517 20518 return bilinearCubeUV( envMap, sampleDirection, mipInt ); 20519 20520 } 20521 20522 void main() { 20523 20524 vec3 axis = latitudinal ? poleAxis : cross( poleAxis, vOutputDirection ); 20525 20526 if ( all( equal( axis, vec3( 0.0 ) ) ) ) { 20527 20528 axis = vec3( vOutputDirection.z, 0.0, - vOutputDirection.x ); 20529 20530 } 20531 20532 axis = normalize( axis ); 20533 20534 gl_FragColor = vec4( 0.0, 0.0, 0.0, 1.0 ); 20535 gl_FragColor.rgb += weights[ 0 ] * getSample( 0.0, axis ); 20536 20537 for ( int i = 1; i < n; i++ ) { 20538 20539 if ( i >= samples ) { 20540 20541 break; 20542 20543 } 20544 20545 float theta = dTheta * float( i ); 20546 gl_FragColor.rgb += weights[ i ] * getSample( -1.0 * theta, axis ); 20547 gl_FragColor.rgb += weights[ i ] * getSample( theta, axis ); 20548 20549 } 20550 20551 } 20552 ` 20553 ), 20554 blending: Ui, 20555 depthTest: !1, 20556 depthWrite: !1 20557 }); 20558} 20559function Td() { 20560 return new yn({ 20561 name: "EquirectangularToCubeUV", 20562 uniforms: { 20563 envMap: { value: null } 20564 }, 20565 vertexShader: Yo(), 20566 fragmentShader: ( 20567 /* glsl */ 20568 ` 20569 20570 precision mediump float; 20571 precision mediump int; 20572 20573 varying vec3 vOutputDirection; 20574 20575 uniform sampler2D envMap; 20576 20577 #include <common> 20578 20579 void main() { 20580 20581 vec3 outputDirection = normalize( vOutputDirection ); 20582 vec2 uv = equirectUv( outputDirection ); 20583 20584 gl_FragColor = vec4( texture2D ( envMap, uv ).rgb, 1.0 ); 20585 20586 } 20587 ` 20588 ), 20589 blending: Ui, 20590 depthTest: !1, 20591 depthWrite: !1 20592 }); 20593} 20594function Ad() { 20595 return new yn({ 20596 name: "CubemapToCubeUV", 20597 uniforms: { 20598 envMap: { value: null }, 20599 flipEnvMap: { value: -1 } 20600 }, 20601 vertexShader: Yo(), 20602 fragmentShader: ( 20603 /* glsl */ 20604 ` 20605 20606 precision mediump float; 20607 precision mediump int; 20608 20609 uniform float flipEnvMap; 20610 20611 varying vec3 vOutputDirection; 20612 20613 uniform samplerCube envMap; 20614 20615 void main() { 20616 20617 gl_FragColor = textureCube( envMap, vec3( flipEnvMap * vOutputDirection.x, vOutputDirection.yz ) ); 20618 20619 } 20620 ` 20621 ), 20622 blending: Ui, 20623 depthTest: !1, 20624 depthWrite: !1 20625 }); 20626} 20627function Yo() { 20628 return ( 20629 /* glsl */ 20630 ` 20631 20632 precision mediump float; 20633 precision mediump int; 20634 20635 attribute float faceIndex; 20636 20637 varying vec3 vOutputDirection; 20638 20639 // RH coordinate system; PMREM face-indexing convention 20640 vec3 getDirection( vec2 uv, float face ) { 20641 20642 uv = 2.0 * uv - 1.0; 20643 20644 vec3 direction = vec3( uv, 1.0 ); 20645 20646 if ( face == 0.0 ) { 20647 20648 direction = direction.zyx; // ( 1, v, u ) pos x 20649 20650 } else if ( face == 1.0 ) { 20651 20652 direction = direction.xzy; 20653 direction.xz *= -1.0; // ( -u, 1, -v ) pos y 20654 20655 } else if ( face == 2.0 ) { 20656 20657 direction.x *= -1.0; // ( -u, v, 1 ) pos z 20658 20659 } else if ( face == 3.0 ) { 20660 20661 direction = direction.zyx; 20662 direction.xz *= -1.0; // ( -1, v, -u ) neg x 20663 20664 } else if ( face == 4.0 ) { 20665 20666 direction = direction.xzy; 20667 direction.xy *= -1.0; // ( -u, -1, v ) neg y 20668 20669 } else if ( face == 5.0 ) { 20670 20671 direction.z *= -1.0; // ( u, v, -1 ) neg z 20672 20673 } 20674 20675 return direction; 20676 20677 } 20678 20679 void main() { 20680 20681 vOutputDirection = getDirection( uv, faceIndex ); 20682 gl_Position = vec4( position, 1.0 ); 20683 20684 } 20685 ` 20686 ); 20687} 20688class Kp extends fi { 20689 /** 20690 * Constructs a new cube render target. 20691 * 20692 * @param {number} [size=1] - The size of the render target.
vendor: 11,606 bytes, lines 20693-21055
20693 * @param {RenderTarget~Options} [options] - The configuration object. 20694 */ 20695 constructor(e = 1, t = {}) { 20696 super(e, e, t), this.isWebGLCubeRenderTarget = !0; 20697 const i = { width: e, height: e, depth: 1 }, r = [i, i, i, i, i, i]; 20698 this.texture = new Gp(r), this._setTextureOptions(t), this.texture.isRenderTargetTexture = !0; 20699 } 20700 /** 20701 * Converts the given equirectangular texture to a cube map. 20702 * 20703 * @param {WebGLRenderer} renderer - The renderer. 20704 * @param {Texture} texture - The equirectangular texture. 20705 * @return {WebGLCubeRenderTarget} A reference to this cube render target. 20706 */ 20707 fromEquirectangularTexture(e, t) { 20708 this.texture.type = t.type, this.texture.colorSpace = t.colorSpace, this.texture.generateMipmaps = t.generateMipmaps, this.texture.minFilter = t.minFilter, this.texture.magFilter = t.magFilter; 20709 const i = { 20710 uniforms: { 20711 tEquirect: { value: null } 20712 }, 20713 vertexShader: ( 20714 /* glsl */ 20715 ` 20716 20717 varying vec3 vWorldDirection; 20718 20719 vec3 transformDirection( in vec3 dir, in mat4 matrix ) { 20720 20721 return normalize( ( matrix * vec4( dir, 0.0 ) ).xyz ); 20722 20723 } 20724 20725 void main() { 20726 20727 vWorldDirection = transformDirection( position, modelMatrix ); 20728 20729 #include <begin_vertex> 20730 #include <project_vertex> 20731 20732 } 20733 ` 20734 ), 20735 fragmentShader: ( 20736 /* glsl */ 20737 ` 20738 20739 uniform sampler2D tEquirect; 20740 20741 varying vec3 vWorldDirection; 20742 20743 #include <common> 20744 20745 void main() { 20746 20747 vec3 direction = normalize( vWorldDirection ); 20748 20749 vec2 sampleUV = equirectUv( direction ); 20750 20751 gl_FragColor = texture2D( tEquirect, sampleUV ); 20752 20753 } 20754 ` 20755 ) 20756 }, r = new Sa(5, 5, 5), s = new yn({ 20757 name: "CubemapFromEquirect", 20758 uniforms: _s(i.uniforms), 20759 vertexShader: i.vertexShader, 20760 fragmentShader: i.fragmentShader, 20761 side: Mn, 20762 blending: Ui 20763 }); 20764 s.uniforms.tEquirect.value = t; 20765 const a = new _n(r, s), l = t.minFilter; 20766 return t.minFilter === Mr && (t.minFilter = fn), new oy(1, 10, this).update(e, a), t.minFilter = l, a.geometry.dispose(), a.material.dispose(), this; 20767 } 20768 /** 20769 * Clears this cube render target. 20770 * 20771 * @param {WebGLRenderer} renderer - The renderer. 20772 * @param {boolean} [color=true] - Whether the color buffer should be cleared or not. 20773 * @param {boolean} [depth=true] - Whether the depth buffer should be cleared or not. 20774 * @param {boolean} [stencil=true] - Whether the stencil buffer should be cleared or not. 20775 */ 20776 clear(e, t = !0, i = !0, r = !0) { 20777 const s = e.getRenderTarget(); 20778 for (let a = 0; a < 6; a++) 20779 e.setRenderTarget(this, a), e.clear(t, i, r); 20780 e.setRenderTarget(s); 20781 } 20782} 20783function nw(n) { 20784 let e = /* @__PURE__ */ new WeakMap(), t = /* @__PURE__ */ new WeakMap(), i = null; 20785 function r(d, f = !1) { 20786 return d == null ? null : f ? a(d) : s(d); 20787 } 20788 function s(d) { 20789 if (d && d.isTexture) { 20790 const f = d.mapping; 20791 if (f === ul || f === hl) 20792 if (e.has(d)) { 20793 const p = e.get(d).texture; 20794 return l(p, d.mapping); 20795 } else { 20796 const p = d.image; 20797 if (p && p.height > 0) { 20798 const v = new Kp(p.height); 20799 return v.fromEquirectangularTexture(n, d), e.set(d, v), d.addEventListener("dispose", c), l(v.texture, d.mapping); 20800 } else 20801 return null; 20802 } 20803 } 20804 return d; 20805 } 20806 function a(d) { 20807 if (d && d.isTexture) { 20808 const f = d.mapping, p = f === ul || f === hl, v = f === Cr || f === gs; 20809 if (p || v) { 20810 let m = t.get(d); 20811 const g = m !== void 0 ? m.texture.pmremVersion : 0; 20812 if (d.isRenderTargetTexture && d.pmremVersion !== g) 20813 return i === null && (i = new Ed(n)), m = p ? i.fromEquirectangular(d, m) : i.fromCubemap(d, m), m.texture.pmremVersion = d.pmremVersion, t.set(d, m), m.texture; 20814 if (m !== void 0) 20815 return m.texture; 20816 { 20817 const _ = d.image; 20818 return p && _ && _.height > 0 || v && _ && o(_) ? (i === null && (i = new Ed(n)), m = p ? i.fromEquirectangular(d) : i.fromCubemap(d), m.texture.pmremVersion = d.pmremVersion, t.set(d, m), d.addEventListener("dispose", u), m.texture) : null; 20819 } 20820 } 20821 } 20822 return d; 20823 } 20824 function l(d, f) { 20825 return f === ul ? d.mapping = Cr : f === hl && (d.mapping = gs), d; 20826 } 20827 function o(d) { 20828 let f = 0; 20829 const p = 6; 20830 for (let v = 0; v < p; v++) 20831 d[v] !== void 0 && f++; 20832 return f === p; 20833 } 20834 function c(d) { 20835 const f = d.target; 20836 f.removeEventListener("dispose", c); 20837 const p = e.get(f); 20838 p !== void 0 && (e.delete(f), p.dispose()); 20839 } 20840 function u(d) { 20841 const f = d.target; 20842 f.removeEventListener("dispose", u); 20843 const p = t.get(f); 20844 p !== void 0 && (t.delete(f), p.dispose()); 20845 } 20846 function h() { 20847 e = /* @__PURE__ */ new WeakMap(), t = /* @__PURE__ */ new WeakMap(), i !== null && (i.dispose(), i = null); 20848 } 20849 return { 20850 get: r, 20851 dispose: h 20852 }; 20853} 20854function iw(n) { 20855 const e = {}; 20856 function t(i) { 20857 if (e[i] !== void 0) 20858 return e[i]; 20859 const r = n.getExtension(i); 20860 return e[i] = r, r; 20861 } 20862 return { 20863 has: function(i) { 20864 return t(i) !== null; 20865 }, 20866 init: function() { 20867 t("EXT_color_buffer_float"), t("WEBGL_clip_cull_distance"), t("OES_texture_float_linear"), t("EXT_color_buffer_half_float"), t("WEBGL_multisampled_render_to_texture"), t("WEBGL_render_shared_exponent"); 20868 }, 20869 get: function(i) { 20870 const r = t(i); 20871 return r === null && Kc("WebGLRenderer: " + i + " extension not supported."), r; 20872 } 20873 }; 20874} 20875function rw(n, e, t, i) { 20876 const r = {}, s = /* @__PURE__ */ new WeakMap(); 20877 function a(h) { 20878 const d = h.target; 20879 d.index !== null && e.remove(d.index); 20880 for (const p in d.attributes) 20881 e.remove(d.attributes[p]); 20882 d.removeEventListener("dispose", a), delete r[d.id]; 20883 const f = s.get(d); 20884 f && (e.remove(f), s.delete(d)), i.releaseStatesOfGeometry(d), d.isInstancedBufferGeometry === !0 && delete d._maxInstanceCount, t.memory.geometries--; 20885 } 20886 function l(h, d) { 20887 return r[d.id] === !0 || (d.addEventListener("dispose", a), r[d.id] = !0, t.memory.geometries++), d; 20888 } 20889 function o(h) { 20890 const d = h.attributes; 20891 for (const f in d) 20892 e.update(d[f], n.ARRAY_BUFFER); 20893 } 20894 function c(h) { 20895 const d = [], f = h.index, p = h.attributes.position; 20896 let v = 0; 20897 if (p === void 0) 20898 return; 20899 if (f !== null) { 20900 const _ = f.array; 20901 v = f.version; 20902 for (let x = 0, E = _.length; x < E; x += 3) { 20903 const R = _[x + 0], T = _[x + 1], w = _[x + 2]; 20904 d.push(R, T, T, w, w, R); 20905 } 20906 } else { 20907 const _ = p.array; 20908 v = p.version; 20909 for (let x = 0, E = _.length / 3 - 1; x < E; x += 3) { 20910 const R = x + 0, T = x + 1, w = x + 2; 20911 d.push(R, T, T, w, w, R); 20912 } 20913 } 20914 const m = new (p.count >= 65535 ? Bp : Fp)(d, 1); 20915 m.version = v; 20916 const g = s.get(h); 20917 g && e.remove(g), s.set(h, m); 20918 } 20919 function u(h) { 20920 const d = s.get(h); 20921 if (d) { 20922 const f = h.index; 20923 f !== null && d.version < f.version && c(h); 20924 } else 20925 c(h); 20926 return s.get(h); 20927 } 20928 return { 20929 get: l, 20930 update: o, 20931 getWireframeAttribute: u 20932 }; 20933} 20934function sw(n, e, t) { 20935 let i; 20936 function r(h) { 20937 i = h; 20938 } 20939 let s, a; 20940 function l(h) { 20941 s = h.type, a = h.bytesPerElement; 20942 } 20943 function o(h, d) { 20944 n.drawElements(i, d, s, h * a), t.update(d, i, 1); 20945 } 20946 function c(h, d, f) { 20947 f !== 0 && (n.drawElementsInstanced(i, d, s, h * a, f), t.update(d, i, f)); 20948 } 20949 function u(h, d, f) { 20950 if (f === 0) return; 20951 e.get("WEBGL_multi_draw").multiDrawElementsWEBGL(i, d, 0, s, h, 0, f); 20952 let v = 0; 20953 for (let m = 0; m < f; m++) 20954 v += d[m]; 20955 t.update(v, i, 1); 20956 } 20957 this.setMode = r, this.setIndex = l, this.render = o, this.renderInstances = c, this.renderMultiDraw = u; 20958} 20959function aw(n) { 20960 const e = { 20961 geometries: 0, 20962 textures: 0 20963 }, t = { 20964 frame: 0, 20965 calls: 0, 20966 triangles: 0, 20967 points: 0, 20968 lines: 0 20969 }; 20970 function i(s, a, l) { 20971 switch (t.calls++, a) { 20972 case n.TRIANGLES: 20973 t.triangles += l * (s / 3); 20974 break; 20975 case n.LINES: 20976 t.lines += l * (s / 2); 20977 break; 20978 case n.LINE_STRIP: 20979 t.lines += l * (s - 1); 20980 break; 20981 case n.LINE_LOOP: 20982 t.lines += l * s; 20983 break; 20984 case n.POINTS: 20985 t.points += l * s; 20986 break; 20987 default: 20988 xt("WebGLInfo: Unknown draw mode:", a); 20989 break; 20990 } 20991 } 20992 function r() { 20993 t.calls = 0, t.triangles = 0, t.points = 0, t.lines = 0; 20994 } 20995 return { 20996 memory: e, 20997 render: t, 20998 programs: null, 20999 autoReset: !0, 21000 reset: r, 21001 update: i 21002 }; 21003} 21004function ow(n, e, t) { 21005 const i = /* @__PURE__ */ new WeakMap(), r = new Gt(); 21006 function s(a, l, o) { 21007 const c = a.morphTargetInfluences, u = l.morphAttributes.position || l.morphAttributes.normal || l.morphAttributes.color, h = u !== void 0 ? u.length : 0; 21008 let d = i.get(l); 21009 if (d === void 0 || d.count !== h) { 21010 let M = function() { 21011 w.dispose(), i.delete(l), l.removeEventListener("dispose", M); 21012 }; 21013 d !== void 0 && d.texture.dispose(); 21014 const f = l.morphAttributes.position !== void 0, p = l.morphAttributes.normal !== void 0, v = l.morphAttributes.color !== void 0, m = l.morphAttributes.position || [], g = l.morphAttributes.normal || [], _ = l.morphAttributes.color || []; 21015 let x = 0; 21016 f === !0 && (x = 1), p === !0 && (x = 2), v === !0 && (x = 3); 21017 let E = l.attributes.position.count * x, R = 1; 21018 E > e.maxTextureSize && (R = Math.ceil(E / e.maxTextureSize), E = e.maxTextureSize); 21019 const T = new Float32Array(E * R * 4 * h), w = new Op(T, E, R, h); 21020 w.type = ti, w.needsUpdate = !0; 21021 const y = x * 4; 21022 for (let L = 0; L < h; L++) { 21023 const C = m[L], U = g[L], V = _[L], F = E * R * 4 * L; 21024 for (let I = 0; I < C.count; I++) { 21025 const k = I * y; 21026 f === !0 && (r.fromBufferAttribute(C, I), T[F + k + 0] = r.x, T[F + k + 1] = r.y, T[F + k + 2] = r.z, T[F + k + 3] = 0), p === !0 && (r.fromBufferAttribute(U, I), T[F + k + 4] = r.x, T[F + k + 5] = r.y, T[F + k + 6] = r.z, T[F + k + 7] = 0), v === !0 && (r.fromBufferAttribute(V, I), T[F + k + 8] = r.x, T[F + k + 9] = r.y, T[F + k + 10] = r.z, T[F + k + 11] = V.itemSize === 4 ? r.w : 1); 21027 } 21028 } 21029 d = { 21030 count: h, 21031 texture: w, 21032 size: new wt(E, R) 21033 }, i.set(l, d), l.addEventListener("dispose", M); 21034 } 21035 if (a.isInstancedMesh === !0 && a.morphTexture !== null) 21036 o.getUniforms().setValue(n, "morphTexture", a.morphTexture, t); 21037 else { 21038 let f = 0; 21039 for (let v = 0; v < c.length; v++) 21040 f += c[v]; 21041 const p = l.morphTargetsRelative ? 1 : 1 - f; 21042 o.getUniforms().setValue(n, "morphTargetBaseInfluence", p), o.getUniforms().setValue(n, "morphTargetInfluences", c); 21043 } 21044 o.getUniforms().setValue(n, "morphTargetsTexture", d.texture, t), o.getUniforms().setValue(n, "morphTargetsTextureSize", d.size); 21045 } 21046 return { 21047 update: s 21048 }; 21049} 21050function lw(n, e, t, i, r) { 21051 let s = /* @__PURE__ */ new WeakMap(); 21052 function a(c) { 21053 const u = r.render.frame, h = c.geometry, d = e.get(c, h); 21054 if (s.get(d) !== u && (e.update(d), s.set(d, u)), c.isInstancedMesh && (c.hasEventListener("dispose", o) === !1 && c.addEventListener("dispose", o), s.get(c) !== u && (t.update(c.instanceMatrix, n.ARRAY_BUFFER), c.instanceColor !== null && t.update(c.instanceColor, n.ARRAY_BUFFER), s.set(c, u))), c.isSkinnedMesh) { 21055 const f = c.skeleton;
21056 s.get(f) !== u && (f.update(), s.set(f, u)); 21057 } 21058 return d; 21059 } 21060 function l() { 21061 s = /* @__PURE__ */ new WeakMap(); 21062 } 21063 function o(c) { 21064 const u = c.target; 21065 u.removeEventListener("dispose", o), i.releaseStatesOfObject(u), t.remove(u.instanceMatrix), u.instanceColor !== null && t.remove(u.instanceColor); 21066 } 21067 return { 21068 update: a, 21069 dispose: l 21070 }; 21071} 21072const cw = { 21073 [bp]: "LINEAR_TONE_MAPPING", 21074 [wp]: "REINHARD_TONE_MAPPING", 21075 [Sp]: "CINEON_TONE_MAPPING", 21076 [Ep]: "ACES_FILMIC_TONE_MAPPING", 21077 [Tp]: "AGX_TONE_MAPPING", 21078 [Ap]: "NEUTRAL_TONE_MAPPING", 21079 [Mp]: "CUSTOM_TONE_MAPPING" 21080}; 21081function uw(n, e, t, i, r) { 21082 const s = new fi(e, t, { 21083 type: n, 21084 depthBuffer: i, 21085 stencilBuffer: r, 21086 depthTexture: i ? new vs(e, t) : void 0 21087 }), a = new fi(e, t, { 21088 type: ki, 21089 depthBuffer: !1, 21090 stencilBuffer: !1 21091 }), l = new xn(); 21092 l.setAttribute("position", new vn([-1, 3, 0, -1, -1, 0, 3, -1, 0], 3)), l.setAttribute("uv", new vn([0, 2, 0, 0, 2, 0], 2)); 21093 const o = new ny({ 21094 uniforms: { 21095 tDiffuse: { value: null } 21096 }, 21097 vertexShader: ( 21098 /* glsl */ 21099 ` 21100 precision highp float; 21101 21102 uniform mat4 modelViewMatrix; 21103 uniform mat4 projectionMatrix; 21104 21105 attribute vec3 position; 21106 attribute vec2 uv; 21107 21108 varying vec2 vUv; 21109 21110 void main() { 21111 vUv = uv; 21112 gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 ); 21113 }` 21114 ), 21115 fragmentShader: ( 21116 /* glsl */ 21117 ` 21118 precision highp float; 21119 21120 uniform sampler2D tDiffuse; 21121 21122 varying vec2 vUv; 21123 21124 #include <tonemapping_pars_fragment> 21125 #include <colorspace_pars_fragment> 21126 21127 void main() { 21128 gl_FragColor = texture2D( tDiffuse, vUv ); 21129 21130 #ifdef LINEAR_TONE_MAPPING 21131 gl_FragColor.rgb = LinearToneMapping( gl_FragColor.rgb ); 21132 #elif defined( REINHARD_TONE_MAPPING ) 21133 gl_FragColor.rgb = ReinhardToneMapping( gl_FragColor.rgb ); 21134 #elif defined( CINEON_TONE_MAPPING ) 21135 gl_FragColor.rgb = CineonToneMapping( gl_FragColor.rgb ); 21136 #elif defined( ACES_FILMIC_TONE_MAPPING ) 21137 gl_FragColor.rgb = ACESFilmicToneMapping( gl_FragColor.rgb ); 21138 #elif defined( AGX_TONE_MAPPING ) 21139 gl_FragColor.rgb = AgXToneMapping( gl_FragColor.rgb ); 21140 #elif defined( NEUTRAL_TONE_MAPPING ) 21141 gl_FragColor.rgb = NeutralToneMapping( gl_FragColor.rgb ); 21142 #elif defined( CUSTOM_TONE_MAPPING ) 21143 gl_FragColor.rgb = CustomToneMapping( gl_FragColor.rgb ); 21144 #endif 21145 21146 #ifdef SRGB_TRANSFER 21147 gl_FragColor = sRGBTransferOETF( gl_FragColor ); 21148 #endif 21149 }` 21150 ), 21151 depthTest: !1, 21152 depthWrite: !1 21153 }), c = new _n(l, o), u = new qu(-1, 1, 1, -1, 0, 1); 21154 let h = null, d = null, f = !1, p, v = null, m = [], g = !1; 21155 this.setSize = function(_, x) { 21156 s.setSize(_, x), a.setSize(_, x); 21157 for (let E = 0; E < m.length; E++) { 21158 const R = m[E]; 21159 R.setSize && R.setSize(_, x); 21160 } 21161 }, this.setEffects = function(_) { 21162 m = _, g = m.length > 0 && m[0].isRenderPass === !0; 21163 const x = s.width, E = s.height; 21164 for (let R = 0; R < m.length; R++) { 21165 const T = m[R]; 21166 T.setSize && T.setSize(x, E); 21167 } 21168 }, this.begin = function(_, x) { 21169 if (f || _.toneMapping === di && m.length === 0) return !1; 21170 if (v = x, x !== null) { 21171 const E = x.width, R = x.height; 21172 (s.width !== E || s.height !== R) && this.setSize(E, R); 21173 } 21174 return g === !1 && _.setRenderTarget(s), p = _.toneMapping, _.toneMapping = di, !0; 21175 }, this.hasRenderPass = function() { 21176 return g; 21177 }, this.end = function(_, x) { 21178 _.toneMapping = p, f = !0; 21179 let E = s, R = a; 21180 for (let T = 0; T < m.length; T++) { 21181 const w = m[T]; 21182 if (w.enabled !== !1 && (w.render(_, R, E, x), w.needsSwap !== !1)) { 21183 const y = E; 21184 E = R, R = y; 21185 } 21186 } 21187 if (h !== _.outputColorSpace || d !== _.toneMapping) { 21188 h = _.outputColorSpace, d = _.toneMapping, o.defines = {}, _t.getTransfer(h) === Nt && (o.defines.SRGB_TRANSFER = ""); 21189 const T = cw[d]; 21190 T && (o.defines[T] = ""), o.needsUpdate = !0; 21191 } 21192 o.uniforms.tDiffuse.value = E.texture, _.setRenderTarget(v), _.render(c, u), v = null, f = !1; 21193 }, this.isCompositing = function() { 21194 return f; 21195 }, this.dispose = function() { 21196 s.depthTexture && s.depthTexture.dispose(), s.dispose(), a.dispose(), l.dispose(), o.dispose(); 21197 }; 21198} 21199const Jp = /* @__PURE__ */ new gn(), eu = /* @__PURE__ */ new vs(1, 1), Zp = /* @__PURE__ */ new Op(), Qp = /* @__PURE__ */ new N_(), em = /* @__PURE__ */ new Gp(), Rd = [], Cd = [], Pd = new Float32Array(16), Ld = new Float32Array(9), Nd = new Float32Array(4); 21200function Ts(n, e, t) { 21201 const i = n[0]; 21202 if (i <= 0 || i > 0) return n; 21203 const r = e * t; 21204 let s = Rd[r]; 21205 if (s === void 0 && (s = new Float32Array(r), Rd[r] = s), e !== 0) { 21206 i.toArray(s, 0); 21207 for (let a = 1, l = 0; a !== e; ++a) 21208 l += t, n[a].toArray(s, l); 21209 } 21210 return s; 21211} 21212function Qt(n, e) { 21213 if (n.length !== e.length) return !1; 21214 for (let t = 0, i = n.length; t < i; t++) 21215 if (n[t] !== e[t]) return !1; 21216 return !0; 21217} 21218function en(n, e) { 21219 for (let t = 0, i = e.length; t < i; t++) 21220 n[t] = e[t]; 21221} 21222function Ko(n, e) { 21223 let t = Cd[e]; 21224 t === void 0 && (t = new Int32Array(e), Cd[e] = t); 21225 for (let i = 0; i !== e; ++i) 21226 t[i] = n.allocateTextureUnit(); 21227 return t; 21228} 21229function hw(n, e) { 21230 const t = this.cache; 21231 t[0] !== e && (n.uniform1f(this.addr, e), t[0] = e); 21232} 21233function dw(n, e) { 21234 const t = this.cache; 21235 if (e.x !== void 0) 21236 (t[0] !== e.x || t[1] !== e.y) && (n.uniform2f(this.addr, e.x, e.y), t[0] = e.x, t[1] = e.y); 21237 else { 21238 if (Qt(t, e)) return; 21239 n.uniform2fv(this.addr, e), en(t, e); 21240 } 21241} 21242function fw(n, e) { 21243 const t = this.cache; 21244 if (e.x !== void 0) 21245 (t[0] !== e.x || t[1] !== e.y || t[2] !== e.z) && (n.uniform3f(this.addr, e.x, e.y, e.z), t[0] = e.x, t[1] = e.y, t[2] = e.z); 21246 else if (e.r !== void 0) 21247 (t[0] !== e.r || t[1] !== e.g || t[2] !== e.b) && (n.uniform3f(this.addr, e.r, e.g, e.b), t[0] = e.r, t[1] = e.g, t[2] = e.b); 21248 else { 21249 if (Qt(t, e)) return; 21250 n.uniform3fv(this.addr, e), en(t, e); 21251 } 21252} 21253function pw(n, e) { 21254 const t = this.cache; 21255 if (e.x !== void 0) 21256 (t[0] !== e.x || t[1] !== e.y || t[2] !== e.z || t[3] !== e.w) && (n.uniform4f(this.addr, e.x, e.y, e.z, e.w), t[0] = e.x, t[1] = e.y, t[2] = e.z, t[3] = e.w); 21257 else { 21258 if (Qt(t, e)) return; 21259 n.uniform4fv(this.addr, e), en(t, e); 21260 } 21261} 21262function mw(n, e) { 21263 const t = this.cache, i = e.elements; 21264 if (i === void 0) { 21265 if (Qt(t, e)) return; 21266 n.uniformMatrix2fv(this.addr, !1, e), en(t, e); 21267 } else { 21268 if (Qt(t, i)) return; 21269 Nd.set(i), n.uniformMatrix2fv(this.addr, !1, Nd), en(t, i); 21270 } 21271} 21272function gw(n, e) { 21273 const t = this.cache, i = e.elements; 21274 if (i === void 0) { 21275 if (Qt(t, e)) return; 21276 n.uniformMatrix3fv(this.addr, !1, e), en(t, e); 21277 } else { 21278 if (Qt(t, i)) return; 21279 Ld.set(i), n.uniformMatrix3fv(this.addr, !1, Ld), en(t, i); 21280 } 21281} 21282function vw(n, e) { 21283 const t = this.cache, i = e.elements; 21284 if (i === void 0) { 21285 if (Qt(t, e)) return; 21286 n.uniformMatrix4fv(this.addr, !1, e), en(t, e); 21287 } else { 21288 if (Qt(t, i)) return; 21289 Pd.set(i), n.uniformMatrix4fv(this.addr, !1, Pd), en(t, i); 21290 } 21291} 21292function _w(n, e) { 21293 const t = this.cache; 21294 t[0] !== e && (n.uniform1i(this.addr, e), t[0] = e); 21295} 21296function yw(n, e) { 21297 const t = this.cache; 21298 if (e.x !== void 0) 21299 (t[0] !== e.x || t[1] !== e.y) && (n.uniform2i(this.addr, e.x, e.y), t[0] = e.x, t[1] = e.y); 21300 else { 21301 if (Qt(t, e)) return; 21302 n.uniform2iv(this.addr, e), en(t, e); 21303 } 21304} 21305function xw(n, e) { 21306 const t = this.cache; 21307 if (e.x !== void 0) 21308 (t[0] !== e.x || t[1] !== e.y || t[2] !== e.z) && (n.uniform3i(this.addr, e.x, e.y, e.z), t[0] = e.x, t[1] = e.y, t[2] = e.z); 21309 else { 21310 if (Qt(t, e)) return; 21311 n.uniform3iv(this.addr, e), en(t, e); 21312 } 21313} 21314function bw(n, e) { 21315 const t = this.cache; 21316 if (e.x !== void 0) 21317 (t[0] !== e.x || t[1] !== e.y || t[2] !== e.z || t[3] !== e.w) && (n.uniform4i(this.addr, e.x, e.y, e.z, e.w), t[0] = e.x, t[1] = e.y, t[2] = e.z, t[3] = e.w); 21318 else { 21319 if (Qt(t, e)) return; 21320 n.uniform4iv(this.addr, e), en(t, e); 21321 } 21322} 21323function ww(n, e) { 21324 const t = this.cache; 21325 t[0] !== e && (n.uniform1ui(this.addr, e), t[0] = e); 21326} 21327function Sw(n, e) { 21328 const t = this.cache; 21329 if (e.x !== void 0) 21330 (t[0] !== e.x || t[1] !== e.y) && (n.uniform2ui(this.addr, e.x, e.y), t[0] = e.x, t[1] = e.y); 21331 else { 21332 if (Qt(t, e)) return; 21333 n.uniform2uiv(this.addr, e), en(t, e); 21334 } 21335} 21336function Ew(n, e) { 21337 const t = this.cache; 21338 if (e.x !== void 0) 21339 (t[0] !== e.x || t[1] !== e.y || t[2] !== e.z) && (n.uniform3ui(this.addr, e.x, e.y, e.z), t[0] = e.x, t[1] = e.y, t[2] = e.z); 21340 else { 21341 if (Qt(t, e)) return; 21342 n.uniform3uiv(this.addr, e), en(t, e); 21343 } 21344} 21345function Mw(n, e) { 21346 const t = this.cache; 21347 if (e.x !== void 0) 21348 (t[0] !== e.x || t[1] !== e.y || t[2] !== e.z || t[3] !== e.w) && (n.uniform4ui(this.addr, e.x, e.y, e.z, e.w), t[0] = e.x, t[1] = e.y, t[2] = e.z, t[3] = e.w); 21349 else { 21350 if (Qt(t, e)) return; 21351 n.uniform4uiv(this.addr, e), en(t, e); 21352 } 21353} 21354function Tw(n, e, t) { 21355 const i = this.cache, r = t.allocateTextureUnit(); 21356 i[0] !== r && (n.uniform1i(this.addr, r), i[0] = r); 21357 let s; 21358 this.type === n.SAMPLER_2D_SHADOW ? (eu.compareFunction = t.isReversedDepthBuffer() ? Hu : zu, s = eu) : s = Jp, t.setTexture2D(e || s, r); 21359} 21360function Aw(n, e, t) { 21361 const i = this.cache, r = t.allocateTextureUnit(); 21362 i[0] !== r && (n.uniform1i(this.addr, r), i[0] = r), t.setTexture3D(e || Qp, r); 21363} 21364function Rw(n, e, t) { 21365 const i = this.cache, r = t.allocateTextureUnit(); 21366 i[0] !== r && (n.uniform1i(this.addr, r), i[0] = r), t.setTextureCube(e || em, r); 21367} 21368function Cw(n, e, t) { 21369 const i = this.cache, r = t.allocateTextureUnit(); 21370 i[0] !== r && (n.uniform1i(this.addr, r), i[0] = r), t.setTexture2DArray(e || Zp, r); 21371} 21372function Pw(n) { 21373 switch (n) { 21374 case 5126: 21375 return hw; 21376 // FLOAT 21377 case 35664: 21378 return dw; 21379 // _VEC2 21380 case 35665: 21381 return fw; 21382 // _VEC3 21383 case 35666: 21384 return pw; 21385 // _VEC4 21386 case 35674: 21387 return mw; 21388 // _MAT2 21389 case 35675: 21390 return gw; 21391 // _MAT3 21392 case 35676: 21393 return vw; 21394 // _MAT4 21395 case 5124: 21396 case 35670: 21397 return _w; 21398 // INT, BOOL 21399 case 35667: 21400 case 35671: 21401 return yw; 21402 // _VEC2 21403 case 35668: 21404 case 35672: 21405 return xw; 21406 // _VEC3 21407 case 35669: 21408 case 35673: 21409 return bw; 21410 // _VEC4 21411 case 5125: 21412 return ww; 21413 // UINT 21414 case 36294: 21415 return Sw; 21416 // _VEC2 21417 case 36295: 21418 return Ew; 21419 // _VEC3 21420 case 36296: 21421 return Mw; 21422 // _VEC4 21423 case 35678: 21424 // SAMPLER_2D 21425 case 36198: 21426 // SAMPLER_EXTERNAL_OES 21427 case 36298: 21428 // INT_SAMPLER_2D 21429 case 36306: 21430 // UNSIGNED_INT_SAMPLER_2D 21431 case 35682: 21432 return Tw; 21433 case 35679: 21434 // SAMPLER_3D 21435 case 36299: 21436 // INT_SAMPLER_3D 21437 case 36307: 21438 return Aw; 21439 case 35680: 21440 // SAMPLER_CUBE 21441 case 36300: 21442 // INT_SAMPLER_CUBE 21443 case 36308: 21444 // UNSIGNED_INT_SAMPLER_CUBE 21445 case 36293: 21446 return Rw; 21447 case 36289: 21448 // SAMPLER_2D_ARRAY 21449 case 36303: 21450 // INT_SAMPLER_2D_ARRAY 21451 case 36311: 21452 // UNSIGNED_INT_SAMPLER_2D_ARRAY 21453 case 36292: 21454 return Cw; 21455 } 21456} 21457function Lw(n, e) { 21458 n.uniform1fv(this.addr, e); 21459} 21460function Nw(n, e) { 21461 const t = Ts(e, this.size, 2); 21462 n.uniform2fv(this.addr, t); 21463} 21464function Iw(n, e) { 21465 const t = Ts(e, this.size, 3); 21466 n.uniform3fv(this.addr, t); 21467} 21468function Dw(n, e) { 21469 const t = Ts(e, this.size, 4); 21470 n.uniform4fv(this.addr, t); 21471} 21472function Uw(n, e) { 21473 const t = Ts(e, this.size, 4); 21474 n.uniformMatrix2fv(this.addr, !1, t); 21475} 21476function Ow(n, e) { 21477 const t = Ts(e, this.size, 9); 21478 n.uniformMatrix3fv(this.addr, !1, t); 21479} 21480function kw(n, e) { 21481 const t = Ts(e, this.size, 16); 21482 n.uniformMatrix4fv(this.addr, !1, t); 21483} 21484function Fw(n, e) { 21485 n.uniform1iv(this.addr, e); 21486} 21487function Bw(n, e) { 21488 n.uniform2iv(this.addr, e); 21489} 21490function zw(n, e) { 21491 n.uniform3iv(this.addr, e); 21492} 21493function Hw(n, e) { 21494 n.uniform4iv(this.addr, e); 21495} 21496function Gw(n, e) { 21497 n.uniform1uiv(this.addr, e); 21498} 21499function Vw(n, e) { 21500 n.uniform2uiv(this.addr, e); 21501} 21502function Ww(n, e) { 21503 n.uniform3uiv(this.addr, e); 21504} 21505function $w(n, e) { 21506 n.uniform4uiv(this.addr, e); 21507} 21508function jw(n, e, t) { 21509 const i = this.cache, r = e.length, s = Ko(t, r); 21510 Qt(i, s) || (n.uniform1iv(this.addr, s), en(i, s)); 21511 let a; 21512 this.type === n.SAMPLER_2D_SHADOW ? a = eu : a = Jp; 21513 for (let l = 0; l !== r; ++l) 21514 t.setTexture2D(e[l] || a, s[l]); 21515} 21516function Xw(n, e, t) { 21517 const i = this.cache, r = e.length, s = Ko(t, r); 21518 Qt(i, s) || (n.uniform1iv(this.addr, s), en(i, s)); 21519 for (let a = 0; a !== r; ++a) 21520 t.setTexture3D(e[a] || Qp, s[a]); 21521} 21522function qw(n, e, t) { 21523 const i = this.cache, r = e.length, s = Ko(t, r); 21524 Qt(i, s) || (n.uniform1iv(this.addr, s), en(i, s)); 21525 for (let a = 0; a !== r; ++a) 21526 t.setTextureCube(e[a] || em, s[a]); 21527} 21528function Yw(n, e, t) { 21529 const i = this.cache, r = e.length, s = Ko(t, r); 21530 Qt(i, s) || (n.uniform1iv(this.addr, s), en(i, s)); 21531 for (let a = 0; a !== r; ++a) 21532 t.setTexture2DArray(e[a] || Zp, s[a]); 21533} 21534function Kw(n) { 21535 switch (n) { 21536 case 5126: 21537 return Lw; 21538 // FLOAT 21539 case 35664: 21540 return Nw; 21541 // _VEC2 21542 case 35665: 21543 return Iw; 21544 // _VEC3 21545 case 35666: 21546 return Dw; 21547 // _VEC4 21548 case 35674: 21549 return Uw; 21550 // _MAT2 21551 case 35675: 21552 return Ow; 21553 // _MAT3 21554 case 35676: 21555 return kw; 21556 // _MAT4 21557 case 5124: 21558 case 35670: 21559 return Fw; 21560 // INT, BOOL 21561 case 35667: 21562 case 35671: 21563 return Bw; 21564 // _VEC2 21565 case 35668: 21566 case 35672: 21567 return zw; 21568 // _VEC3 21569 case 35669: 21570 case 35673: 21571 return Hw; 21572 // _VEC4 21573 case 5125: 21574 return Gw; 21575 // UINT 21576 case 36294: 21577 return Vw; 21578 // _VEC2 21579 case 36295: 21580 return Ww; 21581 // _VEC3 21582 case 36296: 21583 return $w; 21584 // _VEC4 21585 case 35678: 21586 // SAMPLER_2D 21587 case 36198: 21588 // SAMPLER_EXTERNAL_OES 21589 case 36298: 21590 // INT_SAMPLER_2D 21591 case 36306: 21592 // UNSIGNED_INT_SAMPLER_2D 21593 case 35682: 21594 return jw; 21595 case 35679: 21596 // SAMPLER_3D 21597 case 36299: 21598 // INT_SAMPLER_3D 21599 case 36307: 21600 return Xw; 21601 case 35680: 21602 // SAMPLER_CUBE 21603 case 36300: 21604 // INT_SAMPLER_CUBE 21605 case 36308: 21606 // UNSIGNED_INT_SAMPLER_CUBE 21607 case 36293: 21608 return qw; 21609 case 36289: 21610 // SAMPLER_2D_ARRAY 21611 case 36303: 21612 // INT_SAMPLER_2D_ARRAY 21613 case 36311: 21614 // UNSIGNED_INT_SAMPLER_2D_ARRAY 21615 case 36292: 21616 return Yw; 21617 } 21618} 21619class Jw { 21620 constructor(e, t, i) { 21621 this.id = e, this.addr = i, this.cache = [], this.type = t.type, this.setValue = Pw(t.type); 21622 } 21623} 21624class Zw { 21625 constructor(e, t, i) { 21626 this.id = e, this.addr = i, this.cache = [], this.type = t.type, this.size = t.size, this.setValue = Kw(t.type); 21627 } 21628} 21629class Qw { 21630 constructor(e) { 21631 this.id = e, this.seq = [], this.map = {}; 21632 } 21633 setValue(e, t, i) { 21634 const r = this.seq; 21635 for (let s = 0, a = r.length; s !== a; ++s) { 21636 const l = r[s]; 21637 l.setValue(e, t[l.id], i); 21638 } 21639 } 21640} 21641const Gl = /(\w+)(\])?(\[|\.)?/g; 21642function Id(n, e) { 21643 n.seq.push(e), n.map[e.id] = e; 21644} 21645function eS(n, e, t) { 21646 const i = n.name, r = i.length; 21647 for (Gl.lastIndex = 0; ; ) { 21648 const s = Gl.exec(i), a = Gl.lastIndex; 21649 let l = s[1]; 21650 const o = s[2] === "]", c = s[3]; 21651 if (o && (l = l | 0), c === void 0 || c === "[" && a + 2 === r) { 21652 Id(t, c === void 0 ? new Jw(l, n, e) : new Zw(l, n, e)); 21653 break; 21654 } else { 21655 let h = t.map[l]; 21656 h === void 0 && (h = new Qw(l), Id(t, h)), t = h; 21657 } 21658 } 21659} 21660class So { 21661 constructor(e, t) { 21662 this.seq = [], this.map = {}; 21663 const i = e.getProgramParameter(t, e.ACTIVE_UNIFORMS); 21664 for (let a = 0; a < i; ++a) { 21665 const l = e.getActiveUniform(t, a), o = e.getUniformLocation(t, l.name); 21666 eS(l, o, this); 21667 } 21668 const r = [], s = []; 21669 for (const a of this.seq) 21670 a.type === e.SAMPLER_2D_SHADOW || a.type === e.SAMPLER_CUBE_SHADOW || a.type === e.SAMPLER_2D_ARRAY_SHADOW ? r.push(a) : s.push(a); 21671 r.length > 0 && (this.seq = r.concat(s)); 21672 } 21673 setValue(e, t, i, r) { 21674 const s = this.map[t]; 21675 s !== void 0 && s.setValue(e, i, r); 21676 } 21677 setOptional(e, t, i) { 21678 const r = t[i]; 21679 r !== void 0 && this.setValue(e, i, r); 21680 } 21681 static upload(e, t, i, r) { 21682 for (l
vendor: 7,478 bytes, lines 21682-21919
21682et s = 0, a = t.length; s !== a; ++s) { 21683 const l = t[s], o = i[l.id]; 21684 o.needsUpdate !== !1 && l.setValue(e, o.value, r); 21685 } 21686 } 21687 static seqWithValue(e, t) { 21688 const i = []; 21689 for (let r = 0, s = e.length; r !== s; ++r) { 21690 const a = e[r]; 21691 a.id in t && i.push(a); 21692 } 21693 return i; 21694 } 21695} 21696function Dd(n, e, t) { 21697 const i = n.createShader(e); 21698 return n.shaderSource(i, t), n.compileShader(i), i; 21699} 21700const tS = 37297; 21701let nS = 0; 21702function iS(n, e) { 21703 const t = n.split(` 21704`), i = [], r = Math.max(e - 6, 0), s = Math.min(e + 6, t.length); 21705 for (let a = r; a < s; a++) { 21706 const l = a + 1; 21707 i.push(`${l === e ? ">" : " "} ${l}: ${t[a]}`); 21708 } 21709 return i.join(` 21710`); 21711} 21712const Ud = /* @__PURE__ */ new ot(); 21713function rS(n) { 21714 _t._getMatrix(Ud, _t.workingColorSpace, n); 21715 const e = `mat3( ${Ud.elements.map((t) => t.toFixed(4))} )`; 21716 switch (_t.getTransfer(n)) { 21717 case Lo: 21718 return [e, "LinearTransferOETF"]; 21719 case Nt: 21720 return [e, "sRGBTransferOETF"]; 21721 default: 21722 return tt("WebGLProgram: Unsupported color space: ", n), [e, "LinearTransferOETF"]; 21723 } 21724} 21725function Od(n, e, t) { 21726 const i = n.getShaderParameter(e, n.COMPILE_STATUS), s = (n.getShaderInfoLog(e) || "").trim(); 21727 if (i && s === "") return ""; 21728 const a = /ERROR: 0:(\d+)/.exec(s); 21729 if (a) { 21730 const l = parseInt(a[1]); 21731 return t.toUpperCase() + ` 21732 21733` + s + ` 21734 21735` + iS(n.getShaderSource(e), l); 21736 } else 21737 return s; 21738} 21739function sS(n, e) { 21740 const t = rS(e); 21741 return [ 21742 `vec4 ${n}( vec4 value ) {`, 21743 ` return ${t[1]}( vec4( value.rgb * ${t[0]}, value.a ) );`, 21744 "}" 21745 ].join(` 21746`); 21747} 21748const aS = { 21749 [bp]: "Linear", 21750 [wp]: "Reinhard", 21751 [Sp]: "Cineon", 21752 [Ep]: "ACESFilmic", 21753 [Tp]: "AgX", 21754 [Ap]: "Neutral", 21755 [Mp]: "Custom" 21756}; 21757function oS(n, e) { 21758 const t = aS[e]; 21759 return t === void 0 ? (tt("WebGLProgram: Unsupported toneMapping:", e), "vec3 " + n + "( vec3 color ) { return LinearToneMapping( color ); }") : "vec3 " + n + "( vec3 color ) { return " + t + "ToneMapping( color ); }"; 21760} 21761const no = /* @__PURE__ */ new W(); 21762function lS() { 21763 _t.getLuminanceCoefficients(no); 21764 const n = no.x.toFixed(4), e = no.y.toFixed(4), t = no.z.toFixed(4); 21765 return [ 21766 "float luminance( const in vec3 rgb ) {", 21767 ` const vec3 weights = vec3( ${n}, ${e}, ${t} );`, 21768 " return dot( weights, rgb );", 21769 "}" 21770 ].join(` 21771`); 21772} 21773function cS(n) { 21774 return [ 21775 n.extensionClipCullDistance ? "#extension GL_ANGLE_clip_cull_distance : require" : "", 21776 n.extensionMultiDraw ? "#extension GL_ANGLE_multi_draw : require" : "" 21777 ].filter(Xs).join(` 21778`); 21779} 21780function uS(n) { 21781 const e = []; 21782 for (const t in n) { 21783 const i = n[t]; 21784 i !== !1 && e.push("#define " + t + " " + i); 21785 } 21786 return e.join(` 21787`); 21788} 21789function hS(n, e) { 21790 const t = {}, i = n.getProgramParameter(e, n.ACTIVE_ATTRIBUTES); 21791 for (let r = 0; r < i; r++) { 21792 const s = n.getActiveAttrib(e, r), a = s.name; 21793 let l = 1; 21794 s.type === n.FLOAT_MAT2 && (l = 2), s.type === n.FLOAT_MAT3 && (l = 3), s.type === n.FLOAT_MAT4 && (l = 4), t[a] = { 21795 type: s.type, 21796 location: n.getAttribLocation(e, a), 21797 locationSize: l 21798 }; 21799 } 21800 return t; 21801} 21802function Xs(n) { 21803 return n !== ""; 21804} 21805function kd(n, e) { 21806 const t = e.numSpotLightShadows + e.numSpotLightMaps - e.numSpotLightShadowsWithMaps; 21807 return n.replace(/NUM_DIR_LIGHTS/g, e.numDirLights).replace(/NUM_SPOT_LIGHTS/g, e.numSpotLights).replace(/NUM_SPOT_LIGHT_MAPS/g, e.numSpotLightMaps).replace(/NUM_SPOT_LIGHT_COORDS/g, t).replace(/NUM_RECT_AREA_LIGHTS/g, e.numRectAreaLights).replace(/NUM_POINT_LIGHTS/g, e.numPointLights).replace(/NUM_HEMI_LIGHTS/g, e.numHemiLights).replace(/NUM_DIR_LIGHT_SHADOWS/g, e.numDirLightShadows).replace(/NUM_SPOT_LIGHT_SHADOWS_WITH_MAPS/g, e.numSpotLightShadowsWithMaps).replace(/NUM_SPOT_LIGHT_SHADOWS/g, e.numSpotLightShadows).replace(/NUM_POINT_LIGHT_SHADOWS/g, e.numPointLightShadows); 21808} 21809function Fd(n, e) { 21810 return n.replace(/NUM_CLIPPING_PLANES/g, e.numClippingPlanes).replace(/UNION_CLIPPING_PLANES/g, e.numClippingPlanes - e.numClipIntersection); 21811} 21812const dS = /^[ \t]*#include +<([\w\d./]+)>/gm; 21813function tu(n) { 21814 return n.replace(dS, pS); 21815} 21816const fS = /* @__PURE__ */ new Map(); 21817function pS(n, e) { 21818 let t = ct[e]; 21819 if (t === void 0) { 21820 const i = fS.get(e); 21821 if (i !== void 0) 21822 t = ct[i], tt('WebGLRenderer: Shader chunk "%s" has been deprecated. Use "%s" instead.', e, i); 21823 else 21824 throw new Error("Can not resolve #include <" + e + ">"); 21825 } 21826 return tu(t); 21827} 21828const mS = /#pragma unroll_loop_start\s+for\s*\(\s*int\s+i\s*=\s*(\d+)\s*;\s*i\s*<\s*(\d+)\s*;\s*i\s*\+\+\s*\)\s*{([\s\S]+?)}\s+#pragma unroll_loop_end/g; 21829function Bd(n) { 21830 return n.replace(mS, gS); 21831} 21832function gS(n, e, t, i) { 21833 let r = ""; 21834 for (let s = parseInt(e); s < parseInt(t); s++) 21835 r += i.replace(/\[\s*i\s*\]/g, "[ " + s + " ]").replace(/UNROLLED_LOOP_INDEX/g, s); 21836 return r; 21837} 21838function zd(n) { 21839 let e = `precision ${n.precision} float; 21840 precision ${n.precision} int; 21841 precision ${n.precision} sampler2D; 21842 precision ${n.precision} samplerCube; 21843 precision ${n.precision} sampler3D; 21844 precision ${n.precision} sampler2DArray; 21845 precision ${n.precision} sampler2DShadow; 21846 precision ${n.precision} samplerCubeShadow; 21847 precision ${n.precision} sampler2DArrayShadow; 21848 precision ${n.precision} isampler2D; 21849 precision ${n.precision} isampler3D; 21850 precision ${n.precision} isamplerCube; 21851 precision ${n.precision} isampler2DArray; 21852 precision ${n.precision} usampler2D; 21853 precision ${n.precision} usampler3D; 21854 precision ${n.precision} usamplerCube; 21855 precision ${n.precision} usampler2DArray; 21856 `; 21857 return n.precision === "highp" ? e += ` 21858#define HIGH_PRECISION` : n.precision === "mediump" ? e += ` 21859#define MEDIUM_PRECISION` : n.precision === "lowp" && (e += ` 21860#define LOW_PRECISION`), e; 21861} 21862const vS = { 21863 [_o]: "SHADOWMAP_TYPE_PCF", 21864 [js]: "SHADOWMAP_TYPE_VSM" 21865}; 21866function _S(n) { 21867 return vS[n.shadowMapType] || "SHADOWMAP_TYPE_BASIC"; 21868} 21869const yS = { 21870 [Cr]: "ENVMAP_TYPE_CUBE", 21871 [gs]: "ENVMAP_TYPE_CUBE", 21872 [$o]: "ENVMAP_TYPE_CUBE_UV" 21873}; 21874function xS(n) { 21875 return n.envMap === !1 ? "ENVMAP_TYPE_CUBE" : yS[n.envMapMode] || "ENVMAP_TYPE_CUBE"; 21876} 21877const bS = { 21878 [gs]: "ENVMAP_MODE_REFRACTION" 21879}; 21880function wS(n) { 21881 return n.envMap === !1 ? "ENVMAP_MODE_REFLECTION" : bS[n.envMapMode] || "ENVMAP_MODE_REFLECTION"; 21882} 21883const SS = { 21884 [Nu]: "ENVMAP_BLENDING_MULTIPLY", 21885 [h_]: "ENVMAP_BLENDING_MIX", 21886 [d_]: "ENVMAP_BLENDING_ADD" 21887}; 21888function ES(n) { 21889 return n.envMap === !1 ? "ENVMAP_BLENDING_NONE" : SS[n.combine] || "ENVMAP_BLENDING_NONE"; 21890} 21891function MS(n) { 21892 const e = n.envMapCubeUVHeight; 21893 if (e === null) return null; 21894 const t = Math.log2(e) - 2, i = 1 / e; 21895 return { texelWidth: 1 / (3 * Math.max(Math.pow(2, t), 112)), texelHeight: i, maxMip: t }; 21896} 21897function TS(n, e, t, i) { 21898 const r = n.getContext(), s = t.defines; 21899 let a = t.vertexShader, l = t.fragmentShader; 21900 const o = _S(t), c = xS(t), u = wS(t), h = ES(t), d = MS(t), f = cS(t), p = uS(s), v = r.createProgram(); 21901 let m, g, _ = t.glslVersion ? "#version " + t.glslVersion + ` 21902` : ""; 21903 t.isRawShaderMaterial ? (m = [ 21904 "#define SHADER_TYPE " + t.shaderType, 21905 "#define SHADER_NAME " + t.shaderName, 21906 p 21907 ].filter(Xs).join(` 21908`), m.length > 0 && (m += ` 21909`), g = [ 21910 "#define SHADER_TYPE " + t.shaderType, 21911 "#define SHADER_NAME " + t.shaderName, 21912 p 21913 ].filter(Xs).join(` 21914`), g.length > 0 && (g += ` 21915`)) : (m = [ 21916 zd(t), 21917 "#define SHADER_TYPE " + t.shaderType, 21918 "#define SHADER_NAME " + t.shaderName, 21919 p,
vendor: 12,048 bytes, lines 21920-22162
21920 t.extensionClipCullDistance ? "#define USE_CLIP_DISTANCE" : "", 21921 t.batching ? "#define USE_BATCHING" : "", 21922 t.batchingColor ? "#define USE_BATCHING_COLOR" : "", 21923 t.instancing ? "#define USE_INSTANCING" : "", 21924 t.instancingColor ? "#define USE_INSTANCING_COLOR" : "", 21925 t.instancingMorph ? "#define USE_INSTANCING_MORPH" : "", 21926 t.useFog && t.fog ? "#define USE_FOG" : "", 21927 t.useFog && t.fogExp2 ? "#define FOG_EXP2" : "", 21928 t.map ? "#define USE_MAP" : "", 21929 t.envMap ? "#define USE_ENVMAP" : "", 21930 t.envMap ? "#define " + u : "", 21931 t.lightMap ? "#define USE_LIGHTMAP" : "", 21932 t.aoMap ? "#define USE_AOMAP" : "", 21933 t.bumpMap ? "#define USE_BUMPMAP" : "", 21934 t.normalMap ? "#define USE_NORMALMAP" : "", 21935 t.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", 21936 t.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", 21937 t.displacementMap ? "#define USE_DISPLACEMENTMAP" : "", 21938 t.emissiveMap ? "#define USE_EMISSIVEMAP" : "", 21939 t.anisotropy ? "#define USE_ANISOTROPY" : "", 21940 t.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", 21941 t.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", 21942 t.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", 21943 t.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", 21944 t.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", 21945 t.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", 21946 t.specularMap ? "#define USE_SPECULARMAP" : "", 21947 t.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", 21948 t.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", 21949 t.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", 21950 t.metalnessMap ? "#define USE_METALNESSMAP" : "", 21951 t.alphaMap ? "#define USE_ALPHAMAP" : "", 21952 t.alphaHash ? "#define USE_ALPHAHASH" : "", 21953 t.transmission ? "#define USE_TRANSMISSION" : "", 21954 t.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", 21955 t.thicknessMap ? "#define USE_THICKNESSMAP" : "", 21956 t.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", 21957 t.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", 21958 // 21959 t.mapUv ? "#define MAP_UV " + t.mapUv : "", 21960 t.alphaMapUv ? "#define ALPHAMAP_UV " + t.alphaMapUv : "", 21961 t.lightMapUv ? "#define LIGHTMAP_UV " + t.lightMapUv : "", 21962 t.aoMapUv ? "#define AOMAP_UV " + t.aoMapUv : "", 21963 t.emissiveMapUv ? "#define EMISSIVEMAP_UV " + t.emissiveMapUv : "", 21964 t.bumpMapUv ? "#define BUMPMAP_UV " + t.bumpMapUv : "", 21965 t.normalMapUv ? "#define NORMALMAP_UV " + t.normalMapUv : "", 21966 t.displacementMapUv ? "#define DISPLACEMENTMAP_UV " + t.displacementMapUv : "", 21967 t.metalnessMapUv ? "#define METALNESSMAP_UV " + t.metalnessMapUv : "", 21968 t.roughnessMapUv ? "#define ROUGHNESSMAP_UV " + t.roughnessMapUv : "", 21969 t.anisotropyMapUv ? "#define ANISOTROPYMAP_UV " + t.anisotropyMapUv : "", 21970 t.clearcoatMapUv ? "#define CLEARCOATMAP_UV " + t.clearcoatMapUv : "", 21971 t.clearcoatNormalMapUv ? "#define CLEARCOAT_NORMALMAP_UV " + t.clearcoatNormalMapUv : "", 21972 t.clearcoatRoughnessMapUv ? "#define CLEARCOAT_ROUGHNESSMAP_UV " + t.clearcoatRoughnessMapUv : "", 21973 t.iridescenceMapUv ? "#define IRIDESCENCEMAP_UV " + t.iridescenceMapUv : "", 21974 t.iridescenceThicknessMapUv ? "#define IRIDESCENCE_THICKNESSMAP_UV " + t.iridescenceThicknessMapUv : "", 21975 t.sheenColorMapUv ? "#define SHEEN_COLORMAP_UV " + t.sheenColorMapUv : "", 21976 t.sheenRoughnessMapUv ? "#define SHEEN_ROUGHNESSMAP_UV " + t.sheenRoughnessMapUv : "", 21977 t.specularMapUv ? "#define SPECULARMAP_UV " + t.specularMapUv : "", 21978 t.specularColorMapUv ? "#define SPECULAR_COLORMAP_UV " + t.specularColorMapUv : "", 21979 t.specularIntensityMapUv ? "#define SPECULAR_INTENSITYMAP_UV " + t.specularIntensityMapUv : "", 21980 t.transmissionMapUv ? "#define TRANSMISSIONMAP_UV " + t.transmissionMapUv : "", 21981 t.thicknessMapUv ? "#define THICKNESSMAP_UV " + t.thicknessMapUv : "", 21982 // 21983 t.vertexTangents && t.flatShading === !1 ? "#define USE_TANGENT" : "", 21984 t.vertexNormals ? "#define HAS_NORMAL" : "", 21985 t.vertexColors ? "#define USE_COLOR" : "", 21986 t.vertexAlphas ? "#define USE_COLOR_ALPHA" : "", 21987 t.vertexUv1s ? "#define USE_UV1" : "", 21988 t.vertexUv2s ? "#define USE_UV2" : "", 21989 t.vertexUv3s ? "#define USE_UV3" : "", 21990 t.pointsUvs ? "#define USE_POINTS_UV" : "", 21991 t.flatShading ? "#define FLAT_SHADED" : "", 21992 t.skinning ? "#define USE_SKINNING" : "", 21993 t.morphTargets ? "#define USE_MORPHTARGETS" : "", 21994 t.morphNormals && t.flatShading === !1 ? "#define USE_MORPHNORMALS" : "", 21995 t.morphColors ? "#define USE_MORPHCOLORS" : "", 21996 t.morphTargetsCount > 0 ? "#define MORPHTARGETS_TEXTURE_STRIDE " + t.morphTextureStride : "", 21997 t.morphTargetsCount > 0 ? "#define MORPHTARGETS_COUNT " + t.morphTargetsCount : "", 21998 t.doubleSided ? "#define DOUBLE_SIDED" : "", 21999 t.flipSided ? "#define FLIP_SIDED" : "", 22000 t.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", 22001 t.shadowMapEnabled ? "#define " + o : "", 22002 t.sizeAttenuation ? "#define USE_SIZEATTENUATION" : "", 22003 t.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", 22004 t.logarithmicDepthBuffer ? "#define USE_LOGARITHMIC_DEPTH_BUFFER" : "", 22005 t.reversedDepthBuffer ? "#define USE_REVERSED_DEPTH_BUFFER" : "", 22006 "uniform mat4 modelMatrix;", 22007 "uniform mat4 modelViewMatrix;", 22008 "uniform mat4 projectionMatrix;", 22009 "uniform mat4 viewMatrix;", 22010 "uniform mat3 normalMatrix;", 22011 "uniform vec3 cameraPosition;", 22012 "uniform bool isOrthographic;", 22013 "#ifdef USE_INSTANCING", 22014 " attribute mat4 instanceMatrix;", 22015 "#endif", 22016 "#ifdef USE_INSTANCING_COLOR", 22017 " attribute vec3 instanceColor;", 22018 "#endif", 22019 "#ifdef USE_INSTANCING_MORPH", 22020 " uniform sampler2D morphTexture;", 22021 "#endif", 22022 "attribute vec3 position;", 22023 "attribute vec3 normal;", 22024 "attribute vec2 uv;", 22025 "#ifdef USE_UV1", 22026 " attribute vec2 uv1;", 22027 "#endif", 22028 "#ifdef USE_UV2", 22029 " attribute vec2 uv2;", 22030 "#endif", 22031 "#ifdef USE_UV3", 22032 " attribute vec2 uv3;", 22033 "#endif", 22034 "#ifdef USE_TANGENT", 22035 " attribute vec4 tangent;", 22036 "#endif", 22037 "#if defined( USE_COLOR_ALPHA )", 22038 " attribute vec4 color;", 22039 "#elif defined( USE_COLOR )", 22040 " attribute vec3 color;", 22041 "#endif", 22042 "#ifdef USE_SKINNING", 22043 " attribute vec4 skinIndex;", 22044 " attribute vec4 skinWeight;", 22045 "#endif", 22046 ` 22047` 22048 ].filter(Xs).join(` 22049`), g = [ 22050 zd(t), 22051 "#define SHADER_TYPE " + t.shaderType, 22052 "#define SHADER_NAME " + t.shaderName, 22053 p, 22054 t.useFog && t.fog ? "#define USE_FOG" : "", 22055 t.useFog && t.fogExp2 ? "#define FOG_EXP2" : "", 22056 t.alphaToCoverage ? "#define ALPHA_TO_COVERAGE" : "", 22057 t.map ? "#define USE_MAP" : "", 22058 t.matcap ? "#define USE_MATCAP" : "", 22059 t.envMap ? "#define USE_ENVMAP" : "", 22060 t.envMap ? "#define " + c : "", 22061 t.envMap ? "#define " + u : "", 22062 t.envMap ? "#define " + h : "", 22063 d ? "#define CUBEUV_TEXEL_WIDTH " + d.texelWidth : "", 22064 d ? "#define CUBEUV_TEXEL_HEIGHT " + d.texelHeight : "", 22065 d ? "#define CUBEUV_MAX_MIP " + d.maxMip + ".0" : "", 22066 t.lightMap ? "#define USE_LIGHTMAP" : "", 22067 t.aoMap ? "#define USE_AOMAP" : "", 22068 t.bumpMap ? "#define USE_BUMPMAP" : "", 22069 t.normalMap ? "#define USE_NORMALMAP" : "", 22070 t.normalMapObjectSpace ? "#define USE_NORMALMAP_OBJECTSPACE" : "", 22071 t.normalMapTangentSpace ? "#define USE_NORMALMAP_TANGENTSPACE" : "", 22072 t.packedNormalMap ? "#define USE_PACKED_NORMALMAP" : "", 22073 t.emissiveMap ? "#define USE_EMISSIVEMAP" : "", 22074 t.anisotropy ? "#define USE_ANISOTROPY" : "", 22075 t.anisotropyMap ? "#define USE_ANISOTROPYMAP" : "", 22076 t.clearcoat ? "#define USE_CLEARCOAT" : "", 22077 t.clearcoatMap ? "#define USE_CLEARCOATMAP" : "", 22078 t.clearcoatRoughnessMap ? "#define USE_CLEARCOAT_ROUGHNESSMAP" : "", 22079 t.clearcoatNormalMap ? "#define USE_CLEARCOAT_NORMALMAP" : "", 22080 t.dispersion ? "#define USE_DISPERSION" : "", 22081 t.iridescence ? "#define USE_IRIDESCENCE" : "", 22082 t.iridescenceMap ? "#define USE_IRIDESCENCEMAP" : "", 22083 t.iridescenceThicknessMap ? "#define USE_IRIDESCENCE_THICKNESSMAP" : "", 22084 t.specularMap ? "#define USE_SPECULARMAP" : "", 22085 t.specularColorMap ? "#define USE_SPECULAR_COLORMAP" : "", 22086 t.specularIntensityMap ? "#define USE_SPECULAR_INTENSITYMAP" : "", 22087 t.roughnessMap ? "#define USE_ROUGHNESSMAP" : "", 22088 t.metalnessMap ? "#define USE_METALNESSMAP" : "", 22089 t.alphaMap ? "#define USE_ALPHAMAP" : "", 22090 t.alphaTest ? "#define USE_ALPHATEST" : "", 22091 t.alphaHash ? "#define USE_ALPHAHASH" : "", 22092 t.sheen ? "#define USE_SHEEN" : "", 22093 t.sheenColorMap ? "#define USE_SHEEN_COLORMAP" : "", 22094 t.sheenRoughnessMap ? "#define USE_SHEEN_ROUGHNESSMAP" : "", 22095 t.transmission ? "#define USE_TRANSMISSION" : "", 22096 t.transmissionMap ? "#define USE_TRANSMISSIONMAP" : "", 22097 t.thicknessMap ? "#define USE_THICKNESSMAP" : "", 22098 t.vertexTangents && t.flatShading === !1 ? "#define USE_TANGENT" : "", 22099 t.vertexColors || t.instancingColor ? "#define USE_COLOR" : "", 22100 t.vertexAlphas || t.batchingColor ? "#define USE_COLOR_ALPHA" : "", 22101 t.vertexUv1s ? "#define USE_UV1" : "", 22102 t.vertexUv2s ? "#define USE_UV2" : "", 22103 t.vertexUv3s ? "#define USE_UV3" : "", 22104 t.pointsUvs ? "#define USE_POINTS_UV" : "", 22105 t.gradientMap ? "#define USE_GRADIENTMAP" : "", 22106 t.flatShading ? "#define FLAT_SHADED" : "", 22107 t.doubleSided ? "#define DOUBLE_SIDED" : "", 22108 t.flipSided ? "#define FLIP_SIDED" : "", 22109 t.shadowMapEnabled ? "#define USE_SHADOWMAP" : "", 22110 t.shadowMapEnabled ? "#define " + o : "", 22111 t.premultipliedAlpha ? "#define PREMULTIPLIED_ALPHA" : "", 22112 t.numLightProbes > 0 ? "#define USE_LIGHT_PROBES" : "", 22113 t.numLightProbeGrids > 0 ? "#define USE_LIGHT_PROBES_GRID" : "", 22114 t.decodeVideoTexture ? "#define DECODE_VIDEO_TEXTURE" : "", 22115 t.decodeVideoTextureEmissive ? "#define DECODE_VIDEO_TEXTURE_EMISSIVE" : "", 22116 t.logarithmicDepthBuffer ? "#define USE_LOGARITHMIC_DEPTH_BUFFER" : "", 22117 t.reversedDepthBuffer ? "#define USE_REVERSED_DEPTH_BUFFER" : "", 22118 "uniform mat4 viewMatrix;", 22119 "uniform vec3 cameraPosition;", 22120 "uniform bool isOrthographic;", 22121 t.toneMapping !== di ? "#define TONE_MAPPING" : "", 22122 t.toneMapping !== di ? ct.tonemapping_pars_fragment : "", 22123 // this code is required here because it is used by the toneMapping() function defined below 22124 t.toneMapping !== di ? oS("toneMapping", t.toneMapping) : "", 22125 t.dithering ? "#define DITHERING" : "", 22126 t.opaque ? "#define OPAQUE" : "", 22127 ct.colorspace_pars_fragment, 22128 // this code is required here because it is used by the various encoding/decoding function defined below 22129 sS("linearToOutputTexel", t.outputColorSpace), 22130 lS(), 22131 t.useDepthPacking ? "#define DEPTH_PACKING " + t.depthPacking : "", 22132 ` 22133` 22134 ].filter(Xs).join(` 22135`)), a = tu(a), a = kd(a, t), a = Fd(a, t), l = tu(l), l = kd(l, t), l = Fd(l, t), a = Bd(a), l = Bd(l), t.isRawShaderMaterial !== !0 && (_ = `#version 300 es 22136`, m = [ 22137 f, 22138 "#define attribute in", 22139 "#define varying out", 22140 "#define texture2D texture" 22141 ].join(` 22142`) + ` 22143` + m, g = [ 22144 "#define varying in", 22145 t.glslVersion === $h ? "" : "layout(location = 0) out highp vec4 pc_fragColor;", 22146 t.glslVersion === $h ? "" : "#define gl_FragColor pc_fragColor", 22147 "#define gl_FragDepthEXT gl_FragDepth", 22148 "#define texture2D texture", 22149 "#define textureCube texture", 22150 "#define texture2DProj textureProj", 22151 "#define texture2DLodEXT textureLod", 22152 "#define texture2DProjLodEXT textureProjLod", 22153 "#define textureCubeLodEXT textureLod", 22154 "#define texture2DGradEXT textureGrad", 22155 "#define texture2DProjGradEXT textureProjGrad", 22156 "#define textureCubeGradEXT textureGrad" 22157 ].join(` 22158`) + ` 22159` + g); 22160 const x = _ + m + a, E = _ + g + l, R = Dd(r, r.VERTEX_SHADER, x), T = Dd(r, r.FRAGMENT_SHADER, E); 22161 r.attachShader(v, R), r.attachShader(v, T), t.index0AttributeName !== void 0 ? r.bindAttribLocation(v, 0, t.index0AttributeName) : t.morphTargets === !0 && r.bindAttribLocation(v, 0, "position"), r.linkProgram(v); 22162 function w(C) {
vendor: 16,909 bytes, lines 22163-22508
22163 if (n.debug.checkShaderErrors) { 22164 const U = r.getProgramInfoLog(v) || "", V = r.getShaderInfoLog(R) || "", F = r.getShaderInfoLog(T) || "", I = U.trim(), k = V.trim(), H = F.trim(); 22165 let X = !0, K = !0; 22166 if (r.getProgramParameter(v, r.LINK_STATUS) === !1) 22167 if (X = !1, typeof n.debug.onShaderError == "function") 22168 n.debug.onShaderError(r, v, R, T); 22169 else { 22170 const ae = Od(r, R, "vertex"), se = Od(r, T, "fragment"); 22171 xt( 22172 "THREE.WebGLProgram: Shader Error " + r.getError() + " - VALIDATE_STATUS " + r.getProgramParameter(v, r.VALIDATE_STATUS) + ` 22173 22174Material Name: ` + C.name + ` 22175Material Type: ` + C.type + ` 22176 22177Program Info Log: ` + I + ` 22178` + ae + ` 22179` + se 22180 ); 22181 } 22182 else I !== "" ? tt("WebGLProgram: Program Info Log:", I) : (k === "" || H === "") && (K = !1); 22183 K && (C.diagnostics = { 22184 runnable: X, 22185 programLog: I, 22186 vertexShader: { 22187 log: k, 22188 prefix: m 22189 }, 22190 fragmentShader: { 22191 log: H, 22192 prefix: g 22193 } 22194 }); 22195 } 22196 r.deleteShader(R), r.deleteShader(T), y = new So(r, v), M = hS(r, v); 22197 } 22198 let y; 22199 this.getUniforms = function() { 22200 return y === void 0 && w(this), y; 22201 }; 22202 let M; 22203 this.getAttributes = function() { 22204 return M === void 0 && w(this), M; 22205 }; 22206 let L = t.rendererExtensionParallelShaderCompile === !1; 22207 return this.isReady = function() { 22208 return L === !1 && (L = r.getProgramParameter(v, tS)), L; 22209 }, this.destroy = function() { 22210 i.releaseStatesOfProgram(this), r.deleteProgram(v), this.program = void 0; 22211 }, this.type = t.shaderType, this.name = t.shaderName, this.id = nS++, this.cacheKey = e, this.usedTimes = 1, this.program = v, this.vertexShader = R, this.fragmentShader = T, this; 22212} 22213let AS = 0; 22214class RS { 22215 constructor() { 22216 this.shaderCache = /* @__PURE__ */ new Map(), this.materialCache = /* @__PURE__ */ new Map(); 22217 } 22218 update(e) { 22219 const t = e.vertexShader, i = e.fragmentShader, r = this._getShaderStage(t), s = this._getShaderStage(i), a = this._getShaderCacheForMaterial(e); 22220 return a.has(r) === !1 && (a.add(r), r.usedTimes++), a.has(s) === !1 && (a.add(s), s.usedTimes++), this; 22221 } 22222 remove(e) { 22223 const t = this.materialCache.get(e); 22224 for (const i of t) 22225 i.usedTimes--, i.usedTimes === 0 && this.shaderCache.delete(i.code); 22226 return this.materialCache.delete(e), this; 22227 } 22228 getVertexShaderID(e) { 22229 return this._getShaderStage(e.vertexShader).id; 22230 } 22231 getFragmentShaderID(e) { 22232 return this._getShaderStage(e.fragmentShader).id; 22233 } 22234 dispose() { 22235 this.shaderCache.clear(), this.materialCache.clear(); 22236 } 22237 _getShaderCacheForMaterial(e) { 22238 const t = this.materialCache; 22239 let i = t.get(e); 22240 return i === void 0 && (i = /* @__PURE__ */ new Set(), t.set(e, i)), i; 22241 } 22242 _getShaderStage(e) { 22243 const t = this.shaderCache; 22244 let i = t.get(e); 22245 return i === void 0 && (i = new CS(e), t.set(e, i)), i; 22246 } 22247} 22248class CS { 22249 constructor(e) { 22250 this.id = AS++, this.code = e, this.usedTimes = 0; 22251 } 22252} 22253function PS(n) { 22254 return n === Pr || n === Ro || n === Co; 22255} 22256function LS(n, e, t, i, r, s) { 22257 const a = new Vu(), l = new RS(), o = /* @__PURE__ */ new Set(), c = [], u = /* @__PURE__ */ new Map(), h = i.logarithmicDepthBuffer; 22258 let d = i.precision; 22259 const f = { 22260 MeshDepthMaterial: "depth", 22261 MeshDistanceMaterial: "distance", 22262 MeshNormalMaterial: "normal", 22263 MeshBasicMaterial: "basic", 22264 MeshLambertMaterial: "lambert", 22265 MeshPhongMaterial: "phong", 22266 MeshToonMaterial: "toon", 22267 MeshStandardMaterial: "physical", 22268 MeshPhysicalMaterial: "physical", 22269 MeshMatcapMaterial: "matcap", 22270 LineBasicMaterial: "basic", 22271 LineDashedMaterial: "dashed", 22272 PointsMaterial: "points", 22273 ShadowMaterial: "shadow", 22274 SpriteMaterial: "sprite" 22275 }; 22276 function p(y) { 22277 return o.add(y), y === 0 ? "uv" : `uv${y}`; 22278 } 22279 function v(y, M, L, C, U, V) { 22280 const F = C.fog, I = U.geometry, k = y.isMeshStandardMaterial || y.isMeshLambertMaterial || y.isMeshPhongMaterial ? C.environment : null, H = y.isMeshStandardMaterial || y.isMeshLambertMaterial && !y.envMap || y.isMeshPhongMaterial && !y.envMap, X = e.get(y.envMap || k, H), K = X && X.mapping === $o ? X.image.height : null, ae = f[y.type]; 22281 y.precision !== null && (d = i.getMaxPrecision(y.precision), d !== y.precision && tt("WebGLProgram.getParameters:", y.precision, "not supported, using", d, "instead.")); 22282 const se = I.morphAttributes.position || I.morphAttributes.normal || I.morphAttributes.color, he = se !== void 0 ? se.length : 0; 22283 let Ce = 0; 22284 I.morphAttributes.position !== void 0 && (Ce = 1), I.morphAttributes.normal !== void 0 && (Ce = 2), I.morphAttributes.color !== void 0 && (Ce = 3); 22285 let Ie, Ee, J, le; 22286 if (ae) { 22287 const it = li[ae]; 22288 Ie = it.vertexShader, Ee = it.fragmentShader; 22289 } else 22290 Ie = y.vertexShader, Ee = y.fragmentShader, l.update(y), J = l.getVertexShaderID(y), le = l.getFragmentShaderID(y); 22291 const te = n.getRenderTarget(), ie = n.state.buffers.depth.getReversed(), fe = U.isInstancedMesh === !0, Se = U.isBatchedMesh === !0, Fe = !!y.map, Me = !!y.matcap, Ke = !!X, at = !!y.aoMap, Ue = !!y.lightMap, lt = !!y.bumpMap, ut = !!y.normalMap, Tt = !!y.displacementMap, D = !!y.emissiveMap, Rt = !!y.metalnessMap, Qe = !!y.roughnessMap, dt = y.anisotropy > 0, pe = y.clearcoat > 0, At = y.dispersion > 0, A = y.iridescence > 0, b = y.sheen > 0, G = y.transmission > 0, Q = dt && !!y.anisotropyMap, oe = pe && !!y.clearcoatMap, me = pe && !!y.clearcoatNormalMap, ve = pe && !!y.clearcoatRoughnessMap, Z = A && !!y.iridescenceMap, ee = A && !!y.iridescenceThicknessMap, Ae = b && !!y.sheenColorMap, De = b && !!y.sheenRoughnessMap, xe = !!y.specularMap, _e = !!y.specularColorMap, et = !!y.specularIntensityMap, nt = G && !!y.transmissionMap, gt = G && !!y.thicknessMap, O = !!y.gradientMap, ye = !!y.alphaMap, ne = y.alphaTest > 0, Ne = !!y.alphaHash, be = !!y.extensions; 22292 let ce = di; 22293 y.toneMapped && (te === null || te.isXRRenderTarget === !0) && (ce = n.toneMapping); 22294 const Ge = { 22295 shaderID: ae, 22296 shaderType: y.type, 22297 shaderName: y.name, 22298 vertexShader: Ie, 22299 fragmentShader: Ee, 22300 defines: y.defines, 22301 customVertexShaderID: J, 22302 customFragmentShaderID: le, 22303 isRawShaderMaterial: y.isRawShaderMaterial === !0, 22304 glslVersion: y.glslVersion, 22305 precision: d, 22306 batching: Se, 22307 batchingColor: Se && U._colorsTexture !== null, 22308 instancing: fe, 22309 instancingColor: fe && U.instanceColor !== null, 22310 instancingMorph: fe && U.morphTexture !== null, 22311 outputColorSpace: te === null ? n.outputColorSpace : te.isXRRenderTarget === !0 ? te.texture.colorSpace : _t.workingColorSpace, 22312 alphaToCoverage: !!y.alphaToCoverage, 22313 map: Fe, 22314 matcap: Me, 22315 envMap: Ke, 22316 envMapMode: Ke && X.mapping, 22317 envMapCubeUVHeight: K, 22318 aoMap: at, 22319 lightMap: Ue, 22320 bumpMap: lt, 22321 normalMap: ut, 22322 displacementMap: Tt, 22323 emissiveMap: D, 22324 normalMapObjectSpace: ut && y.normalMapType === m_, 22325 normalMapTangentSpace: ut && y.normalMapType === Yc, 22326 packedNormalMap: ut && y.normalMapType === Yc && PS(y.normalMap.format), 22327 metalnessMap: Rt, 22328 roughnessMap: Qe, 22329 anisotropy: dt, 22330 anisotropyMap: Q, 22331 clearcoat: pe, 22332 clearcoatMap: oe, 22333 clearcoatNormalMap: me, 22334 clearcoatRoughnessMap: ve, 22335 dispersion: At, 22336 iridescence: A, 22337 iridescenceMap: Z, 22338 iridescenceThicknessMap: ee, 22339 sheen: b, 22340 sheenColorMap: Ae, 22341 sheenRoughnessMap: De, 22342 specularMap: xe, 22343 specularColorMap: _e, 22344 specularIntensityMap: et, 22345 transmission: G, 22346 transmissionMap: nt, 22347 thicknessMap: gt, 22348 gradientMap: O, 22349 opaque: y.transparent === !1 && y.blending === hs && y.alphaToCoverage === !1, 22350 alphaMap: ye, 22351 alphaTest: ne, 22352 alphaHash: Ne, 22353 combine: y.combine, 22354 // 22355 mapUv: Fe && p(y.map.channel), 22356 aoMapUv: at && p(y.aoMap.channel), 22357 lightMapUv: Ue && p(y.lightMap.channel), 22358 bumpMapUv: lt && p(y.bumpMap.channel), 22359 normalMapUv: ut && p(y.normalMap.channel), 22360 displacementMapUv: Tt && p(y.displacementMap.channel), 22361 emissiveMapUv: D && p(y.emissiveMap.channel), 22362 metalnessMapUv: Rt && p(y.metalnessMap.channel), 22363 roughnessMapUv: Qe && p(y.roughnessMap.channel), 22364 anisotropyMapUv: Q && p(y.anisotropyMap.channel), 22365 clearcoatMapUv: oe && p(y.clearcoatMap.channel), 22366 clearcoatNormalMapUv: me && p(y.clearcoatNormalMap.channel), 22367 clearcoatRoughnessMapUv: ve && p(y.clearcoatRoughnessMap.channel), 22368 iridescenceMapUv: Z && p(y.iridescenceMap.channel), 22369 iridescenceThicknessMapUv: ee && p(y.iridescenceThicknessMap.channel), 22370 sheenColorMapUv: Ae && p(y.sheenColorMap.channel), 22371 sheenRoughnessMapUv: De && p(y.sheenRoughnessMap.channel), 22372 specularMapUv: xe && p(y.specularMap.channel), 22373 specularColorMapUv: _e && p(y.specularColorMap.channel), 22374 specularIntensityMapUv: et && p(y.specularIntensityMap.channel), 22375 transmissionMapUv: nt && p(y.transmissionMap.channel), 22376 thicknessMapUv: gt && p(y.thicknessMap.channel), 22377 alphaMapUv: ye && p(y.alphaMap.channel), 22378 // 22379 vertexTangents: !!I.attributes.tangent && (ut || dt), 22380 vertexNormals: !!I.attributes.normal, 22381 vertexColors: y.vertexColors, 22382 vertexAlphas: y.vertexColors === !0 && !!I.attributes.color && I.attributes.color.itemSize === 4, 22383 pointsUvs: U.isPoints === !0 && !!I.attributes.uv && (Fe || ye), 22384 fog: !!F, 22385 useFog: y.fog === !0, 22386 fogExp2: !!F && F.isFogExp2, 22387 flatShading: y.wireframe === !1 && (y.flatShading === !0 || I.attributes.normal === void 0 && ut === !1 && (y.isMeshLambertMaterial || y.isMeshPhongMaterial || y.isMeshStandardMaterial || y.isMeshPhysicalMaterial)), 22388 sizeAttenuation: y.sizeAttenuation === !0, 22389 logarithmicDepthBuffer: h, 22390 reversedDepthBuffer: ie, 22391 skinning: U.isSkinnedMesh === !0, 22392 morphTargets: I.morphAttributes.position !== void 0, 22393 morphNormals: I.morphAttributes.normal !== void 0, 22394 morphColors: I.morphAttributes.color !== void 0, 22395 morphTargetsCount: he, 22396 morphTextureStride: Ce, 22397 numDirLights: M.directional.length, 22398 numPointLights: M.point.length, 22399 numSpotLights: M.spot.length, 22400 numSpotLightMaps: M.spotLightMap.length, 22401 numRectAreaLights: M.rectArea.length, 22402 numHemiLights: M.hemi.length, 22403 numDirLightShadows: M.directionalShadowMap.length, 22404 numPointLightShadows: M.pointShadowMap.length, 22405 numSpotLightShadows: M.spotShadowMap.length, 22406 numSpotLightShadowsWithMaps: M.numSpotLightShadowsWithMaps, 22407 numLightProbes: M.numLightProbes, 22408 numLightProbeGrids: V.length, 22409 numClippingPlanes: s.numPlanes, 22410 numClipIntersection: s.numIntersection, 22411 dithering: y.dithering, 22412 shadowMapEnabled: n.shadowMap.enabled && L.length > 0, 22413 shadowMapType: n.shadowMap.type, 22414 toneMapping: ce, 22415 decodeVideoTexture: Fe && y.map.isVideoTexture === !0 && _t.getTransfer(y.map.colorSpace) === Nt, 22416 decodeVideoTextureEmissive: D && y.emissiveMap.isVideoTexture === !0 && _t.getTransfer(y.emissiveMap.colorSpace) === Nt, 22417 premultipliedAlpha: y.premultipliedAlpha, 22418 doubleSided: y.side === Ni, 22419 flipSided: y.side === Mn, 22420 useDepthPacking: y.depthPacking >= 0, 22421 depthPacking: y.depthPacking || 0, 22422 index0AttributeName: y.index0AttributeName, 22423 extensionClipCullDistance: be && y.extensions.clipCullDistance === !0 && t.has("WEBGL_clip_cull_distance"), 22424 extensionMultiDraw: (be && y.extensions.multiDraw === !0 || Se) && t.has("WEBGL_multi_draw"), 22425 rendererExtensionParallelShaderCompile: t.has("KHR_parallel_shader_compile"), 22426 customProgramCacheKey: y.customProgramCacheKey() 22427 }; 22428 return Ge.vertexUv1s = o.has(1), Ge.vertexUv2s = o.has(2), Ge.vertexUv3s = o.has(3), o.clear(), Ge; 22429 } 22430 function m(y) { 22431 const M = []; 22432 if (y.shaderID ? M.push(y.shaderID) : (M.push(y.customVertexShaderID), M.push(y.customFragmentShaderID)), y.defines !== void 0) 22433 for (const L in y.defines) 22434 M.push(L), M.push(y.defines[L]); 22435 return y.isRawShaderMaterial === !1 && (g(M, y), _(M, y), M.push(n.outputColorSpace)), M.push(y.customProgramCacheKey), M.join(); 22436 } 22437 function g(y, M) { 22438 y.push(M.precision), y.push(M.outputColorSpace), y.push(M.envMapMode), y.push(M.envMapCubeUVHeight), y.push(M.mapUv), y.push(M.alphaMapUv), y.push(M.lightMapUv), y.push(M.aoMapUv), y.push(M.bumpMapUv), y.push(M.normalMapUv), y.push(M.displacementMapUv), y.push(M.emissiveMapUv), y.push(M.metalnessMapUv), y.push(M.roughnessMapUv), y.push(M.anisotropyMapUv), y.push(M.clearcoatMapUv), y.push(M.clearcoatNormalMapUv), y.push(M.clearcoatRoughnessMapUv), y.push(M.iridescenceMapUv), y.push(M.iridescenceThicknessMapUv), y.push(M.sheenColorMapUv), y.push(M.sheenRoughnessMapUv), y.push(M.specularMapUv), y.push(M.specularColorMapUv), y.push(M.specularIntensityMapUv), y.push(M.transmissionMapUv), y.push(M.thicknessMapUv), y.push(M.combine), y.push(M.fogExp2), y.push(M.sizeAttenuation), y.push(M.morphTargetsCount), y.push(M.morphAttributeCount), y.push(M.numDirLights), y.push(M.numPointLights), y.push(M.numSpotLights), y.push(M.numSpotLightMaps), y.push(M.numHemiLights), y.push(M.numRectAreaLights), y.push(M.numDirLightShadows), y.push(M.numPointLightShadows), y.push(M.numSpotLightShadows), y.push(M.numSpotLightShadowsWithMaps), y.push(M.numLightProbes), y.push(M.shadowMapType), y.push(M.toneMapping), y.push(M.numClippingPlanes), y.push(M.numClipIntersection), y.push(M.depthPacking); 22439 } 22440 function _(y, M) { 22441 a.disableAll(), M.instancing && a.enable(0), M.instancingColor && a.enable(1), M.instancingMorph && a.enable(2), M.matcap && a.enable(3), M.envMap && a.enable(4), M.normalMapObjectSpace && a.enable(5), M.normalMapTangentSpace && a.enable(6), M.clearcoat && a.enable(7), M.iridescence && a.enable(8), M.alphaTest && a.enable(9), M.vertexColors && a.enable(10), M.vertexAlphas && a.enable(11), M.vertexUv1s && a.enable(12), M.vertexUv2s && a.enable(13), M.vertexUv3s && a.enable(14), M.vertexTangents && a.enable(15), M.anisotropy && a.enable(16), M.alphaHash && a.enable(17), M.batching && a.enable(18), M.dispersion && a.enable(19), M.batchingColor && a.enable(20), M.gradientMap && a.enable(21), M.packedNormalMap && a.enable(22), M.vertexNormals && a.enable(23), y.push(a.mask), a.disableAll(), M.fog && a.enable(0), M.useFog && a.enable(1), M.flatShading && a.enable(2), M.logarithmicDepthBuffer && a.enable(3), M.reversedDepthBuffer && a.enable(4), M.skinning && a.enable(5), M.morphTargets && a.enable(6), M.morphNormals && a.enable(7), M.morphColors && a.enable(8), M.premultipliedAlpha && a.enable(9), M.shadowMapEnabled && a.enable(10), M.doubleSided && a.enable(11), M.flipSided && a.enable(12), M.useDepthPacking && a.enable(13), M.dithering && a.enable(14), M.transmission && a.enable(15), M.sheen && a.enable(16), M.opaque && a.enable(17), M.pointsUvs && a.enable(18), M.decodeVideoTexture && a.enable(19), M.decodeVideoTextureEmissive && a.enable(20), M.alphaToCoverage && a.enable(21), M.numLightProbeGrids > 0 && a.enable(22), y.push(a.mask); 22442 } 22443 function x(y) { 22444 const M = f[y.type]; 22445 let L; 22446 if (M) { 22447 const C = li[M]; 22448 L = Q_.clone(C.uniforms); 22449 } else 22450 L = y.uniforms; 22451 return L; 22452 } 22453 function E(y, M) { 22454 let L = u.get(M); 22455 return L !== void 0 ? ++L.usedTimes : (L = new TS(n, M, y, r), c.push(L), u.set(M, L)), L; 22456 } 22457 function R(y) { 22458 if (--y.usedTimes === 0) { 22459 const M = c.indexOf(y); 22460 c[M] = c[c.length - 1], c.pop(), u.delete(y.cacheKey), y.destroy(); 22461 } 22462 } 22463 function T(y) { 22464 l.remove(y); 22465 } 22466 function w() { 22467 l.dispose(); 22468 } 22469 return { 22470 getParameters: v, 22471 getProgramCacheKey: m, 22472 getUniforms: x, 22473 acquireProgram: E, 22474 releaseProgram: R, 22475 releaseShaderCache: T, 22476 // Exposed for resource monitoring & error feedback via renderer.info: 22477 programs: c, 22478 dispose: w 22479 }; 22480} 22481function NS() { 22482 let n = /* @__PURE__ */ new WeakMap(); 22483 function e(a) { 22484 return n.has(a); 22485 } 22486 function t(a) { 22487 let l = n.get(a); 22488 return l === void 0 && (l = {}, n.set(a, l)), l; 22489 } 22490 function i(a) { 22491 n.delete(a); 22492 } 22493 function r(a, l, o) { 22494 n.get(a)[l] = o; 22495 } 22496 function s() { 22497 n = /* @__PURE__ */ new WeakMap(); 22498 } 22499 return { 22500 has: e, 22501 get: t, 22502 remove: i, 22503 update: r, 22504 dispose: s 22505 }; 22506} 22507function IS(n, e) { 22508 return n.groupOrder !== e.groupOrder ? n.groupOrder - e.groupOrder : n.renderOrder !== e.renderOrder ? n.renderOrder - e.renderOrder : n.material.id !== e.material.id ? n.material.id - e.material.id : n.materialVariant !== e.materialVariant ? n.materialVariant - e.materialVariant : n.z !== e.z ? n.z - e.z : n.id
22508- e.id; 22509} 22510function Hd(n, e) { 22511 return n.groupOrder !== e.groupOrder ? n.groupOrder - e.groupOrder : n.renderOrder !== e.renderOrder ? n.renderOrder - e.renderOrder : n.z !== e.z ? e.z - n.z : n.id - e.id; 22512} 22513function Gd() { 22514 const n = []; 22515 let e = 0; 22516 const t = [], i = [], r = []; 22517 function s() { 22518 e = 0, t.length = 0, i.length = 0, r.length = 0; 22519 } 22520 function a(d) { 22521 let f = 0; 22522 return d.isInstancedMesh && (f += 2), d.isSkinnedMesh && (f += 1), f; 22523 } 22524 function l(d, f, p, v, m, g) { 22525 let _ = n[e]; 22526 return _ === void 0 ? (_ = { 22527 id: d.id, 22528 object: d, 22529 geometry: f, 22530 material: p, 22531 materialVariant: a(d), 22532 groupOrder: v, 22533 renderOrder: d.renderOrder, 22534 z: m, 22535 group: g 22536 }, n[e] = _) : (_.id = d.id, _.object = d, _.geometry = f, _.material = p, _.materialVariant = a(d), _.groupOrder = v, _.renderOrder = d.renderOrder, _.z = m, _.group = g), e++, _; 22537 } 22538 function o(d, f, p, v, m, g) { 22539 const _ = l(d, f, p, v, m, g); 22540 p.transmission > 0 ? i.push(_) : p.transparent === !0 ? r.push(_)
vendor: 11,061 bytes, lines 22540-22857
22540: t.push(_); 22541 } 22542 function c(d, f, p, v, m, g) { 22543 const _ = l(d, f, p, v, m, g); 22544 p.transmission > 0 ? i.unshift(_) : p.transparent === !0 ? r.unshift(_) : t.unshift(_); 22545 } 22546 function u(d, f) { 22547 t.length > 1 && t.sort(d || IS), i.length > 1 && i.sort(f || Hd), r.length > 1 && r.sort(f || Hd); 22548 } 22549 function h() { 22550 for (let d = e, f = n.length; d < f; d++) { 22551 const p = n[d]; 22552 if (p.id === null) break; 22553 p.id = null, p.object = null, p.geometry = null, p.material = null, p.group = null; 22554 } 22555 } 22556 return { 22557 opaque: t, 22558 transmissive: i, 22559 transparent: r, 22560 init: s, 22561 push: o, 22562 unshift: c, 22563 finish: h, 22564 sort: u 22565 }; 22566} 22567function DS() { 22568 let n = /* @__PURE__ */ new WeakMap(); 22569 function e(i, r) { 22570 const s = n.get(i); 22571 let a; 22572 return s === void 0 ? (a = new Gd(), n.set(i, [a])) : r >= s.length ? (a = new Gd(), s.push(a)) : a = s[r], a; 22573 } 22574 function t() { 22575 n = /* @__PURE__ */ new WeakMap(); 22576 } 22577 return { 22578 get: e, 22579 dispose: t 22580 }; 22581} 22582function US() { 22583 const n = {}; 22584 return { 22585 get: function(e) { 22586 if (n[e.id] !== void 0) 22587 return n[e.id]; 22588 let t; 22589 switch (e.type) { 22590 case "DirectionalLight": 22591 t = { 22592 direction: new W(), 22593 color: new Et() 22594 }; 22595 break; 22596 case "SpotLight": 22597 t = { 22598 position: new W(), 22599 direction: new W(), 22600 color: new Et(), 22601 distance: 0, 22602 coneCos: 0, 22603 penumbraCos: 0, 22604 decay: 0 22605 }; 22606 break; 22607 case "PointLight": 22608 t = { 22609 position: new W(), 22610 color: new Et(), 22611 distance: 0, 22612 decay: 0 22613 }; 22614 break; 22615 case "HemisphereLight": 22616 t = { 22617 direction: new W(), 22618 skyColor: new Et(), 22619 groundColor: new Et() 22620 }; 22621 break; 22622 case "RectAreaLight": 22623 t = { 22624 color: new Et(), 22625 position: new W(), 22626 halfWidth: new W(), 22627 halfHeight: new W() 22628 }; 22629 break; 22630 } 22631 return n[e.id] = t, t; 22632 } 22633 }; 22634} 22635function OS() { 22636 const n = {}; 22637 return { 22638 get: function(e) { 22639 if (n[e.id] !== void 0) 22640 return n[e.id]; 22641 let t; 22642 switch (e.type) { 22643 case "DirectionalLight": 22644 t = { 22645 shadowIntensity: 1, 22646 shadowBias: 0, 22647 shadowNormalBias: 0, 22648 shadowRadius: 1, 22649 shadowMapSize: new wt() 22650 }; 22651 break; 22652 case "SpotLight": 22653 t = { 22654 shadowIntensity: 1, 22655 shadowBias: 0, 22656 shadowNormalBias: 0, 22657 shadowRadius: 1, 22658 shadowMapSize: new wt() 22659 }; 22660 break; 22661 case "PointLight": 22662 t = { 22663 shadowIntensity: 1, 22664 shadowBias: 0, 22665 shadowNormalBias: 0, 22666 shadowRadius: 1, 22667 shadowMapSize: new wt(), 22668 shadowCameraNear: 1, 22669 shadowCameraFar: 1e3 22670 }; 22671 break; 22672 } 22673 return n[e.id] = t, t; 22674 } 22675 }; 22676} 22677let kS = 0; 22678function FS(n, e) { 22679 return (e.castShadow ? 2 : 0) - (n.castShadow ? 2 : 0) + (e.map ? 1 : 0) - (n.map ? 1 : 0); 22680} 22681function BS(n) { 22682 const e = new US(), t = OS(), i = { 22683 version: 0, 22684 hash: { 22685 directionalLength: -1, 22686 pointLength: -1, 22687 spotLength: -1, 22688 rectAreaLength: -1, 22689 hemiLength: -1, 22690 numDirectionalShadows: -1, 22691 numPointShadows: -1, 22692 numSpotShadows: -1, 22693 numSpotMaps: -1, 22694 numLightProbes: -1 22695 }, 22696 ambient: [0, 0, 0], 22697 probe: [], 22698 directional: [], 22699 directionalShadow: [], 22700 directionalShadowMap: [], 22701 directionalShadowMatrix: [], 22702 spot: [], 22703 spotLightMap: [], 22704 spotShadow: [], 22705 spotShadowMap: [], 22706 spotLightMatrix: [], 22707 rectArea: [], 22708 rectAreaLTC1: null, 22709 rectAreaLTC2: null, 22710 point: [], 22711 pointShadow: [], 22712 pointShadowMap: [], 22713 pointShadowMatrix: [], 22714 hemi: [], 22715 numSpotLightShadowsWithMaps: 0, 22716 numLightProbes: 0 22717 }; 22718 for (let c = 0; c < 9; c++) i.probe.push(new W()); 22719 const r = new W(), s = new kt(), a = new kt(); 22720 function l(c) { 22721 let u = 0, h = 0, d = 0; 22722 for (let M = 0; M < 9; M++) i.probe[M].set(0, 0, 0); 22723 let f = 0, p = 0, v = 0, m = 0, g = 0, _ = 0, x = 0, E = 0, R = 0, T = 0, w = 0; 22724 c.sort(FS); 22725 for (let M = 0, L = c.length; M < L; M++) { 22726 const C = c[M], U = C.color, V = C.intensity, F = C.distance; 22727 let I = null; 22728 if (C.shadow && C.shadow.map && (C.shadow.map.texture.format === Pr ? I = C.shadow.map.texture : I = C.shadow.map.depthTexture || C.shadow.map.texture), C.isAmbientLight) 22729 u += U.r * V, h += U.g * V, d += U.b * V; 22730 else if (C.isLightProbe) { 22731 for (let k = 0; k < 9; k++) 22732 i.probe[k].addScaledVector(C.sh.coefficients[k], V); 22733 w++; 22734 } else if (C.isDirectionalLight) { 22735 const k = e.get(C); 22736 if (k.color.copy(C.color).multiplyScalar(C.intensity), C.castShadow) { 22737 const H = C.shadow, X = t.get(C); 22738 X.shadowIntensity = H.intensity, X.shadowBias = H.bias, X.shadowNormalBias = H.normalBias, X.shadowRadius = H.radius, X.shadowMapSize = H.mapSize, i.directionalShadow[f] = X, i.directionalShadowMap[f] = I, i.directionalShadowMatrix[f] = C.shadow.matrix, _++; 22739 } 22740 i.directional[f] = k, f++; 22741 } else if (C.isSpotLight) { 22742 const k = e.get(C); 22743 k.position.setFromMatrixPosition(C.matrixWorld), k.color.copy(U).multiplyScalar(V), k.distance = F, k.coneCos = Math.cos(C.angle), k.penumbraCos = Math.cos(C.angle * (1 - C.penumbra)), k.decay = C.decay, i.spot[v] = k; 22744 const H = C.shadow; 22745 if (C.map && (i.spotLightMap[R] = C.map, R++, H.updateMatrices(C), C.castShadow && T++), i.spotLightMatrix[v] = H.matrix, C.castShadow) { 22746 const X = t.get(C); 22747 X.shadowIntensity = H.intensity, X.shadowBias = H.bias, X.shadowNormalBias = H.normalBias, X.shadowRadius = H.radius, X.shadowMapSize = H.mapSize, i.spotShadow[v] = X, i.spotShadowMap[v] = I, E++; 22748 } 22749 v++; 22750 } else if (C.isRectAreaLight) { 22751 const k = e.get(C); 22752 k.color.copy(U).multiplyScalar(V), k.halfWidth.set(C.width * 0.5, 0, 0), k.halfHeight.set(0, C.height * 0.5, 0), i.rectArea[m] = k, m++; 22753 } else if (C.isPointLight) { 22754 const k = e.get(C); 22755 if (k.color.copy(C.color).multiplyScalar(C.intensity), k.distance = C.distance, k.decay = C.decay, C.castShadow) { 22756 const H = C.shadow, X = t.get(C); 22757 X.shadowIntensity = H.intensity, X.shadowBias = H.bias, X.shadowNormalBias = H.normalBias, X.shadowRadius = H.radius, X.shadowMapSize = H.mapSize, X.shadowCameraNear = H.camera.near, X.shadowCameraFar = H.camera.far, i.pointShadow[p] = X, i.pointShadowMap[p] = I, i.pointShadowMatrix[p] = C.shadow.matrix, x++; 22758 } 22759 i.point[p] = k, p++; 22760 } else if (C.isHemisphereLight) { 22761 const k = e.get(C); 22762 k.skyColor.copy(C.color).multiplyScalar(V), k.groundColor.copy(C.groundColor).multiplyScalar(V), i.hemi[g] = k, g++; 22763 } 22764 } 22765 m > 0 && (n.has("OES_texture_float_linear") === !0 ? (i.rectAreaLTC1 = Pe.LTC_FLOAT_1, i.rectAreaLTC2 = Pe.LTC_FLOAT_2) : (i.rectAreaLTC1 = Pe.LTC_HALF_1, i.rectAreaLTC2 = Pe.LTC_HALF_2)), i.ambient[0] = u, i.ambient[1] = h, i.ambient[2] = d; 22766 const y = i.hash; 22767 (y.directionalLength !== f || y.pointLength !== p || y.spotLength !== v || y.rectAreaLength !== m || y.hemiLength !== g || y.numDirectionalShadows !== _ || y.numPointShadows !== x || y.numSpotShadows !== E || y.numSpotMaps !== R || y.numLightProbes !== w) && (i.directional.length = f, i.spot.length = v, i.rectArea.length = m, i.point.length = p, i.hemi.length = g, i.directionalShadow.length = _, i.directionalShadowMap.length = _, i.pointShadow.length = x, i.pointShadowMap.length = x, i.spotShadow.length = E, i.spotShadowMap.length = E, i.directionalShadowMatrix.length = _, i.pointShadowMatrix.length = x, i.spotLightMatrix.length = E + R - T, i.spotLightMap.length = R, i.numSpotLightShadowsWithMaps = T, i.numLightProbes = w, y.directionalLength = f, y.pointLength = p, y.spotLength = v, y.rectAreaLength = m, y.hemiLength = g, y.numDirectionalShadows = _, y.numPointShadows = x, y.numSpotShadows = E, y.numSpotMaps = R, y.numLightProbes = w, i.version = kS++); 22768 } 22769 function o(c, u) { 22770 let h = 0, d = 0, f = 0, p = 0, v = 0; 22771 const m = u.matrixWorldInverse; 22772 for (let g = 0, _ = c.length; g < _; g++) { 22773 const x = c[g]; 22774 if (x.isDirectionalLight) { 22775 const E = i.directional[h]; 22776 E.direction.setFromMatrixPosition(x.matrixWorld), r.setFromMatrixPosition(x.target.matrixWorld), E.direction.sub(r), E.direction.transformDirection(m), h++; 22777 } else if (x.isSpotLight) { 22778 const E = i.spot[f]; 22779 E.position.setFromMatrixPosition(x.matrixWorld), E.position.applyMatrix4(m), E.direction.setFromMatrixPosition(x.matrixWorld), r.setFromMatrixPosition(x.target.matrixWorld), E.direction.sub(r), E.direction.transformDirection(m), f++; 22780 } else if (x.isRectAreaLight) { 22781 const E = i.rectArea[p]; 22782 E.position.setFromMatrixPosition(x.matrixWorld), E.position.applyMatrix4(m), a.identity(), s.copy(x.matrixWorld), s.premultiply(m), a.extractRotation(s), E.halfWidth.set(x.width * 0.5, 0, 0), E.halfHeight.set(0, x.height * 0.5, 0), E.halfWidth.applyMatrix4(a), E.halfHeight.applyMatrix4(a), p++; 22783 } else if (x.isPointLight) { 22784 const E = i.point[d]; 22785 E.position.setFromMatrixPosition(x.matrixWorld), E.position.applyMatrix4(m), d++; 22786 } else if (x.isHemisphereLight) { 22787 const E = i.hemi[v]; 22788 E.direction.setFromMatrixPosition(x.matrixWorld), E.direction.transformDirection(m), v++; 22789 } 22790 } 22791 } 22792 return { 22793 setup: l, 22794 setupView: o, 22795 state: i 22796 }; 22797} 22798function Vd(n) { 22799 const e = new BS(n), t = [], i = [], r = []; 22800 function s(d) { 22801 h.camera = d, t.length = 0, i.length = 0, r.length = 0; 22802 } 22803 function a(d) { 22804 t.push(d); 22805 } 22806 function l(d) { 22807 i.push(d); 22808 } 22809 function o(d) { 22810 r.push(d); 22811 } 22812 function c() { 22813 e.setup(t); 22814 } 22815 function u(d) { 22816 e.setupView(t, d); 22817 } 22818 const h = { 22819 lightsArray: t, 22820 shadowsArray: i, 22821 lightProbeGridArray: r, 22822 camera: null, 22823 lights: e, 22824 transmissionRenderTarget: {}, 22825 textureUnits: 0 22826 }; 22827 return { 22828 init: s, 22829 state: h, 22830 setupLights: c, 22831 setupLightsView: u, 22832 pushLight: a, 22833 pushShadow: l, 22834 pushLightProbeGrid: o 22835 }; 22836} 22837function zS(n) { 22838 let e = /* @__PURE__ */ new WeakMap(); 22839 function t(r, s = 0) { 22840 const a = e.get(r); 22841 let l; 22842 return a === void 0 ? (l = new Vd(n), e.set(r, [l])) : s >= a.length ? (l = new Vd(n), a.push(l)) : l = a[s], l; 22843 } 22844 function i() { 22845 e = /* @__PURE__ */ new WeakMap(); 22846 } 22847 return { 22848 get: t, 22849 dispose: i 22850 }; 22851} 22852const HS = `void main() { 22853 gl_Position = vec4( position, 1.0 ); 22854}`, GS = `uniform sampler2D shadow_pass; 22855uniform vec2 resolution; 22856uniform float radius; 22857void main() {
22858 const float samples = float( VSM_SAMPLES ); 22859 float mean = 0.0; 22860 float squared_mean = 0.0; 22861 float uvStride = samples <= 1.0 ? 0.0 : 2.0 / ( samples - 1.0 ); 22862 float uvStart = samples <= 1.0 ? 0.0 : - 1.0; 22863 for ( float i = 0.0; i < samples; i ++ ) { 22864 float uvOffset = uvStart + i * uvStride; 22865 #ifdef HORIZONTAL_PASS 22866 vec2 distribution = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( uvOffset, 0.0 ) * radius ) / resolution ).rg; 22867 mean += distribution.x; 22868 squared_mean += distribution.y * distribution.y + distribution.x * distribution.x; 22869 #else 22870 float depth = texture2D( shadow_pass, ( gl_FragCoord.xy + vec2( 0.0, uvOffset ) * radius ) / resolution ).r; 22871 mean += depth; 22872 squared_mean += depth * depth; 22873 #endif 22874 } 22875 mean = mean / samples; 22876 squared_mean = squared_mean / samples; 22877 float std_dev = sqrt( max( 0.0, squared_mean - mean * mean ) ); 22878 gl_FragColor = vec4( mean, std_dev, 0.0, 1.0 ); 22879}`, VS = [ 22880 /* @__PURE__ */ new W(1, 0, 0), 22881 /* @__PURE__ */ new W(-1, 0, 0), 22882 /* @__PURE__ */ new W(0, 1, 0), 22883 /* @__PURE__ */ new W(0, -1, 0), 22884 /* @__PURE__ */ new W(0, 0, 1), 22885 /* @__PURE__ */ new W(0, 0, -1) 22886], WS = [ 22887 /* @__PURE__ */ new W(0, -1, 0), 22888 /* @__PURE__ */ new W(0, -1, 0), 22889 /* @__PURE__ */ new W(0, 0, 1), 22890 /* @__PURE__ */ new W(0, 0, -1), 22891 /* @__PURE__ */ new W(0, -1, 0), 22892 /* @__PURE__ */ new W(0, -1, 0) 22893], Wd = /* @__PURE__ */ new kt(), Hs = /* @__PURE__ */ new W(), Vl = /* @__PURE__ */ new W(); 22894function $S(n, e, t) { 22895 let i = new ju(); 22896 const r = new wt(), s = new wt(), a = new Gt(), l = new iy(), o = new ry(), c = {}, u = t.maxTextureSize, h = { [sr]: Mn, [Mn]: sr, [Ni]: Ni }, d = new yn({ 22897 defines: { 22898 VSM_SAMPLES: 8 22899 }, 22900 uniforms: { 22901 shadow_pass: { value: null }, 22902 resolution: { value: new wt() }, 22903 radius: { value: 4 } 22904 }, 22905 vertexShader: HS, 22906 fragmentShader: GS 22907 }), f = d.clone(); 22908 f.defines.HORIZONTAL_PASS = 1; 22909 const p = new xn(); 22910 p.setAttribute( 22911 "position", 22912 new on( 22913 new Float32Array([-1, -1, 0.5, 3, -1, 0.5, -1, 3, 0.5]), 22914 3 22915 ) 22916 ); 22917 const v = new _n(p, d), m = this; 22918 this.enabled = !1, this.autoUpdate = !0, this.needsUpdate = !1, this.type = _o; 22919 let g = this.type; 22920 this.render = function(T, w, y) { 22921 if (m.enabled === !1 || m.autoUpdate === !1 && m.needsUpdate === !1 || T.length === 0) return; 22922 this.type === jv && (tt("WebGLShadowMap: PCFSoftShadowMap has been deprecated. Using PCFShadowMap instead."), this.type = _o); 22923 const M = n.getRenderTarget(), L = n.getActiveCubeFace(), C = n.getActiveMipmapLevel(), U = n.state; 22924 U.setBlending(Ui), U.buffers.depth.getReversed() === !0 ? U.buffers.color.setClear(0, 0, 0, 0) : U.buffers.color.setClear(1, 1, 1, 1), U.buffers.depth.setTest(!0), U.setScissorTest(!1); 22925 const V = g !== this.type; 22926 V && w.traverse(function(F) { 22927 F.material && (Array.isArray(F.material) ? F.material.forEach((I) => I.needsUpdate = !0) : F.material.needsUpdate = !0); 22928 }); 22929 for (let F = 0, I = T.length; F < I; F++) { 22930 const k = T[F], H = k.shadow; 22931 if (H === void 0) { 22932 tt("WebGLShadowMap:", k, "has no shadow."); 22933 continue; 22934 } 22935 if (H.autoUpdate === !1 && H.needsUpdate === !1) continue; 22936 r.copy(H.mapSize); 22937 const X = H.getFrameExtents(); 22938 r.multiply(X), s.copy(H.mapSize), (r.x > u || r.y > u) && (r.x > u && (s.x = Math.floor(u / X.x), r.x = s.x * X.x, H.mapSize.x = s.x), r.y > u && (s.y = Math.floor(u / X.y), r.y = s.y * X.y, H.mapSize.y = s.y)); 22939 const K = n.state.buffers.depth.getReversed(); 22940 if (H.camera._reversedDepth = K, H.map === null || V === !0) { 22941 if (H.map !== null && (H.map.depthTexture !== null && (H.map.depthTexture.dispose(), H.map.depthTexture = null), H.map.dispose()), this.type === js) { 22942 if (k.isPointLight) { 22943 tt("WebGLShadowMap: VSM shadow maps are not supported for PointLights. Use PCF or BasicShadowMap instead."); 22944 continue; 22945 } 22946 H.map = new fi(r.x, r.y, { 22947 format: Pr, 22948 type: ki, 22949 minFilter: fn, 22950 magFilter: fn, 22951 generateMipmaps: !1 22952 }), H.map.texture.name = k.name + ".shadowMap", H.map.depthTexture = new vs(r.x, r.y, ti), H.map.depthTexture.name = k.name + ".shadowMapDepth", H.map.depthTexture.format = Fi, H.map.depthTexture.compareFunction = null, H.map.depthTexture.minFilter = sn, H.map.depthTexture.magFilter = sn; 22953 } else 22954 k.isPointLight ? (H.map = new Kp(r.x), H.map.depthTexture = new J_(r.x, gi)) : (H.map = new fi(r.x, r.y), H.map.depthTexture = new vs(r.x, r.y, gi)), H.map.depthTexture.name = k.name + ".shadowMap", H.map.depthTexture.format = Fi, this.type === _o ? (H.map.depthTexture.compareFunction = K ? Hu : zu, H.map.depthTexture.minFilter = fn, H.map.depthTexture.magFilter = fn) : (H.map.depthTexture.compareFunction = null, H.map.depthTexture.minFilter = sn, H.map.depthTexture.magFilter = sn); 22955 H.camera.updateProjectionMatrix(); 22956 }
vendor: 2,885 bytes, lines 22957-23001
22957 const ae = H.map.isWebGLCubeRenderTarget ? 6 : 1; 22958 for (let se = 0; se < ae; se++) { 22959 if (H.map.isWebGLCubeRenderTarget) 22960 n.setRenderTarget(H.map, se), n.clear(); 22961 else { 22962 se === 0 && (n.setRenderTarget(H.map), n.clear()); 22963 const he = H.getViewport(se); 22964 a.set( 22965 s.x * he.x, 22966 s.y * he.y, 22967 s.x * he.z, 22968 s.y * he.w 22969 ), U.viewport(a); 22970 } 22971 if (k.isPointLight) { 22972 const he = H.camera, Ce = H.matrix, Ie = k.distance || he.far; 22973 Ie !== he.far && (he.far = Ie, he.updateProjectionMatrix()), Hs.setFromMatrixPosition(k.matrixWorld), he.position.copy(Hs), Vl.copy(he.position), Vl.add(VS[se]), he.up.copy(WS[se]), he.lookAt(Vl), he.updateMatrixWorld(), Ce.makeTranslation(-Hs.x, -Hs.y, -Hs.z), Wd.multiplyMatrices(he.projectionMatrix, he.matrixWorldInverse), H._frustum.setFromProjectionMatrix(Wd, he.coordinateSystem, he.reversedDepth); 22974 } else 22975 H.updateMatrices(k); 22976 i = H.getFrustum(), E(w, y, H.camera, k, this.type); 22977 } 22978 H.isPointLightShadow !== !0 && this.type === js && _(H, y), H.needsUpdate = !1; 22979 } 22980 g = this.type, m.needsUpdate = !1, n.setRenderTarget(M, L, C); 22981 }; 22982 function _(T, w) { 22983 const y = e.update(v); 22984 d.defines.VSM_SAMPLES !== T.blurSamples && (d.defines.VSM_SAMPLES = T.blurSamples, f.defines.VSM_SAMPLES = T.blurSamples, d.needsUpdate = !0, f.needsUpdate = !0), T.mapPass === null && (T.mapPass = new fi(r.x, r.y, { 22985 format: Pr, 22986 type: ki 22987 })), d.uniforms.shadow_pass.value = T.map.depthTexture, d.uniforms.resolution.value = T.mapSize, d.uniforms.radius.value = T.radius, n.setRenderTarget(T.mapPass), n.clear(), n.renderBufferDirect(w, null, y, d, v, null), f.uniforms.shadow_pass.value = T.mapPass.texture, f.uniforms.resolution.value = T.mapSize, f.uniforms.radius.value = T.radius, n.setRenderTarget(T.map), n.clear(), n.renderBufferDirect(w, null, y, f, v, null); 22988 } 22989 function x(T, w, y, M) { 22990 let L = null; 22991 const C = y.isPointLight === !0 ? T.customDistanceMaterial : T.customDepthMaterial; 22992 if (C !== void 0) 22993 L = C; 22994 else if (L = y.isPointLight === !0 ? o : l, n.localClippingEnabled && w.clipShadows === !0 && Array.isArray(w.clippingPlanes) && w.clippingPlanes.length !== 0 || w.displacementMap && w.displacementScale !== 0 || w.alphaMap && w.alphaTest > 0 || w.map && w.alphaTest > 0 || w.alphaToCoverage === !0) { 22995 const U = L.uuid, V = w.uuid; 22996 let F = c[U]; 22997 F === void 0 && (F = {}, c[U] = F); 22998 let I = F[V]; 22999 I === void 0 && (I = L.clone(), F[V] = I, w.addEventListener("dispose", R)), L = I; 23000 } 23001 if (L.visible = w.visible, L.wireframe = w.wireframe, M === js ? L.side = w.shadowSide !== null ? w.shadowSide : w.side : L.side = w.shadowSide !== null ? w.shadowSide : h[w.side], L.alphaMap = w.alph
vendor: 14,696 bytes, lines 23001-23391
23001aMap, L.alphaTest = w.alphaToCoverage === !0 ? 0.5 : w.alphaTest, L.map = w.map, L.clipShadows = w.clipShadows, L.clippingPlanes = w.clippingPlanes, L.clipIntersection = w.clipIntersection, L.displacementMap = w.displacementMap, L.displacementScale = w.displacementScale, L.displacementBias = w.displacementBias, L.wireframeLinewidth = w.wireframeLinewidth, L.linewidth = w.linewidth, y.isPointLight === !0 && L.isMeshDistanceMaterial === !0) { 23002 const U = n.properties.get(L); 23003 U.light = y; 23004 } 23005 return L; 23006 } 23007 function E(T, w, y, M, L) { 23008 if (T.visible === !1) return; 23009 if (T.layers.test(w.layers) && (T.isMesh || T.isLine || T.isPoints) && (T.castShadow || T.receiveShadow && L === js) && (!T.frustumCulled || i.intersectsObject(T))) { 23010 T.modelViewMatrix.multiplyMatrices(y.matrixWorldInverse, T.matrixWorld); 23011 const V = e.update(T), F = T.material; 23012 if (Array.isArray(F)) { 23013 const I = V.groups; 23014 for (let k = 0, H = I.length; k < H; k++) { 23015 const X = I[k], K = F[X.materialIndex]; 23016 if (K && K.visible) { 23017 const ae = x(T, K, M, L); 23018 T.onBeforeShadow(n, T, w, y, V, ae, X), n.renderBufferDirect(y, null, V, ae, T, X), T.onAfterShadow(n, T, w, y, V, ae, X); 23019 } 23020 } 23021 } else if (F.visible) { 23022 const I = x(T, F, M, L); 23023 T.onBeforeShadow(n, T, w, y, V, I, null), n.renderBufferDirect(y, null, V, I, T, null), T.onAfterShadow(n, T, w, y, V, I, null); 23024 } 23025 } 23026 const U = T.children; 23027 for (let V = 0, F = U.length; V < F; V++) 23028 E(U[V], w, y, M, L); 23029 } 23030 function R(T) { 23031 T.target.removeEventListener("dispose", R); 23032 for (const y in c) { 23033 const M = c[y], L = T.target.uuid; 23034 L in M && (M[L].dispose(), delete M[L]); 23035 } 23036 } 23037} 23038function jS(n, e) { 23039 function t() { 23040 let O = !1; 23041 const ye = new Gt(); 23042 let ne = null; 23043 const Ne = new Gt(0, 0, 0, 0); 23044 return { 23045 setMask: function(be) { 23046 ne !== be && !O && (n.colorMask(be, be, be, be), ne = be); 23047 }, 23048 setLocked: function(be) { 23049 O = be; 23050 }, 23051 setClear: function(be, ce, Ge, it, Ft) { 23052 Ft === !0 && (be *= it, ce *= it, Ge *= it), ye.set(be, ce, Ge, it), Ne.equals(ye) === !1 && (n.clearColor(be, ce, Ge, it), Ne.copy(ye)); 23053 }, 23054 reset: function() { 23055 O = !1, ne = null, Ne.set(-1, 0, 0, 0); 23056 } 23057 }; 23058 } 23059 function i() { 23060 let O = !1, ye = !1, ne = null, Ne = null, be = null; 23061 return { 23062 setReversed: function(ce) { 23063 if (ye !== ce) { 23064 const Ge = e.get("EXT_clip_control"); 23065 ce ? Ge.clipControlEXT(Ge.LOWER_LEFT_EXT, Ge.ZERO_TO_ONE_EXT) : Ge.clipControlEXT(Ge.LOWER_LEFT_EXT, Ge.NEGATIVE_ONE_TO_ONE_EXT), ye = ce; 23066 const it = be; 23067 be = null, this.setClear(it); 23068 } 23069 }, 23070 getReversed: function() { 23071 return ye; 23072 }, 23073 setTest: function(ce) { 23074 ce ? te(n.DEPTH_TEST) : ie(n.DEPTH_TEST); 23075 }, 23076 setMask: function(ce) { 23077 ne !== ce && !O && (n.depthMask(ce), ne = ce); 23078 }, 23079 setFunc: function(ce) { 23080 if (ye && (ce = M_[ce]), Ne !== ce) { 23081 switch (ce) { 23082 case uc: 23083 n.depthFunc(n.NEVER); 23084 break; 23085 case hc: 23086 n.depthFunc(n.ALWAYS); 23087 break; 23088 case dc: 23089 n.depthFunc(n.LESS); 23090 break; 23091 case ms: 23092 n.depthFunc(n.LEQUAL); 23093 break; 23094 case fc: 23095 n.depthFunc(n.EQUAL); 23096 break; 23097 case pc: 23098 n.depthFunc(n.GEQUAL); 23099 break; 23100 case mc: 23101 n.depthFunc(n.GREATER); 23102 break; 23103 case gc: 23104 n.depthFunc(n.NOTEQUAL); 23105 break; 23106 default: 23107 n.depthFunc(n.LEQUAL); 23108 } 23109 Ne = ce; 23110 } 23111 }, 23112 setLocked: function(ce) { 23113 O = ce; 23114 }, 23115 setClear: function(ce) { 23116 be !== ce && (be = ce, ye && (ce = 1 - ce), n.clearDepth(ce)); 23117 }, 23118 reset: function() { 23119 O = !1, ne = null, Ne = null, be = null, ye = !1; 23120 } 23121 }; 23122 } 23123 function r() { 23124 let O = !1, ye = null, ne = null, Ne = null, be = null, ce = null, Ge = null, it = null, Ft = null; 23125 return { 23126 setTest: function(Ct) { 23127 O || (Ct ? te(n.STENCIL_TEST) : ie(n.STENCIL_TEST)); 23128 }, 23129 setMask: function(Ct) { 23130 ye !== Ct && !O && (n.stencilMask(Ct), ye = Ct); 23131 }, 23132 setFunc: function(Ct, N, B) { 23133 (ne !== Ct || Ne !== N || be !== B) && (n.stencilFunc(Ct, N, B), ne = Ct, Ne = N, be = B); 23134 }, 23135 setOp: function(Ct, N, B) { 23136 (ce !== Ct || Ge !== N || it !== B) && (n.stencilOp(Ct, N, B), ce = Ct, Ge = N, it = B); 23137 }, 23138 setLocked: function(Ct) { 23139 O = Ct; 23140 }, 23141 setClear: function(Ct) { 23142 Ft !== Ct && (n.clearStencil(Ct), Ft = Ct); 23143 }, 23144 reset: function() { 23145 O = !1, ye = null, ne = null, Ne = null, be = null, ce = null, Ge = null, it = null, Ft = null; 23146 } 23147 }; 23148 } 23149 const s = new t(), a = new i(), l = new r(), o = /* @__PURE__ */ new WeakMap(), c = /* @__PURE__ */ new WeakMap(); 23150 let u = {}, h = {}, d = {}, f = /* @__PURE__ */ new WeakMap(), p = [], v = null, m = !1, g = null, _ = null, x = null, E = null, R = null, T = null, w = null, y = new Et(0, 0, 0), M = 0, L = !1, C = null, U = null, V = null, F = null, I = null; 23151 const k = n.getParameter(n.MAX_COMBINED_TEXTURE_IMAGE_UNITS); 23152 let H = !1, X = 0; 23153 const K = n.getParameter(n.VERSION); 23154 K.indexOf("WebGL") !== -1 ? (X = parseFloat(/^WebGL (\d)/.exec(K)[1]), H = X >= 1) : K.indexOf("OpenGL ES") !== -1 && (X = parseFloat(/^OpenGL ES (\d)/.exec(K)[1]), H = X >= 2); 23155 let ae = null, se = {}; 23156 const he = n.getParameter(n.SCISSOR_BOX), Ce = n.getParameter(n.VIEWPORT), Ie = new Gt().fromArray(he), Ee = new Gt().fromArray(Ce); 23157 function J(O, ye, ne, Ne) { 23158 const be = new Uint8Array(4), ce = n.createTexture(); 23159 n.bindTexture(O, ce), n.texParameteri(O, n.TEXTURE_MIN_FILTER, n.NEAREST), n.texParameteri(O, n.TEXTURE_MAG_FILTER, n.NEAREST); 23160 for (let Ge = 0; Ge < ne; Ge++) 23161 O === n.TEXTURE_3D || O === n.TEXTURE_2D_ARRAY ? n.texImage3D(ye, 0, n.RGBA, 1, 1, Ne, 0, n.RGBA, n.UNSIGNED_BYTE, be) : n.texImage2D(ye + Ge, 0, n.RGBA, 1, 1, 0, n.RGBA, n.UNSIGNED_BYTE, be); 23162 return ce; 23163 } 23164 const le = {}; 23165 le[n.TEXTURE_2D] = J(n.TEXTURE_2D, n.TEXTURE_2D, 1), le[n.TEXTURE_CUBE_MAP] = J(n.TEXTURE_CUBE_MAP, n.TEXTURE_CUBE_MAP_POSITIVE_X, 6), le[n.TEXTURE_2D_ARRAY] = J(n.TEXTURE_2D_ARRAY, n.TEXTURE_2D_ARRAY, 1, 1), le[n.TEXTURE_3D] = J(n.TEXTURE_3D, n.TEXTURE_3D, 1, 1), s.setClear(0, 0, 0, 1), a.setClear(1), l.setClear(0), te(n.DEPTH_TEST), a.setFunc(ms), lt(!1), ut(zh), te(n.CULL_FACE), at(Ui); 23166 function te(O) { 23167 u[O] !== !0 && (n.enable(O), u[O] = !0); 23168 } 23169 function ie(O) { 23170 u[O] !== !1 && (n.disable(O), u[O] = !1); 23171 } 23172 function fe(O, ye) { 23173 return d[O] !== ye ? (n.bindFramebuffer(O, ye), d[O] = ye, O === n.DRAW_FRAMEBUFFER && (d[n.FRAMEBUFFER] = ye), O === n.FRAMEBUFFER && (d[n.DRAW_FRAMEBUFFER] = ye), !0) : !1; 23174 } 23175 function Se(O, ye) { 23176 let ne = p, Ne = !1; 23177 if (O) { 23178 ne = f.get(ye), ne === void 0 && (ne = [], f.set(ye, ne)); 23179 const be = O.textures; 23180 if (ne.length !== be.length || ne[0] !== n.COLOR_ATTACHMENT0) { 23181 for (let ce = 0, Ge = be.length; ce < Ge; ce++) 23182 ne[ce] = n.COLOR_ATTACHMENT0 + ce; 23183 ne.length = be.length, Ne = !0; 23184 } 23185 } else 23186 ne[0] !== n.BACK && (ne[0] = n.BACK, Ne = !0); 23187 Ne && n.drawBuffers(ne); 23188 } 23189 function Fe(O) { 23190 return v !== O ? (n.useProgram(O), v = O, !0) : !1; 23191 } 23192 const Me = { 23193 [wr]: n.FUNC_ADD, 23194 [qv]: n.FUNC_SUBTRACT, 23195 [Yv]: n.FUNC_REVERSE_SUBTRACT 23196 }; 23197 Me[Kv] = n.MIN, Me[Jv] = n.MAX; 23198 const Ke = { 23199 [Zv]: n.ZERO, 23200 [Qv]: n.ONE, 23201 [e_]: n.SRC_COLOR, 23202 [lc]: n.SRC_ALPHA, 23203 [a_]: n.SRC_ALPHA_SATURATE, 23204 [r_]: n.DST_COLOR, 23205 [n_]: n.DST_ALPHA, 23206 [t_]: n.ONE_MINUS_SRC_COLOR, 23207 [cc]: n.ONE_MINUS_SRC_ALPHA, 23208 [s_]: n.ONE_MINUS_DST_COLOR, 23209 [i_]: n.ONE_MINUS_DST_ALPHA, 23210 [o_]: n.CONSTANT_COLOR, 23211 [l_]: n.ONE_MINUS_CONSTANT_COLOR, 23212 [c_]: n.CONSTANT_ALPHA, 23213 [u_]: n.ONE_MINUS_CONSTANT_ALPHA 23214 }; 23215 function at(O, ye, ne, Ne, be, ce, Ge, it, Ft, Ct) { 23216 if (O === Ui) { 23217 m === !0 && (ie(n.BLEND), m = !1); 23218 return; 23219 } 23220 if (m === !1 && (te(n.BLEND), m = !0), O !== Xv) { 23221 if (O !== g || Ct !== L) { 23222 if ((_ !== wr || R !== wr) && (n.blendEquation(n.FUNC_ADD), _ = wr, R = wr), Ct) 23223 switch (O) { 23224 case hs: 23225 n.blendFuncSeparate(n.ONE, n.ONE_MINUS_SRC_ALPHA, n.ONE, n.ONE_MINUS_SRC_ALPHA); 23226 break; 23227 case oc: 23228 n.blendFunc(n.ONE, n.ONE); 23229 break; 23230 case Hh: 23231 n.blendFuncSeparate(n.ZERO, n.ONE_MINUS_SRC_COLOR, n.ZERO, n.ONE); 23232 break; 23233 case Gh: 23234 n.blendFuncSeparate(n.DST_COLOR, n.ONE_MINUS_SRC_ALPHA, n.ZERO, n.ONE); 23235 break; 23236 default: 23237 xt("WebGLState: Invalid blending: ", O); 23238 break; 23239 } 23240 else 23241 switch (O) { 23242 case hs: 23243 n.blendFuncSeparate(n.SRC_ALPHA, n.ONE_MINUS_SRC_ALPHA, n.ONE, n.ONE_MINUS_SRC_ALPHA); 23244 break; 23245 case oc: 23246 n.blendFuncSeparate(n.SRC_ALPHA, n.ONE, n.ONE, n.ONE); 23247 break; 23248 case Hh: 23249 xt("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true"); 23250 break; 23251 case Gh: 23252 xt("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true"); 23253 break; 23254 default: 23255 xt("WebGLState: Invalid blending: ", O); 23256 break; 23257 } 23258 x = null, E = null, T = null, w = null, y.set(0, 0, 0), M = 0, g = O, L = Ct; 23259 } 23260 return; 23261 } 23262 be = be || ye, ce = ce || ne, Ge = Ge || Ne, (ye !== _ || be !== R) && (n.blendEquationSeparate(Me[ye], Me[be]), _ = ye, R = be), (ne !== x || Ne !== E || ce !== T || Ge !== w) && (n.blendFuncSeparate(Ke[ne], Ke[Ne], Ke[ce], Ke[Ge]), x = ne, E = Ne, T = ce, w = Ge), (it.equals(y) === !1 || Ft !== M) && (n.blendColor(it.r, it.g, it.b, Ft), y.copy(it), M = Ft), g = O, L = !1; 23263 } 23264 function Ue(O, ye) { 23265 O.side === Ni ? ie(n.CULL_FACE) : te(n.CULL_FACE); 23266 let ne = O.side === Mn; 23267 ye && (ne = !ne), lt(ne), O.blending === hs && O.transparent === !1 ? at(Ui) : at(O.blending, O.blendEquation, O.blendSrc, O.blendDst, O.blendEquationAlpha, O.blendSrcAlpha, O.blendDstAlpha, O.blendColor, O.blendAlpha, O.premultipliedAlpha), a.setFunc(O.depthFunc), a.setTest(O.depthTest), a.setMask(O.depthWrite), s.setMask(O.colorWrite); 23268 const Ne = O.stencilWrite; 23269 l.setTest(Ne), Ne && (l.setMask(O.stencilWriteMask), l.setFunc(O.stencilFunc, O.stencilRef, O.stencilFuncMask), l.setOp(O.stencilFail, O.stencilZFail, O.stencilZPass)), D(O.polygonOffset, O.polygonOffsetFactor, O.polygonOffsetUnits), O.alphaToCoverage === !0 ? te(n.SAMPLE_ALPHA_TO_COVERAGE) : ie(n.SAMPLE_ALPHA_TO_COVERAGE); 23270 } 23271 function lt(O) { 23272 C !== O && (O ? n.frontFace(n.CW) : n.frontFace(n.CCW), C = O); 23273 } 23274 function ut(O) { 23275 O !== Wv ? (te(n.CULL_FACE), O !== U && (O === zh ? n.cullFace(n.BACK) : O === $v ? n.cullFace(n.FRONT) : n.cullFace(n.FRONT_AND_BACK))) : ie(n.CULL_FACE), U = O; 23276 } 23277 function Tt(O) { 23278 O !== V && (H && n.lineWidth(O), V = O); 23279 } 23280 function D(O, ye, ne) { 23281 O ? (te(n.POLYGON_OFFSET_FILL), (F !== ye || I !== ne) && (F = ye, I = ne, a.getReversed() && (ye = -ye), n.polygonOffset(ye, ne))) : ie(n.POLYGON_OFFSET_FILL); 23282 } 23283 function Rt(O) { 23284 O ? te(n.SCISSOR_TEST) : ie(n.SCISSOR_TEST); 23285 } 23286 function Qe(O) { 23287 O === void 0 && (O = n.TEXTURE0 + k - 1), ae !== O && (n.activeTexture(O), ae = O); 23288 } 23289 function dt(O, ye, ne) { 23290 ne === void 0 && (ae === null ? ne = n.TEXTURE0 + k - 1 : ne = ae); 23291 let Ne = se[ne]; 23292 Ne === void 0 && (Ne = { type: void 0, texture: void 0 }, se[ne] = Ne), (Ne.type !== O || Ne.texture !== ye) && (ae !== ne && (n.activeTexture(ne), ae = ne), n.bindTexture(O, ye || le[O]), Ne.type = O, Ne.texture = ye); 23293 } 23294 function pe() { 23295 const O = se[ae]; 23296 O !== void 0 && O.type !== void 0 && (n.bindTexture(O.type, null), O.type = void 0, O.texture = void 0); 23297 } 23298 function At() { 23299 try { 23300 n.compressedTexImage2D(...arguments); 23301 } catch (O) { 23302 xt("WebGLState:", O); 23303 } 23304 } 23305 function A() { 23306 try { 23307 n.compressedTexImage3D(...arguments); 23308 } catch (O) { 23309 xt("WebGLState:", O); 23310 } 23311 } 23312 function b() { 23313 try { 23314 n.texSubImage2D(...arguments); 23315 } catch (O) { 23316 xt("WebGLState:", O); 23317 } 23318 } 23319 function G() { 23320 try { 23321 n.texSubImage3D(...arguments); 23322 } catch (O) { 23323 xt("WebGLState:", O); 23324 } 23325 } 23326 function Q() { 23327 try { 23328 n.compressedTexSubImage2D(...arguments); 23329 } catch (O) { 23330 xt("WebGLState:", O); 23331 } 23332 } 23333 function oe() { 23334 try { 23335 n.compressedTexSubImage3D(...arguments); 23336 } catch (O) { 23337 xt("WebGLState:", O); 23338 } 23339 } 23340 function me() { 23341 try { 23342 n.texStorage2D(...arguments); 23343 } catch (O) { 23344 xt("WebGLState:", O); 23345 } 23346 } 23347 function ve() { 23348 try { 23349 n.texStorage3D(...arguments); 23350 } catch (O) { 23351 xt("WebGLState:", O); 23352 } 23353 } 23354 function Z() { 23355 try { 23356 n.texImage2D(...arguments); 23357 } catch (O) { 23358 xt("WebGLState:", O); 23359 } 23360 } 23361 function ee() { 23362 try { 23363 n.texImage3D(...arguments); 23364 } catch (O) { 23365 xt("WebGLState:", O); 23366 } 23367 } 23368 function Ae(O) { 23369 return h[O] !== void 0 ? h[O] : n.getParameter(O); 23370 } 23371 function De(O, ye) { 23372 h[O] !== ye && (n.pixelStorei(O, ye), h[O] = ye); 23373 } 23374 function xe(O) { 23375 Ie.equals(O) === !1 && (n.scissor(O.x, O.y, O.z, O.w), Ie.copy(O)); 23376 } 23377 function _e(O) { 23378 Ee.equals(O) === !1 && (n.viewport(O.x, O.y, O.z, O.w), Ee.copy(O)); 23379 } 23380 function et(O, ye) { 23381 let ne = c.get(ye); 23382 ne === void 0 && (ne = /* @__PURE__ */ new WeakMap(), c.set(ye, ne)); 23383 let Ne = ne.get(O); 23384 Ne === void 0 && (Ne = n.getUniformBlockIndex(ye, O.name), ne.set(O, Ne)); 23385 } 23386 function nt(O, ye) { 23387 const Ne = c.get(ye).get(O); 23388 o.get(ye) !== Ne && (n.uniformBlockBinding(ye, Ne, O.__bindingPointIndex), o.set(ye, Ne)); 23389 } 23390 function gt() { 23391 n.disable(n.BLEND), n.disable(n.CULL_FACE), n.disable(n.DEPTH_TEST), n.disable(n.POLYGON_OFFSET_FILL), n.disable(n.SCISSOR_TEST), n.disable(n.STENCIL_TEST), n.disable(n.SAMPLE_ALPHA_TO_COVERAGE), n.blendEquation(n.FUNC_ADD), n.blendFunc(n.ONE, n.ZERO), n.blendFuncSeparate(n.ONE, n.ZERO, n.ONE, n.ZERO), n.blendColor
23391(0, 0, 0, 0), n.colorMask(!0, !0, !0, !0), n.clearColor(0, 0, 0, 0), n.depthMask(!0), n.depthFunc(n.LESS), a.setReversed(!1), n.clearDepth(1), n.stencilMask(4294967295), n.stencilFunc(n.ALWAYS, 0, 4294967295), n.stencilOp(n.KEEP, n.KEEP, n.KEEP), n.clearStencil(0), n.cullFace(n.BACK), n.frontFace(n.CCW), n.polygonOffset(0, 0), n.activeTexture(n.TEXTURE0), n.bindFramebuffer(n.FRAMEBUFFER, null), n.bindFramebuffer(n.DRAW_FRAMEBUFFER, null), n.bindFramebuffer(n.READ_FRAMEBUFFER, null), n.useProgram(null), n.lineWidth(1), n.scissor(0, 0, n.canvas.width, n.canvas.height), n.viewport(0, 0, n.canvas.width, n.canvas.height), n.pixelStorei(n.PACK_ALIGNMENT, 4), n.pixelStorei(n.UNPACK_ALIGNMENT, 4), n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL, !1), n.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL, !1), n.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL, n.BROWSER_DEFAULT_WEBGL), n.pixelStorei(n.PACK_ROW_LENGTH, 0), n.pixelStorei(n.PACK_SKIP_PIXELS, 0), n.pixelStorei(n.PACK_SKIP_ROWS, 0), n.pixelStorei(n.UNPACK_ROW_LENGTH, 0), n.pixelStorei(n.UNPACK_IMAGE_HEIGHT, 0), n.pixelStorei(n.UNPACK_SKIP_PIXELS, 0), n.pixelStorei(n.UNPACK_SKIP_ROWS, 0), n.pixelStorei(n.UNPACK_SKIP_IMAGES, 0), u = {}, h = {}, ae = null, se = {}, d = {}, f = /* @__PURE__ */ new WeakMap(), p = [], v = null, m = !1, g = null, _ = null, x = null, E = null, R = null, T = null, w = null, y = new Et(0, 0, 0), M = 0, L = !1, C = null, U = null, V = null, F = null, I = null, Ie.set(0, 0, n.canvas.width, n.canvas.height), Ee.set(0, 0, n.canvas.width, n.canvas.height), s.reset(), a.reset(), l.reset(); 23392 } 23393 return { 23394 buffers: { 23395 color: s, 23396 depth: a, 23397 stencil: l 23398 }, 23399 enable: te, 23400 disable: ie, 23401 bindFramebuffer: fe, 23402 drawBuffers: Se, 23403 useProgram: Fe, 23404 setBlending: at, 23405 setMaterial: Ue, 23406 setFlipSided: lt, 23407 setCullFace: ut, 23408 setLineWidth: Tt, 23409 setPolygonOffset: D, 23410 setScissorTest: Rt, 23411 activeTexture: Qe, 23412 bindTexture: dt, 23413 unbindTexture: pe, 23414 compressedTexImage2D: At, 23415 compressedTexImage3D: A, 23416 texImage2D: Z, 23417 texImage3D: ee, 23418 pixelStorei: De, 23419 getParameter: Ae, 23420 updateUBOMapping: et, 23421 uniformBlockBinding: nt, 23422 texStorage2D: me, 23423 texStorage3D: ve, 23424 texSubImage2D: b, 23425 texSubImage3D: G, 23426 compressedTexSubImage2D: Q, 23427 compressedTexSubImage3D: oe, 23428 scissor: xe, 23429 viewport: _e, 23430 reset: gt 23431 }; 23432} 23433function XS(n, e, t, i, r, s, a) { 23434 const l = e.has("WEBGL_multisampled_render_to_texture") ? e.get("WEBGL_multisampled_render_to_texture") : null, o = typeof navigator > "u" ? !1 : /OculusBrowser/g.test(navigator.userAgent), c = new wt(), u = /* @__PURE__ */ new WeakMap(), h = /* @__PURE__ */ new Set(); 23435 let d; 23436 const f = /* @__PURE__ */ new WeakMap(); 23437 let p = !1; 23438 try { 23439 p = typeof OffscreenCanvas < "u" && new OffscreenCanvas(1, 1).getContext("2d") !== null; 23440 } catch { 23441 } 23442 function v(A, b) { 23443 return p ? new OffscreenCanvas(A, b) : No("canvas"); 23444 } 23445 function m(A, b, G) { 23446 let Q = 1; 23447 const oe = At(A); 23448 if ((oe.width > G || oe.height > G) && (Q = G / Math.max(oe.width, oe.height)), Q < 1) 23449 if (typeof HTMLImageElement < "u" && A instanceof HTMLImageElement || typeof HTMLCanvasElement < "u" && A instanceof HTMLCanvasElement || typeof ImageBitmap < "u" && A instanceof ImageBitmap || typeof VideoFrame < "u" && A instanceof VideoFrame) { 23450 const me = Math.floor(Q * oe.width), ve = Math.floor(Q * oe.height); 23451 d === void 0 && (d = v(me, ve)); 23452 const Z = b ? v(me, ve) : d; 23453 return Z.width = me, Z.height = ve, Z.getContext("2d").drawImage(A, 0, 0, me, ve), tt("WebGLRenderer: Texture has been resized from (" + oe.width + "x" + oe.height + ") to (" + me + "x" + ve + ")."), Z; 23454 } else 23455 return "data" in A && tt("WebGLRenderer: Image in DataTexture is too big (" + oe.width + "x" + oe.height + ")."), A; 23456 return A; 23457 } 23458 function g(A) { 23459 return A.generateMipmaps; 23460 } 23461 function _(A) { 23462 n.generateMipmap(A); 23463 } 23464 function x(A) { 23465 return A.isWebGLCubeRenderTarget ? n.TEXTURE_CUBE_MAP : A.isWebGL3DRenderTarget ? n.TEXTURE_3D : A.isWebGLArrayRenderTarget || A.isCompressedArrayTexture ? n.TEXTURE_2D_ARRAY : n.TEXTURE_2D; 23466 } 23467 function E(A, b, G, Q, oe, me = !1) { 23468 if (A !== null) { 23469 if (n[A] !== void 0) return n[A]; 23470 tt("WebGLRenderer: Attempt to use non-existing WebGL internal format '" + A + "'"); 23471 } 23472 let ve; 23473 Q && (ve = e.get("EXT_texture_norm16"), ve || tt("WebGLRenderer: Unable to use normalized textures without EXT_texture_norm16 extension")); 23474 let Z = b; 23475 if (b === n.RED && (G === n.FLOAT && (Z = n.R32F), G === n.HALF_FLOAT && (Z = n.R16F), G === n.UNSIGNED_BYTE && (Z = n.R8), G === n.UNSIGNED_SHORT && ve && (Z = ve.R16_EXT), G === n.SHORT && ve && (Z = ve.R16_SNORM_EXT)), b === n.RED_INTEGER && (G === n.UNSIGNED_BYTE && (Z = n.R8UI), G === n.UNSIGNED_SHORT && (Z = n.R16UI), G === n.UNSIGNED_INT && (Z = n.R32UI), G === n.BYTE && (Z = n.R8I), G === n.SHORT && (Z = n.R16I), G === n.INT && (Z = n.R32I)), b === n.RG && (G === n.FLOAT && (Z = n.RG32F), G === n.HALF_FLOAT && (Z = n.RG16F), G === n.UNSIGNED_BYTE && (Z = n.RG8), G === n.UNSIGNED_SHORT && ve && (Z = ve.RG16_EXT), G === n.SHORT && ve && (Z = ve.RG16_SNORM_EXT)), b === n.RG_INTEGER && (G === n.UNSIGNED_BYTE && (Z = n.RG8UI), G === n.UNSIGNED_SHORT && (Z = n.RG16UI), G === n.UNSIGNED_INT && (Z = n.RG32UI
vendor: 4,781 bytes, lines 23475-23555
23475), G === n.BYTE && (Z = n.RG8I), G === n.SHORT && (Z = n.RG16I), G === n.INT && (Z = n.RG32I)), b === n.RGB_INTEGER && (G === n.UNSIGNED_BYTE && (Z = n.RGB8UI), G === n.UNSIGNED_SHORT && (Z = n.RGB16UI), G === n.UNSIGNED_INT && (Z = n.RGB32UI), G === n.BYTE && (Z = n.RGB8I), G === n.SHORT && (Z = n.RGB16I), G === n.INT && (Z = n.RGB32I)), b === n.RGBA_INTEGER && (G === n.UNSIGNED_BYTE && (Z = n.RGBA8UI), G === n.UNSIGNED_SHORT && (Z = n.RGBA16UI), G === n.UNSIGNED_INT && (Z = n.RGBA32UI), G === n.BYTE && (Z = n.RGBA8I), G === n.SHORT && (Z = n.RGBA16I), G === n.INT && (Z = n.RGBA32I)), b === n.RGB && (G === n.UNSIGNED_SHORT && ve && (Z = ve.RGB16_EXT), G === n.SHORT && ve && (Z = ve.RGB16_SNORM_EXT), G === n.UNSIGNED_INT_5_9_9_9_REV && (Z = n.RGB9_E5), G === n.UNSIGNED_INT_10F_11F_11F_REV && (Z = n.R11F_G11F_B10F)), b === n.RGBA) { 23476 const ee = me ? Lo : _t.getTransfer(oe); 23477 G === n.FLOAT && (Z = n.RGBA32F), G === n.HALF_FLOAT && (Z = n.RGBA16F), G === n.UNSIGNED_BYTE && (Z = ee === Nt ? n.SRGB8_ALPHA8 : n.RGBA8), G === n.UNSIGNED_SHORT && ve && (Z = ve.RGBA16_EXT), G === n.SHORT && ve && (Z = ve.RGBA16_SNORM_EXT), G === n.UNSIGNED_SHORT_4_4_4_4 && (Z = n.RGBA4), G === n.UNSIGNED_SHORT_5_5_5_1 && (Z = n.RGB5_A1); 23478 } 23479 return (Z === n.R16F || Z === n.R32F || Z === n.RG16F || Z === n.RG32F || Z === n.RGBA16F || Z === n.RGBA32F) && e.get("EXT_color_buffer_float"), Z; 23480 } 23481 function R(A, b) { 23482 let G; 23483 return A ? b === null || b === gi || b === oa ? G = n.DEPTH24_STENCIL8 : b === ti ? G = n.DEPTH32F_STENCIL8 : b === aa && (G = n.DEPTH24_STENCIL8, tt("DepthTexture: 16 bit depth attachment is not supported with stencil. Using 24-bit attachment.")) : b === null || b === gi || b === oa ? G = n.DEPTH_COMPONENT24 : b === ti ? G = n.DEPTH_COMPONENT32F : b === aa && (G = n.DEPTH_COMPONENT16), G; 23484 } 23485 function T(A, b) { 23486 return g(A) === !0 || A.isFramebufferTexture && A.minFilter !== sn && A.minFilter !== fn ? Math.log2(Math.max(b.width, b.height)) + 1 : A.mipmaps !== void 0 && A.mipmaps.length > 0 ? A.mipmaps.length : A.isCompressedTexture && Array.isArray(A.image) ? b.mipmaps.length : 1; 23487 } 23488 function w(A) { 23489 const b = A.target; 23490 b.removeEventListener("dispose", w), M(b), b.isVideoTexture && u.delete(b), b.isHTMLTexture && h.delete(b); 23491 } 23492 function y(A) { 23493 const b = A.target; 23494 b.removeEventListener("dispose", y), C(b); 23495 } 23496 function M(A) { 23497 const b = i.get(A); 23498 if (b.__webglInit === void 0) return; 23499 const G = A.source, Q = f.get(G); 23500 if (Q) { 23501 const oe = Q[b.__cacheKey]; 23502 oe.usedTimes--, oe.usedTimes === 0 && L(A), Object.keys(Q).length === 0 && f.delete(G); 23503 } 23504 i.remove(A); 23505 } 23506 function L(A) { 23507 const b = i.get(A); 23508 n.deleteTexture(b.__webglTexture); 23509 const G = A.source, Q = f.get(G); 23510 delete Q[b.__cacheKey], a.memory.textures--; 23511 } 23512 function C(A) { 23513 const b = i.get(A); 23514 if (A.depthTexture && (A.depthTexture.dispose(), i.remove(A.depthTexture)), A.isWebGLCubeRenderTarget) 23515 for (let Q = 0; Q < 6; Q++) { 23516 if (Array.isArray(b.__webglFramebuffer[Q])) 23517 for (let oe = 0; oe < b.__webglFramebuffer[Q].length; oe++) n.deleteFramebuffer(b.__webglFramebuffer[Q][oe]); 23518 else 23519 n.deleteFramebuffer(b.__webglFramebuffer[Q]); 23520 b.__webglDepthbuffer && n.deleteRenderbuffer(b.__webglDepthbuffer[Q]); 23521 } 23522 else { 23523 if (Array.isArray(b.__webglFramebuffer)) 23524 for (let Q = 0; Q < b.__webglFramebuffer.length; Q++) n.deleteFramebuffer(b.__webglFramebuffer[Q]); 23525 else 23526 n.deleteFramebuffer(b.__webglFramebuffer); 23527 if (b.__webglDepthbuffer && n.deleteRenderbuffer(b.__webglDepthbuffer), b.__webglMultisampledFramebuffer && n.deleteFramebuffer(b.__webglMultisampledFramebuffer), b.__webglColorRenderbuffer) 23528 for (let Q = 0; Q < b.__webglColorRenderbuffer.length; Q++) 23529 b.__webglColorRenderbuffer[Q] && n.deleteRenderbuffer(b.__webglColorRenderbuffer[Q]); 23530 b.__webglDepthRenderbuffer && n.deleteRenderbuffer(b.__webglDepthRenderbuffer); 23531 } 23532 const G = A.textures; 23533 for (let Q = 0, oe = G.length; Q < oe; Q++) { 23534 const me = i.get(G[Q]); 23535 me.__webglTexture && (n.deleteTexture(me.__webglTexture), a.memory.textures--), i.remove(G[Q]); 23536 } 23537 i.remove(A); 23538 } 23539 let U = 0; 23540 function V() { 23541 U = 0; 23542 } 23543 function F() { 23544 return U; 23545 } 23546 function I(A) { 23547 U = A; 23548 } 23549 function k() { 23550 const A = U; 23551 return A >= r.maxTextures && tt("WebGLTextures: Trying to use " + A + " texture units while this GPU supports only " + r.maxTextures), U += 1, A; 23552 } 23553 function H(A) { 23554 const b = []; 23555 return b.push(A.wrapS), b.push(A.wrapT), b.push(A.wrapR || 0), b.push(A.magFilter), b.push(A.minFilter), b.push(A.anisotropy), b.push(A.internalFormat), b.pu
vendor: 5,146 bytes, lines 23555-23664
23555sh(A.format), b.push(A.type), b.push(A.generateMipmaps), b.push(A.premultiplyAlpha), b.push(A.flipY), b.push(A.unpackAlignment), b.push(A.colorSpace), b.join(); 23556 } 23557 function X(A, b) { 23558 const G = i.get(A); 23559 if (A.isVideoTexture && dt(A), A.isRenderTargetTexture === !1 && A.isExternalTexture !== !0 && A.version > 0 && G.__version !== A.version) { 23560 const Q = A.image; 23561 if (Q === null) 23562 tt("WebGLRenderer: Texture marked for update but no image data found."); 23563 else if (Q.complete === !1) 23564 tt("WebGLRenderer: Texture marked for update but image is incomplete"); 23565 else { 23566 ie(G, A, b); 23567 return; 23568 } 23569 } else A.isExternalTexture && (G.__webglTexture = A.sourceTexture ? A.sourceTexture : null); 23570 t.bindTexture(n.TEXTURE_2D, G.__webglTexture, n.TEXTURE0 + b); 23571 } 23572 function K(A, b) { 23573 const G = i.get(A); 23574 if (A.isRenderTargetTexture === !1 && A.version > 0 && G.__version !== A.version) { 23575 ie(G, A, b); 23576 return; 23577 } else A.isExternalTexture && (G.__webglTexture = A.sourceTexture ? A.sourceTexture : null); 23578 t.bindTexture(n.TEXTURE_2D_ARRAY, G.__webglTexture, n.TEXTURE0 + b); 23579 } 23580 function ae(A, b) { 23581 const G = i.get(A); 23582 if (A.isRenderTargetTexture === !1 && A.version > 0 && G.__version !== A.version) { 23583 ie(G, A, b); 23584 return; 23585 } 23586 t.bindTexture(n.TEXTURE_3D, G.__webglTexture, n.TEXTURE0 + b); 23587 } 23588 function se(A, b) { 23589 const G = i.get(A); 23590 if (A.isCubeDepthTexture !== !0 && A.version > 0 && G.__version !== A.version) { 23591 fe(G, A, b); 23592 return; 23593 } 23594 t.bindTexture(n.TEXTURE_CUBE_MAP, G.__webglTexture, n.TEXTURE0 + b); 23595 } 23596 const he = { 23597 [vc]: n.REPEAT, 23598 [Di]: n.CLAMP_TO_EDGE, 23599 [_c]: n.MIRRORED_REPEAT 23600 }, Ce = { 23601 [sn]: n.NEAREST, 23602 [f_]: n.NEAREST_MIPMAP_NEAREST, 23603 [Na]: n.NEAREST_MIPMAP_LINEAR, 23604 [fn]: n.LINEAR, 23605 [dl]: n.LINEAR_MIPMAP_NEAREST, 23606 [Mr]: n.LINEAR_MIPMAP_LINEAR 23607 }, Ie = { 23608 [g_]: n.NEVER, 23609 [b_]: n.ALWAYS, 23610 [v_]: n.LESS, 23611 [zu]: n.LEQUAL, 23612 [__]: n.EQUAL, 23613 [Hu]: n.GEQUAL, 23614 [y_]: n.GREATER, 23615 [x_]: n.NOTEQUAL 23616 }; 23617 function Ee(A, b) { 23618 if (b.type === ti && e.has("OES_texture_float_linear") === !1 && (b.magFilter === fn || b.magFilter === dl || b.magFilter === Na || b.magFilter === Mr || b.minFilter === fn || b.minFilter === dl || b.minFilter === Na || b.minFilter === Mr) && tt("WebGLRenderer: Unable to use linear filtering with floating point textures. OES_texture_float_linear not supported on this device."), n.texParameteri(A, n.TEXTURE_WRAP_S, he[b.wrapS]), n.texParameteri(A, n.TEXTURE_WRAP_T, he[b.wrapT]), (A === n.TEXTURE_3D || A === n.TEXTURE_2D_ARRAY) && n.texParameteri(A, n.TEXTURE_WRAP_R, he[b.wrapR]), n.texParameteri(A, n.TEXTURE_MAG_FILTER, Ce[b.magFilter]), n.texParameteri(A, n.TEXTURE_MIN_FILTER, Ce[b.minFilter]), b.compareFunction && (n.texParameteri(A, n.TEXTURE_COMPARE_MODE, n.COMPARE_REF_TO_TEXTURE), n.texParameteri(A, n.TEXTURE_COMPARE_FUNC, Ie[b.compareFunction])), e.has("EXT_texture_filter_anisotropic") === !0) { 23619 if (b.magFilter === sn || b.minFilter !== Na && b.minFilter !== Mr || b.type === ti && e.has("OES_texture_float_linear") === !1) return; 23620 if (b.anisotropy > 1 || i.get(b).__currentAnisotropy) { 23621 const G = e.get("EXT_texture_filter_anisotropic"); 23622 n.texParameterf(A, G.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(b.anisotropy, r.getMaxAnisotropy())), i.get(b).__currentAnisotropy = b.anisotropy; 23623 } 23624 } 23625 } 23626 function J(A, b) { 23627 let G = !1; 23628 A.__webglInit === void 0 && (A.__webglInit = !0, b.addEventListener("dispose", w)); 23629 const Q = b.source; 23630 let oe = f.get(Q); 23631 oe === void 0 && (oe = {}, f.set(Q, oe)); 23632 const me = H(b); 23633 if (me !== A.__cacheKey) { 23634 oe[me] === void 0 && (oe[me] = { 23635 texture: n.createTexture(), 23636 usedTimes: 0 23637 }, a.memory.textures++, G = !0), oe[me].usedTimes++; 23638 const ve = oe[A.__cacheKey]; 23639 ve !== void 0 && (oe[A.__cacheKey].usedTimes--, ve.usedTimes === 0 && L(b)), A.__cacheKey = me, A.__webglTexture = oe[me].texture; 23640 } 23641 return G; 23642 } 23643 function le(A, b, G) { 23644 return Math.floor(Math.floor(A / G) / b); 23645 } 23646 function te(A, b, G, Q) { 23647 const me = A.updateRanges; 23648 if (me.length === 0) 23649 t.texSubImage2D(n.TEXTURE_2D, 0, 0, 0, b.width, b.height, G, Q, b.data); 23650 else { 23651 me.sort((De, xe) => De.start - xe.start); 23652 let ve = 0; 23653 for (let De = 1; De < me.length; De++) { 23654 const xe = me[ve], _e = me[De], et = xe.start + xe.count, nt = le(_e.start, b.width, 4), gt = le(xe.start, b.width, 4); 23655 _e.start <= et + 1 && nt === gt && le(_e.start + _e.count - 1, b.width, 4) === nt ? xe.count = Math.max( 23656 xe.count, 23657 _e.start + _e.count - xe.start 23658 ) : (++ve, me[ve] = _e); 23659 } 23660 me.length = ve + 1; 23661 const Z = t.getParameter(n.UNPACK_ROW_LENGTH), ee = t.getParameter(n.UNPACK_SKIP_PIXELS), Ae = t.getParameter(n.UNPACK_SKIP_ROWS); 23662 t.pixelStorei(n.UNPACK_ROW_LENGTH, b.width); 23663 for (let De = 0, xe = me.length; De < xe; De++) { 23664 const _e = me[De], et = Math.floor(_e.start / 4), nt = Math.
vendor: 5,567 bytes, lines 23664-23744
23664ceil(_e.count / 4), gt = et % b.width, O = Math.floor(et / b.width), ye = nt, ne = 1; 23665 t.pixelStorei(n.UNPACK_SKIP_PIXELS, gt), t.pixelStorei(n.UNPACK_SKIP_ROWS, O), t.texSubImage2D(n.TEXTURE_2D, 0, gt, O, ye, ne, G, Q, b.data); 23666 } 23667 A.clearUpdateRanges(), t.pixelStorei(n.UNPACK_ROW_LENGTH, Z), t.pixelStorei(n.UNPACK_SKIP_PIXELS, ee), t.pixelStorei(n.UNPACK_SKIP_ROWS, Ae); 23668 } 23669 } 23670 function ie(A, b, G) { 23671 let Q = n.TEXTURE_2D; 23672 (b.isDataArrayTexture || b.isCompressedArrayTexture) && (Q = n.TEXTURE_2D_ARRAY), b.isData3DTexture && (Q = n.TEXTURE_3D); 23673 const oe = J(A, b), me = b.source; 23674 t.bindTexture(Q, A.__webglTexture, n.TEXTURE0 + G); 23675 const ve = i.get(me); 23676 if (me.version !== ve.__version || oe === !0) { 23677 if (t.activeTexture(n.TEXTURE0 + G), (typeof ImageBitmap < "u" && b.image instanceof ImageBitmap) === !1) { 23678 const ne = _t.getPrimaries(_t.workingColorSpace), Ne = b.colorSpace === Ji ? null : _t.getPrimaries(b.colorSpace), be = b.colorSpace === Ji || ne === Ne ? n.NONE : n.BROWSER_DEFAULT_WEBGL; 23679 t.pixelStorei(n.UNPACK_FLIP_Y_WEBGL, b.flipY), t.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL, b.premultiplyAlpha), t.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL, be); 23680 } 23681 t.pixelStorei(n.UNPACK_ALIGNMENT, b.unpackAlignment); 23682 let ee = m(b.image, !1, r.maxTextureSize); 23683 ee = pe(b, ee); 23684 const Ae = s.convert(b.format, b.colorSpace), De = s.convert(b.type); 23685 let xe = E(b.internalFormat, Ae, De, b.normalized, b.colorSpace, b.isVideoTexture); 23686 Ee(Q, b); 23687 let _e; 23688 const et = b.mipmaps, nt = b.isVideoTexture !== !0, gt = ve.__version === void 0 || oe === !0, O = me.dataReady, ye = T(b, ee); 23689 if (b.isDepthTexture) 23690 xe = R(b.format === Tr, b.type), gt && (nt ? t.texStorage2D(n.TEXTURE_2D, 1, xe, ee.width, ee.height) : t.texImage2D(n.TEXTURE_2D, 0, xe, ee.width, ee.height, 0, Ae, De, null)); 23691 else if (b.isDataTexture) 23692 if (et.length > 0) { 23693 nt && gt && t.texStorage2D(n.TEXTURE_2D, ye, xe, et[0].width, et[0].height); 23694 for (let ne = 0, Ne = et.length; ne < Ne; ne++) 23695 _e = et[ne], nt ? O && t.texSubImage2D(n.TEXTURE_2D, ne, 0, 0, _e.width, _e.height, Ae, De, _e.data) : t.texImage2D(n.TEXTURE_2D, ne, xe, _e.width, _e.height, 0, Ae, De, _e.data); 23696 b.generateMipmaps = !1; 23697 } else 23698 nt ? (gt && t.texStorage2D(n.TEXTURE_2D, ye, xe, ee.width, ee.height), O && te(b, ee, Ae, De)) : t.texImage2D(n.TEXTURE_2D, 0, xe, ee.width, ee.height, 0, Ae, De, ee.data); 23699 else if (b.isCompressedTexture) 23700 if (b.isCompressedArrayTexture) { 23701 nt && gt && t.texStorage3D(n.TEXTURE_2D_ARRAY, ye, xe, et[0].width, et[0].height, ee.depth); 23702 for (let ne = 0, Ne = et.length; ne < Ne; ne++) 23703 if (_e = et[ne], b.format !== ni) 23704 if (Ae !== null) 23705 if (nt) { 23706 if (O) 23707 if (b.layerUpdates.size > 0) { 23708 const be = bd(_e.width, _e.height, b.format, b.type); 23709 for (const ce of b.layerUpdates) { 23710 const Ge = _e.data.subarray( 23711 ce * be / _e.data.BYTES_PER_ELEMENT, 23712 (ce + 1) * be / _e.data.BYTES_PER_ELEMENT 23713 ); 23714 t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY, ne, 0, 0, ce, _e.width, _e.height, 1, Ae, Ge); 23715 } 23716 b.clearLayerUpdates(); 23717 } else 23718 t.compressedTexSubImage3D(n.TEXTURE_2D_ARRAY, ne, 0, 0, 0, _e.width, _e.height, ee.depth, Ae, _e.data); 23719 } else 23720 t.compressedTexImage3D(n.TEXTURE_2D_ARRAY, ne, xe, _e.width, _e.height, ee.depth, 0, _e.data, 0, 0); 23721 else 23722 tt("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()"); 23723 else 23724 nt ? O && t.texSubImage3D(n.TEXTURE_2D_ARRAY, ne, 0, 0, 0, _e.width, _e.height, ee.depth, Ae, De, _e.data) : t.texImage3D(n.TEXTURE_2D_ARRAY, ne, xe, _e.width, _e.height, ee.depth, 0, Ae, De, _e.data); 23725 } else { 23726 nt && gt && t.texStorage2D(n.TEXTURE_2D, ye, xe, et[0].width, et[0].height); 23727 for (let ne = 0, Ne = et.length; ne < Ne; ne++) 23728 _e = et[ne], b.format !== ni ? Ae !== null ? nt ? O && t.compressedTexSubImage2D(n.TEXTURE_2D, ne, 0, 0, _e.width, _e.height, Ae, _e.data) : t.compressedTexImage2D(n.TEXTURE_2D, ne, xe, _e.width, _e.height, 0, _e.data) : tt("WebGLRenderer: Attempt to load unsupported compressed texture format in .uploadTexture()") : nt ? O && t.texSubImage2D(n.TEXTURE_2D, ne, 0, 0, _e.width, _e.height, Ae, De, _e.data) : t.texImage2D(n.TEXTURE_2D, ne, xe, _e.width, _e.height, 0, Ae, De, _e.data); 23729 } 23730 else if (b.isDataArrayTexture) 23731 if (nt) { 23732 if (gt && t.texStorage3D(n.TEXTURE_2D_ARRAY, ye, xe, ee.width, ee.height, ee.depth), O) 23733 if (b.layerUpdates.size > 0) { 23734 const ne = bd(ee.width, ee.height, b.format, b.type); 23735 for (const Ne of b.layerUpdates) { 23736 const be = ee.data.subarray( 23737 Ne * ne / ee.data.BYTES_PER_ELEMENT, 23738 (Ne + 1) * ne / ee.data.BYTES_PER_ELEMENT 23739 ); 23740 t.texSubImage3D(n.TEXTURE_2D_ARRAY, 0, 0, 0, Ne, ee.width, ee.height, 1, Ae, De, be); 23741 } 23742 b.clearLayerUpdates(); 23743 } else 23744 t.texSubImage3D(n.TEXTURE_2D_ARRAY, 0, 0, 0, 0, ee.
vendor: 8,163 bytes, lines 23744-23863
23744width, ee.height, ee.depth, Ae, De, ee.data); 23745 } else 23746 t.texImage3D(n.TEXTURE_2D_ARRAY, 0, xe, ee.width, ee.height, ee.depth, 0, Ae, De, ee.data); 23747 else if (b.isData3DTexture) 23748 nt ? (gt && t.texStorage3D(n.TEXTURE_3D, ye, xe, ee.width, ee.height, ee.depth), O && t.texSubImage3D(n.TEXTURE_3D, 0, 0, 0, 0, ee.width, ee.height, ee.depth, Ae, De, ee.data)) : t.texImage3D(n.TEXTURE_3D, 0, xe, ee.width, ee.height, ee.depth, 0, Ae, De, ee.data); 23749 else if (b.isFramebufferTexture) { 23750 if (gt) 23751 if (nt) 23752 t.texStorage2D(n.TEXTURE_2D, ye, xe, ee.width, ee.height); 23753 else { 23754 let ne = ee.width, Ne = ee.height; 23755 for (let be = 0; be < ye; be++) 23756 t.texImage2D(n.TEXTURE_2D, be, xe, ne, Ne, 0, Ae, De, null), ne >>= 1, Ne >>= 1; 23757 } 23758 } else if (b.isHTMLTexture) { 23759 if ("texElementImage2D" in n) { 23760 const ne = n.canvas; 23761 if (ne.hasAttribute("layoutsubtree") || ne.setAttribute("layoutsubtree", "true"), ee.parentNode !== ne) { 23762 ne.appendChild(ee), h.add(b), ne.onpaint = (it) => { 23763 const Ft = it.changedElements; 23764 for (const Ct of h) 23765 Ft.includes(Ct.image) && (Ct.needsUpdate = !0); 23766 }, ne.requestPaint(); 23767 return; 23768 } 23769 const Ne = 0, be = n.RGBA, ce = n.RGBA, Ge = n.UNSIGNED_BYTE; 23770 n.texElementImage2D(n.TEXTURE_2D, Ne, be, ce, Ge, ee), n.texParameteri(n.TEXTURE_2D, n.TEXTURE_MIN_FILTER, n.LINEAR), n.texParameteri(n.TEXTURE_2D, n.TEXTURE_WRAP_S, n.CLAMP_TO_EDGE), n.texParameteri(n.TEXTURE_2D, n.TEXTURE_WRAP_T, n.CLAMP_TO_EDGE); 23771 } 23772 } else if (et.length > 0) { 23773 if (nt && gt) { 23774 const ne = At(et[0]); 23775 t.texStorage2D(n.TEXTURE_2D, ye, xe, ne.width, ne.height); 23776 } 23777 for (let ne = 0, Ne = et.length; ne < Ne; ne++) 23778 _e = et[ne], nt ? O && t.texSubImage2D(n.TEXTURE_2D, ne, 0, 0, Ae, De, _e) : t.texImage2D(n.TEXTURE_2D, ne, xe, Ae, De, _e); 23779 b.generateMipmaps = !1; 23780 } else if (nt) { 23781 if (gt) { 23782 const ne = At(ee); 23783 t.texStorage2D(n.TEXTURE_2D, ye, xe, ne.width, ne.height); 23784 } 23785 O && t.texSubImage2D(n.TEXTURE_2D, 0, 0, 0, Ae, De, ee); 23786 } else 23787 t.texImage2D(n.TEXTURE_2D, 0, xe, Ae, De, ee); 23788 g(b) && _(Q), ve.__version = me.version, b.onUpdate && b.onUpdate(b); 23789 } 23790 A.__version = b.version; 23791 } 23792 function fe(A, b, G) { 23793 if (b.image.length !== 6) return; 23794 const Q = J(A, b), oe = b.source; 23795 t.bindTexture(n.TEXTURE_CUBE_MAP, A.__webglTexture, n.TEXTURE0 + G); 23796 const me = i.get(oe); 23797 if (oe.version !== me.__version || Q === !0) { 23798 t.activeTexture(n.TEXTURE0 + G); 23799 const ve = _t.getPrimaries(_t.workingColorSpace), Z = b.colorSpace === Ji ? null : _t.getPrimaries(b.colorSpace), ee = b.colorSpace === Ji || ve === Z ? n.NONE : n.BROWSER_DEFAULT_WEBGL; 23800 t.pixelStorei(n.UNPACK_FLIP_Y_WEBGL, b.flipY), t.pixelStorei(n.UNPACK_PREMULTIPLY_ALPHA_WEBGL, b.premultiplyAlpha), t.pixelStorei(n.UNPACK_ALIGNMENT, b.unpackAlignment), t.pixelStorei(n.UNPACK_COLORSPACE_CONVERSION_WEBGL, ee); 23801 const Ae = b.isCompressedTexture || b.image[0].isCompressedTexture, De = b.image[0] && b.image[0].isDataTexture, xe = []; 23802 for (let ce = 0; ce < 6; ce++) 23803 !Ae && !De ? xe[ce] = m(b.image[ce], !0, r.maxCubemapSize) : xe[ce] = De ? b.image[ce].image : b.image[ce], xe[ce] = pe(b, xe[ce]); 23804 const _e = xe[0], et = s.convert(b.format, b.colorSpace), nt = s.convert(b.type), gt = E(b.internalFormat, et, nt, b.normalized, b.colorSpace), O = b.isVideoTexture !== !0, ye = me.__version === void 0 || Q === !0, ne = oe.dataReady; 23805 let Ne = T(b, _e); 23806 Ee(n.TEXTURE_CUBE_MAP, b); 23807 let be; 23808 if (Ae) { 23809 O && ye && t.texStorage2D(n.TEXTURE_CUBE_MAP, Ne, gt, _e.width, _e.height); 23810 for (let ce = 0; ce < 6; ce++) { 23811 be = xe[ce].mipmaps; 23812 for (let Ge = 0; Ge < be.length; Ge++) { 23813 const it = be[Ge]; 23814 b.format !== ni ? et !== null ? O ? ne && t.compressedTexSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + ce, Ge, 0, 0, it.width, it.height, et, it.data) : t.compressedTexImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + ce, Ge, gt, it.width, it.height, 0, it.data) : tt("WebGLRenderer: Attempt to load unsupported compressed texture format in .setTextureCube()") : O ? ne && t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + ce, Ge, 0, 0, it.width, it.height, et, nt, it.data) : t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + ce, Ge, gt, it.width, it.height, 0, et, nt, it.data); 23815 } 23816 } 23817 } else { 23818 if (be = b.mipmaps, O && ye) { 23819 be.length > 0 && Ne++; 23820 const ce = At(xe[0]); 23821 t.texStorage2D(n.TEXTURE_CUBE_MAP, Ne, gt, ce.width, ce.height); 23822 } 23823 for (let ce = 0; ce < 6; ce++) 23824 if (De) { 23825 O ? ne && t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + ce, 0, 0, 0, xe[ce].width, xe[ce].height, et, nt, xe[ce].data) : t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + ce, 0, gt, xe[ce].width, xe[ce].height, 0, et, nt, xe[ce].data); 23826 for (let Ge = 0; Ge < be.length; Ge++) { 23827 const Ft = be[Ge].image[ce].image; 23828 O ? ne && t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + ce, Ge + 1, 0, 0, Ft.width, Ft.height, et, nt, Ft.data) : t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + ce, Ge + 1, gt, Ft.width, Ft.height, 0, et, nt, Ft.data); 23829 } 23830 } else { 23831 O ? ne && t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + ce, 0, 0, 0, et, nt, xe[ce]) : t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + ce, 0, gt, et, nt, xe[ce]); 23832 for (let Ge = 0; Ge < be.length; Ge++) { 23833 const it = be[Ge]; 23834 O ? ne && t.texSubImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + ce, Ge + 1, 0, 0, et, nt, it.image[ce]) : t.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + ce, Ge + 1, gt, et, nt, it.image[ce]); 23835 } 23836 } 23837 } 23838 g(b) && _(n.TEXTURE_CUBE_MAP), me.__version = oe.version, b.onUpdate && b.onUpdate(b); 23839 } 23840 A.__version = b.version; 23841 } 23842 function Se(A, b, G, Q, oe, me) { 23843 const ve = s.convert(G.format, G.colorSpace), Z = s.convert(G.type), ee = E(G.internalFormat, ve, Z, G.normalized, G.colorSpace), Ae = i.get(b), De = i.get(G); 23844 if (De.__renderTarget = b, !Ae.__hasExternalTextures) { 23845 const xe = Math.max(1, b.width >> me), _e = Math.max(1, b.height >> me); 23846 oe === n.TEXTURE_3D || oe === n.TEXTURE_2D_ARRAY ? t.texImage3D(oe, me, ee, xe, _e, b.depth, 0, ve, Z, null) : t.texImage2D(oe, me, ee, xe, _e, 0, ve, Z, null); 23847 } 23848 t.bindFramebuffer(n.FRAMEBUFFER, A), Qe(b) ? l.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER, Q, oe, De.__webglTexture, 0, Rt(b)) : (oe === n.TEXTURE_2D || oe >= n.TEXTURE_CUBE_MAP_POSITIVE_X && oe <= n.TEXTURE_CUBE_MAP_NEGATIVE_Z) && n.framebufferTexture2D(n.FRAMEBUFFER, Q, oe, De.__webglTexture, me), t.bindFramebuffer(n.FRAMEBUFFER, null); 23849 } 23850 function Fe(A, b, G) { 23851 if (n.bindRenderbuffer(n.RENDERBUFFER, A), b.depthBuffer) { 23852 const Q = b.depthTexture, oe = Q && Q.isDepthTexture ? Q.type : null, me = R(b.stencilBuffer, oe), ve = b.stencilBuffer ? n.DEPTH_STENCIL_ATTACHMENT : n.DEPTH_ATTACHMENT; 23853 Qe(b) ? l.renderbufferStorageMultisampleEXT(n.RENDERBUFFER, Rt(b), me, b.width, b.height) : G ? n.renderbufferStorageMultisample(n.RENDERBUFFER, Rt(b), me, b.width, b.height) : n.renderbufferStorage(n.RENDERBUFFER, me, b.width, b.height), n.framebufferRenderbuffer(n.FRAMEBUFFER, ve, n.RENDERBUFFER, A); 23854 } else { 23855 const Q = b.textures; 23856 for (let oe = 0; oe < Q.length; oe++) { 23857 const me = Q[oe], ve = s.convert(me.format, me.colorSpace), Z = s.convert(me.type), ee = E(me.internalFormat, ve, Z, me.normalized, me.colorSpace); 23858 Qe(b) ? l.renderbufferStorageMultisampleEXT(n.RENDERBUFFER, Rt(b), ee, b.width, b.height) : G ? n.renderbufferStorageMultisample(n.RENDERBUFFER, Rt(b), ee, b.width, b.height) : n.renderbufferStorage(n.RENDERBUFFER, ee, b.width, b.height); 23859 } 23860 } 23861 n.bindRenderbuffer(n.RENDERBUFFER, null); 23862 } 23863 function Me(A, b, G) {
vendor: 4,111 bytes, lines 23864-23933
23864 const Q = b.isWebGLCubeRenderTarget === !0; 23865 if (t.bindFramebuffer(n.FRAMEBUFFER, A), !(b.depthTexture && b.depthTexture.isDepthTexture)) 23866 throw new Error("renderTarget.depthTexture must be an instance of THREE.DepthTexture"); 23867 const oe = i.get(b.depthTexture); 23868 if (oe.__renderTarget = b, (!oe.__webglTexture || b.depthTexture.image.width !== b.width || b.depthTexture.image.height !== b.height) && (b.depthTexture.image.width = b.width, b.depthTexture.image.height = b.height, b.depthTexture.needsUpdate = !0), Q) { 23869 if (oe.__webglInit === void 0 && (oe.__webglInit = !0, b.depthTexture.addEventListener("dispose", w)), oe.__webglTexture === void 0) { 23870 oe.__webglTexture = n.createTexture(), t.bindTexture(n.TEXTURE_CUBE_MAP, oe.__webglTexture), Ee(n.TEXTURE_CUBE_MAP, b.depthTexture); 23871 const Ae = s.convert(b.depthTexture.format), De = s.convert(b.depthTexture.type); 23872 let xe; 23873 b.depthTexture.format === Fi ? xe = n.DEPTH_COMPONENT24 : b.depthTexture.format === Tr && (xe = n.DEPTH24_STENCIL8); 23874 for (let _e = 0; _e < 6; _e++) 23875 n.texImage2D(n.TEXTURE_CUBE_MAP_POSITIVE_X + _e, 0, xe, b.width, b.height, 0, Ae, De, null); 23876 } 23877 } else 23878 X(b.depthTexture, 0); 23879 const me = oe.__webglTexture, ve = Rt(b), Z = Q ? n.TEXTURE_CUBE_MAP_POSITIVE_X + G : n.TEXTURE_2D, ee = b.depthTexture.format === Tr ? n.DEPTH_STENCIL_ATTACHMENT : n.DEPTH_ATTACHMENT; 23880 if (b.depthTexture.format === Fi) 23881 Qe(b) ? l.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER, ee, Z, me, 0, ve) : n.framebufferTexture2D(n.FRAMEBUFFER, ee, Z, me, 0); 23882 else if (b.depthTexture.format === Tr) 23883 Qe(b) ? l.framebufferTexture2DMultisampleEXT(n.FRAMEBUFFER, ee, Z, me, 0, ve) : n.framebufferTexture2D(n.FRAMEBUFFER, ee, Z, me, 0); 23884 else 23885 throw new Error("Unknown depthTexture format"); 23886 } 23887 function Ke(A) { 23888 const b = i.get(A), G = A.isWebGLCubeRenderTarget === !0; 23889 if (b.__boundDepthTexture !== A.depthTexture) { 23890 const Q = A.depthTexture; 23891 if (b.__depthDisposeCallback && b.__depthDisposeCallback(), Q) { 23892 const oe = () => { 23893 delete b.__boundDepthTexture, delete b.__depthDisposeCallback, Q.removeEventListener("dispose", oe); 23894 }; 23895 Q.addEventListener("dispose", oe), b.__depthDisposeCallback = oe; 23896 } 23897 b.__boundDepthTexture = Q; 23898 } 23899 if (A.depthTexture && !b.__autoAllocateDepthBuffer) 23900 if (G) 23901 for (let Q = 0; Q < 6; Q++) 23902 Me(b.__webglFramebuffer[Q], A, Q); 23903 else { 23904 const Q = A.texture.mipmaps; 23905 Q && Q.length > 0 ? Me(b.__webglFramebuffer[0], A, 0) : Me(b.__webglFramebuffer, A, 0); 23906 } 23907 else if (G) { 23908 b.__webglDepthbuffer = []; 23909 for (let Q = 0; Q < 6; Q++) 23910 if (t.bindFramebuffer(n.FRAMEBUFFER, b.__webglFramebuffer[Q]), b.__webglDepthbuffer[Q] === void 0) 23911 b.__webglDepthbuffer[Q] = n.createRenderbuffer(), Fe(b.__webglDepthbuffer[Q], A, !1); 23912 else { 23913 const oe = A.stencilBuffer ? n.DEPTH_STENCIL_ATTACHMENT : n.DEPTH_ATTACHMENT, me = b.__webglDepthbuffer[Q]; 23914 n.bindRenderbuffer(n.RENDERBUFFER, me), n.framebufferRenderbuffer(n.FRAMEBUFFER, oe, n.RENDERBUFFER, me); 23915 } 23916 } else { 23917 const Q = A.texture.mipmaps; 23918 if (Q && Q.length > 0 ? t.bindFramebuffer(n.FRAMEBUFFER, b.__webglFramebuffer[0]) : t.bindFramebuffer(n.FRAMEBUFFER, b.__webglFramebuffer), b.__webglDepthbuffer === void 0) 23919 b.__webglDepthbuffer = n.createRenderbuffer(), Fe(b.__webglDepthbuffer, A, !1); 23920 else { 23921 const oe = A.stencilBuffer ? n.DEPTH_STENCIL_ATTACHMENT : n.DEPTH_ATTACHMENT, me = b.__webglDepthbuffer; 23922 n.bindRenderbuffer(n.RENDERBUFFER, me), n.framebufferRenderbuffer(n.FRAMEBUFFER, oe, n.RENDERBUFFER, me); 23923 } 23924 } 23925 t.bindFramebuffer(n.FRAMEBUFFER, null); 23926 } 23927 function at(A, b, G) { 23928 const Q = i.get(A); 23929 b !== void 0 && Se(Q.__webglFramebuffer, A, A.texture, n.COLOR_ATTACHMENT0, n.TEXTURE_2D, 0), G !== void 0 && Ke(A); 23930 } 23931 function Ue(A) { 23932 const b = A.texture, G = i.get(A), Q = i.get(b); 23933 A.addEventListener("dispose", y);
vendor: 36,581 bytes, lines 23934-24567
23934 const oe = A.textures, me = A.isWebGLCubeRenderTarget === !0, ve = oe.length > 1; 23935 if (ve || (Q.__webglTexture === void 0 && (Q.__webglTexture = n.createTexture()), Q.__version = b.version, a.memory.textures++), me) { 23936 G.__webglFramebuffer = []; 23937 for (let Z = 0; Z < 6; Z++) 23938 if (b.mipmaps && b.mipmaps.length > 0) { 23939 G.__webglFramebuffer[Z] = []; 23940 for (let ee = 0; ee < b.mipmaps.length; ee++) 23941 G.__webglFramebuffer[Z][ee] = n.createFramebuffer(); 23942 } else 23943 G.__webglFramebuffer[Z] = n.createFramebuffer(); 23944 } else { 23945 if (b.mipmaps && b.mipmaps.length > 0) { 23946 G.__webglFramebuffer = []; 23947 for (let Z = 0; Z < b.mipmaps.length; Z++) 23948 G.__webglFramebuffer[Z] = n.createFramebuffer(); 23949 } else 23950 G.__webglFramebuffer = n.createFramebuffer(); 23951 if (ve) 23952 for (let Z = 0, ee = oe.length; Z < ee; Z++) { 23953 const Ae = i.get(oe[Z]); 23954 Ae.__webglTexture === void 0 && (Ae.__webglTexture = n.createTexture(), a.memory.textures++); 23955 } 23956 if (A.samples > 0 && Qe(A) === !1) { 23957 G.__webglMultisampledFramebuffer = n.createFramebuffer(), G.__webglColorRenderbuffer = [], t.bindFramebuffer(n.FRAMEBUFFER, G.__webglMultisampledFramebuffer); 23958 for (let Z = 0; Z < oe.length; Z++) { 23959 const ee = oe[Z]; 23960 G.__webglColorRenderbuffer[Z] = n.createRenderbuffer(), n.bindRenderbuffer(n.RENDERBUFFER, G.__webglColorRenderbuffer[Z]); 23961 const Ae = s.convert(ee.format, ee.colorSpace), De = s.convert(ee.type), xe = E(ee.internalFormat, Ae, De, ee.normalized, ee.colorSpace, A.isXRRenderTarget === !0), _e = Rt(A); 23962 n.renderbufferStorageMultisample(n.RENDERBUFFER, _e, xe, A.width, A.height), n.framebufferRenderbuffer(n.FRAMEBUFFER, n.COLOR_ATTACHMENT0 + Z, n.RENDERBUFFER, G.__webglColorRenderbuffer[Z]); 23963 } 23964 n.bindRenderbuffer(n.RENDERBUFFER, null), A.depthBuffer && (G.__webglDepthRenderbuffer = n.createRenderbuffer(), Fe(G.__webglDepthRenderbuffer, A, !0)), t.bindFramebuffer(n.FRAMEBUFFER, null); 23965 } 23966 } 23967 if (me) { 23968 t.bindTexture(n.TEXTURE_CUBE_MAP, Q.__webglTexture), Ee(n.TEXTURE_CUBE_MAP, b); 23969 for (let Z = 0; Z < 6; Z++) 23970 if (b.mipmaps && b.mipmaps.length > 0) 23971 for (let ee = 0; ee < b.mipmaps.length; ee++) 23972 Se(G.__webglFramebuffer[Z][ee], A, b, n.COLOR_ATTACHMENT0, n.TEXTURE_CUBE_MAP_POSITIVE_X + Z, ee); 23973 else 23974 Se(G.__webglFramebuffer[Z], A, b, n.COLOR_ATTACHMENT0, n.TEXTURE_CUBE_MAP_POSITIVE_X + Z, 0); 23975 g(b) && _(n.TEXTURE_CUBE_MAP), t.unbindTexture(); 23976 } else if (ve) { 23977 for (let Z = 0, ee = oe.length; Z < ee; Z++) { 23978 const Ae = oe[Z], De = i.get(Ae); 23979 let xe = n.TEXTURE_2D; 23980 (A.isWebGL3DRenderTarget || A.isWebGLArrayRenderTarget) && (xe = A.isWebGL3DRenderTarget ? n.TEXTURE_3D : n.TEXTURE_2D_ARRAY), t.bindTexture(xe, De.__webglTexture), Ee(xe, Ae), Se(G.__webglFramebuffer, A, Ae, n.COLOR_ATTACHMENT0 + Z, xe, 0), g(Ae) && _(xe); 23981 } 23982 t.unbindTexture(); 23983 } else { 23984 let Z = n.TEXTURE_2D; 23985 if ((A.isWebGL3DRenderTarget || A.isWebGLArrayRenderTarget) && (Z = A.isWebGL3DRenderTarget ? n.TEXTURE_3D : n.TEXTURE_2D_ARRAY), t.bindTexture(Z, Q.__webglTexture), Ee(Z, b), b.mipmaps && b.mipmaps.length > 0) 23986 for (let ee = 0; ee < b.mipmaps.length; ee++) 23987 Se(G.__webglFramebuffer[ee], A, b, n.COLOR_ATTACHMENT0, Z, ee); 23988 else 23989 Se(G.__webglFramebuffer, A, b, n.COLOR_ATTACHMENT0, Z, 0); 23990 g(b) && _(Z), t.unbindTexture(); 23991 } 23992 A.depthBuffer && Ke(A); 23993 } 23994 function lt(A) { 23995 const b = A.textures; 23996 for (let G = 0, Q = b.length; G < Q; G++) { 23997 const oe = b[G]; 23998 if (g(oe)) { 23999 const me = x(A), ve = i.get(oe).__webglTexture; 24000 t.bindTexture(me, ve), _(me), t.unbindTexture(); 24001 } 24002 } 24003 } 24004 const ut = [], Tt = []; 24005 function D(A) { 24006 if (A.samples > 0) { 24007 if (Qe(A) === !1) { 24008 const b = A.textures, G = A.width, Q = A.height; 24009 let oe = n.COLOR_BUFFER_BIT; 24010 const me = A.stencilBuffer ? n.DEPTH_STENCIL_ATTACHMENT : n.DEPTH_ATTACHMENT, ve = i.get(A), Z = b.length > 1; 24011 if (Z) 24012 for (let Ae = 0; Ae < b.length; Ae++) 24013 t.bindFramebuffer(n.FRAMEBUFFER, ve.__webglMultisampledFramebuffer), n.framebufferRenderbuffer(n.FRAMEBUFFER, n.COLOR_ATTACHMENT0 + Ae, n.RENDERBUFFER, null), t.bindFramebuffer(n.FRAMEBUFFER, ve.__webglFramebuffer), n.framebufferTexture2D(n.DRAW_FRAMEBUFFER, n.COLOR_ATTACHMENT0 + Ae, n.TEXTURE_2D, null, 0); 24014 t.bindFramebuffer(n.READ_FRAMEBUFFER, ve.__webglMultisampledFramebuffer); 24015 const ee = A.texture.mipmaps; 24016 ee && ee.length > 0 ? t.bindFramebuffer(n.DRAW_FRAMEBUFFER, ve.__webglFramebuffer[0]) : t.bindFramebuffer(n.DRAW_FRAMEBUFFER, ve.__webglFramebuffer); 24017 for (let Ae = 0; Ae < b.length; Ae++) { 24018 if (A.resolveDepthBuffer && (A.depthBuffer && (oe |= n.DEPTH_BUFFER_BIT), A.stencilBuffer && A.resolveStencilBuffer && (oe |= n.STENCIL_BUFFER_BIT)), Z) { 24019 n.framebufferRenderbuffer(n.READ_FRAMEBUFFER, n.COLOR_ATTACHMENT0, n.RENDERBUFFER, ve.__webglColorRenderbuffer[Ae]); 24020 const De = i.get(b[Ae]).__webglTexture; 24021 n.framebufferTexture2D(n.DRAW_FRAMEBUFFER, n.COLOR_ATTACHMENT0, n.TEXTURE_2D, De, 0); 24022 } 24023 n.blitFramebuffer(0, 0, G, Q, 0, 0, G, Q, oe, n.NEAREST), o === !0 && (ut.length = 0, Tt.length = 0, ut.push(n.COLOR_ATTACHMENT0 + Ae), A.depthBuffer && A.resolveDepthBuffer === !1 && (ut.push(me), Tt.push(me), n.invalidateFramebuffer(n.DRAW_FRAMEBUFFER, Tt)), n.invalidateFramebuffer(n.READ_FRAMEBUFFER, ut)); 24024 } 24025 if (t.bindFramebuffer(n.READ_FRAMEBUFFER, null), t.bindFramebuffer(n.DRAW_FRAMEBUFFER, null), Z) 24026 for (let Ae = 0; Ae < b.length; Ae++) { 24027 t.bindFramebuffer(n.FRAMEBUFFER, ve.__webglMultisampledFramebuffer), n.framebufferRenderbuffer(n.FRAMEBUFFER, n.COLOR_ATTACHMENT0 + Ae, n.RENDERBUFFER, ve.__webglColorRenderbuffer[Ae]); 24028 const De = i.get(b[Ae]).__webglTexture; 24029 t.bindFramebuffer(n.FRAMEBUFFER, ve.__webglFramebuffer), n.framebufferTexture2D(n.DRAW_FRAMEBUFFER, n.COLOR_ATTACHMENT0 + Ae, n.TEXTURE_2D, De, 0); 24030 } 24031 t.bindFramebuffer(n.DRAW_FRAMEBUFFER, ve.__webglMultisampledFramebuffer); 24032 } else if (A.depthBuffer && A.resolveDepthBuffer === !1 && o) { 24033 const b = A.stencilBuffer ? n.DEPTH_STENCIL_ATTACHMENT : n.DEPTH_ATTACHMENT; 24034 n.invalidateFramebuffer(n.DRAW_FRAMEBUFFER, [b]); 24035 } 24036 } 24037 } 24038 function Rt(A) { 24039 return Math.min(r.maxSamples, A.samples); 24040 } 24041 function Qe(A) { 24042 const b = i.get(A); 24043 return A.samples > 0 && e.has("WEBGL_multisampled_render_to_texture") === !0 && b.__useRenderToTexture !== !1; 24044 } 24045 function dt(A) { 24046 const b = a.render.frame; 24047 u.get(A) !== b && (u.set(A, b), A.update()); 24048 } 24049 function pe(A, b) { 24050 const G = A.colorSpace, Q = A.format, oe = A.type; 24051 return A.isCompressedTexture === !0 || A.isVideoTexture === !0 || G !== Po && G !== Ji && (_t.getTransfer(G) === Nt ? (Q !== ni || oe !== Pn) && tt("WebGLTextures: sRGB encoded textures have to use RGBAFormat and UnsignedByteType.") : xt("WebGLTextures: Unsupported texture color space:", G)), b; 24052 } 24053 function At(A) { 24054 return typeof HTMLImageElement < "u" && A instanceof HTMLImageElement ? (c.width = A.naturalWidth || A.width, c.height = A.naturalHeight || A.height) : typeof VideoFrame < "u" && A instanceof VideoFrame ? (c.width = A.displayWidth, c.height = A.displayHeight) : (c.width = A.width, c.height = A.height), c; 24055 } 24056 this.allocateTextureUnit = k, this.resetTextureUnits = V, this.getTextureUnits = F, this.setTextureUnits = I, this.setTexture2D = X, this.setTexture2DArray = K, this.setTexture3D = ae, this.setTextureCube = se, this.rebindTextures = at, this.setupRenderTarget = Ue, this.updateRenderTargetMipmap = lt, this.updateMultisampleRenderTarget = D, this.setupDepthRenderbuffer = Ke, this.setupFrameBufferTexture = Se, this.useMultisampledRTT = Qe, this.isReversedDepthBuffer = function() { 24057 return t.buffers.depth.getReversed(); 24058 }; 24059} 24060function qS(n, e) { 24061 function t(i, r = Ji) { 24062 let s; 24063 const a = _t.getTransfer(r); 24064 if (i === Pn) return n.UNSIGNED_BYTE; 24065 if (i === Du) return n.UNSIGNED_SHORT_4_4_4_4; 24066 if (i === Uu) return n.UNSIGNED_SHORT_5_5_5_1; 24067 if (i === Lp) return n.UNSIGNED_INT_5_9_9_9_REV; 24068 if (i === Np) return n.UNSIGNED_INT_10F_11F_11F_REV; 24069 if (i === Cp) return n.BYTE; 24070 if (i === Pp) return n.SHORT; 24071 if (i === aa) return n.UNSIGNED_SHORT; 24072 if (i === Iu) return n.INT; 24073 if (i === gi) return n.UNSIGNED_INT; 24074 if (i === ti) return n.FLOAT; 24075 if (i === ki) return n.HALF_FLOAT; 24076 if (i === Ip) return n.ALPHA; 24077 if (i === Dp) return n.RGB; 24078 if (i === ni) return n.RGBA; 24079 if (i === Fi) return n.DEPTH_COMPONENT; 24080 if (i === Tr) return n.DEPTH_STENCIL; 24081 if (i === Ou) return n.RED; 24082 if (i === ku) return n.RED_INTEGER; 24083 if (i === Pr) return n.RG; 24084 if (i === Fu) return n.RG_INTEGER; 24085 if (i === Bu) return n.RGBA_INTEGER; 24086 if (i === yo || i === xo || i === bo || i === wo) 24087 if (a === Nt) 24088 if (s = e.get("WEBGL_compressed_texture_s3tc_srgb"), s !== null) { 24089 if (i === yo) return s.COMPRESSED_SRGB_S3TC_DXT1_EXT; 24090 if (i === xo) return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT; 24091 if (i === bo) return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT; 24092 if (i === wo) return s.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT; 24093 } else 24094 return null; 24095 else if (s = e.get("WEBGL_compressed_texture_s3tc"), s !== null) { 24096 if (i === yo) return s.COMPRESSED_RGB_S3TC_DXT1_EXT; 24097 if (i === xo) return s.COMPRESSED_RGBA_S3TC_DXT1_EXT; 24098 if (i === bo) return s.COMPRESSED_RGBA_S3TC_DXT3_EXT; 24099 if (i === wo) return s.COMPRESSED_RGBA_S3TC_DXT5_EXT; 24100 } else 24101 return null; 24102 if (i === yc || i === xc || i === bc || i === wc) 24103 if (s = e.get("WEBGL_compressed_texture_pvrtc"), s !== null) { 24104 if (i === yc) return s.COMPRESSED_RGB_PVRTC_4BPPV1_IMG; 24105 if (i === xc) return s.COMPRESSED_RGB_PVRTC_2BPPV1_IMG; 24106 if (i === bc) return s.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG; 24107 if (i === wc) return s.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG; 24108 } else 24109 return null; 24110 if (i === Sc || i === Ec || i === Mc || i === Tc || i === Ac || i === Ro || i === Rc) 24111 if (s = e.get("WEBGL_compressed_texture_etc"), s !== null) { 24112 if (i === Sc || i === Ec) return a === Nt ? s.COMPRESSED_SRGB8_ETC2 : s.COMPRESSED_RGB8_ETC2; 24113 if (i === Mc) return a === Nt ? s.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC : s.COMPRESSED_RGBA8_ETC2_EAC; 24114 if (i === Tc) return s.COMPRESSED_R11_EAC; 24115 if (i === Ac) return s.COMPRESSED_SIGNED_R11_EAC; 24116 if (i === Ro) return s.COMPRESSED_RG11_EAC; 24117 if (i === Rc) return s.COMPRESSED_SIGNED_RG11_EAC; 24118 } else 24119 return null; 24120 if (i === Cc || i === Pc || i === Lc || i === Nc || i === Ic || i === Dc || i === Uc || i === Oc || i === kc || i === Fc || i === Bc || i === zc || i === Hc || i === Gc) 24121 if (s = e.get("WEBGL_compressed_texture_astc"), s !== null) { 24122 if (i === Cc) return a === Nt ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR : s.COMPRESSED_RGBA_ASTC_4x4_KHR; 24123 if (i === Pc) return a === Nt ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR : s.COMPRESSED_RGBA_ASTC_5x4_KHR; 24124 if (i === Lc) return a === Nt ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR : s.COMPRESSED_RGBA_ASTC_5x5_KHR; 24125 if (i === Nc) return a === Nt ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR : s.COMPRESSED_RGBA_ASTC_6x5_KHR; 24126 if (i === Ic) return a === Nt ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR : s.COMPRESSED_RGBA_ASTC_6x6_KHR; 24127 if (i === Dc) return a === Nt ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR : s.COMPRESSED_RGBA_ASTC_8x5_KHR; 24128 if (i === Uc) return a === Nt ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR : s.COMPRESSED_RGBA_ASTC_8x6_KHR; 24129 if (i === Oc) return a === Nt ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR : s.COMPRESSED_RGBA_ASTC_8x8_KHR; 24130 if (i === kc) return a === Nt ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR : s.COMPRESSED_RGBA_ASTC_10x5_KHR; 24131 if (i === Fc) return a === Nt ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR : s.COMPRESSED_RGBA_ASTC_10x6_KHR; 24132 if (i === Bc) return a === Nt ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR : s.COMPRESSED_RGBA_ASTC_10x8_KHR; 24133 if (i === zc) return a === Nt ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR : s.COMPRESSED_RGBA_ASTC_10x10_KHR; 24134 if (i === Hc) return a === Nt ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR : s.COMPRESSED_RGBA_ASTC_12x10_KHR; 24135 if (i === Gc) return a === Nt ? s.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR : s.COMPRESSED_RGBA_ASTC_12x12_KHR; 24136 } else 24137 return null; 24138 if (i === Vc || i === Wc || i === $c) 24139 if (s = e.get("EXT_texture_compression_bptc"), s !== null) { 24140 if (i === Vc) return a === Nt ? s.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT : s.COMPRESSED_RGBA_BPTC_UNORM_EXT; 24141 if (i === Wc) return s.COMPRESSED_RGB_BPTC_SIGNED_FLOAT_EXT; 24142 if (i === $c) return s.COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_EXT; 24143 } else 24144 return null; 24145 if (i === jc || i === Xc || i === Co || i === qc) 24146 if (s = e.get("EXT_texture_compression_rgtc"), s !== null) { 24147 if (i === jc) return s.COMPRESSED_RED_RGTC1_EXT; 24148 if (i === Xc) return s.COMPRESSED_SIGNED_RED_RGTC1_EXT; 24149 if (i === Co) return s.COMPRESSED_RED_GREEN_RGTC2_EXT; 24150 if (i === qc) return s.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT; 24151 } else 24152 return null; 24153 return i === oa ? n.UNSIGNED_INT_24_8 : n[i] !== void 0 ? n[i] : null; 24154 } 24155 return { convert: t }; 24156} 24157const YS = ` 24158void main() { 24159 24160 gl_Position = vec4( position, 1.0 ); 24161 24162}`, KS = ` 24163uniform sampler2DArray depthColor; 24164uniform float depthWidth; 24165uniform float depthHeight; 24166 24167void main() { 24168 24169 vec2 coord = vec2( gl_FragCoord.x / depthWidth, gl_FragCoord.y / depthHeight ); 24170 24171 if ( coord.x >= 1.0 ) { 24172 24173 gl_FragDepth = texture( depthColor, vec3( coord.x - 1.0, coord.y, 1 ) ).r; 24174 24175 } else { 24176 24177 gl_FragDepth = texture( depthColor, vec3( coord.x, coord.y, 0 ) ).r; 24178 24179 } 24180 24181}`; 24182class JS { 24183 /** 24184 * Constructs a new depth sensing module. 24185 */ 24186 constructor() { 24187 this.texture = null, this.mesh = null, this.depthNear = 0, this.depthFar = 0; 24188 } 24189 /** 24190 * Inits the depth sensing module 24191 * 24192 * @param {XRWebGLDepthInformation} depthData - The XR depth data. 24193 * @param {XRRenderState} renderState - The XR render state. 24194 */ 24195 init(e, t) { 24196 if (this.texture === null) { 24197 const i = new Vp(e.texture); 24198 (e.depthNear !== t.depthNear || e.depthFar !== t.depthFar) && (this.depthNear = e.depthNear, this.depthFar = e.depthFar), this.texture = i; 24199 } 24200 } 24201 /** 24202 * Returns a plane mesh that visualizes the depth texture. 24203 * 24204 * @param {ArrayCamera} cameraXR - The XR camera. 24205 * @return {?Mesh} The plane mesh. 24206 */ 24207 getMesh(e) { 24208 if (this.texture !== null && this.mesh === null) { 24209 const t = e.cameras[0].viewport, i = new yn({ 24210 vertexShader: YS, 24211 fragmentShader: KS, 24212 uniforms: { 24213 depthColor: { value: this.texture }, 24214 depthWidth: { value: t.z }, 24215 depthHeight: { value: t.w } 24216 } 24217 }); 24218 this.mesh = new _n(new qo(20, 20), i); 24219 } 24220 return this.mesh; 24221 } 24222 /** 24223 * Resets the module 24224 */ 24225 reset() { 24226 this.texture = null, this.mesh = null; 24227 } 24228 /** 24229 * Returns a texture representing the depth of the user's environment. 24230 * 24231 * @return {?ExternalTexture} The depth texture. 24232 */ 24233 getDepthTexture() { 24234 return this.texture; 24235 } 24236} 24237class ZS extends Ir { 24238 /** 24239 * Constructs a new WebGL renderer. 24240 * 24241 * @param {WebGLRenderer} renderer - The renderer. 24242 * @param {WebGL2RenderingContext} gl - The rendering context. 24243 */ 24244 constructor(e, t) { 24245 super(); 24246 const i = this; 24247 let r = null, s = 1, a = null, l = "local-floor", o = 1, c = null, u = null, h = null, d = null, f = null, p = null; 24248 const v = typeof XRWebGLBinding < "u", m = new JS(), g = {}, _ = t.getContextAttributes(); 24249 let x = null, E = null; 24250 const R = [], T = [], w = new wt(); 24251 let y = null; 24252 const M = new mn(); 24253 M.viewport = new Gt(); 24254 const L = new mn(); 24255 L.viewport = new Gt(); 24256 const C = [M, L], U = new ly(); 24257 let V = null, F = null; 24258 this.cameraAutoUpdate = !0, this.enabled = !1, this.isPresenting = !1, this.getController = function(J) { 24259 let le = R[J]; 24260 return le === void 0 && (le = new xl(), R[J] = le), le.getTargetRaySpace(); 24261 }, this.getControllerGrip = function(J) { 24262 let le = R[J]; 24263 return le === void 0 && (le = new xl(), R[J] = le), le.getGripSpace(); 24264 }, this.getHand = function(J) { 24265 let le = R[J]; 24266 return le === void 0 && (le = new xl(), R[J] = le), le.getHandSpace(); 24267 }; 24268 function I(J) { 24269 const le = T.indexOf(J.inputSource); 24270 if (le === -1) 24271 return; 24272 const te = R[le]; 24273 te !== void 0 && (te.update(J.inputSource, J.frame, c || a), te.dispatchEvent({ type: J.type, data: J.inputSource })); 24274 } 24275 function k() { 24276 r.removeEventListener("select", I), r.removeEventListener("selectstart", I), r.removeEventListener("selectend", I), r.removeEventListener("squeeze", I), r.removeEventListener("squeezestart", I), r.removeEventListener("squeezeend", I), r.removeEventListener("end", k), r.removeEventListener("inputsourceschange", H); 24277 for (let J = 0; J < R.length; J++) { 24278 const le = T[J]; 24279 le !== null && (T[J] = null, R[J].disconnect(le)); 24280 } 24281 V = null, F = null, m.reset(); 24282 for (const J in g) 24283 delete g[J]; 24284 e.setRenderTarget(x), f = null, d = null, h = null, r = null, E = null, Ee.stop(), i.isPresenting = !1, e.setPixelRatio(y), e.setSize(w.width, w.height, !1), i.dispatchEvent({ type: "sessionend" }); 24285 } 24286 this.setFramebufferScaleFactor = function(J) { 24287 s = J, i.isPresenting === !0 && tt("WebXRManager: Cannot change framebuffer scale while presenting."); 24288 }, this.setReferenceSpaceType = function(J) { 24289 l = J, i.isPresenting === !0 && tt("WebXRManager: Cannot change reference space type while presenting."); 24290 }, this.getReferenceSpace = function() { 24291 return c || a; 24292 }, this.setReferenceSpace = function(J) { 24293 c = J; 24294 }, this.getBaseLayer = function() { 24295 return d !== null ? d : f; 24296 }, this.getBinding = function() { 24297 return h === null && v && (h = new XRWebGLBinding(r, t)), h; 24298 }, this.getFrame = function() { 24299 return p; 24300 }, this.getSession = function() { 24301 return r; 24302 }, this.setSession = async function(J) { 24303 if (r = J, r !== null) { 24304 if (x = e.getRenderTarget(), r.addEventListener("select", I), r.addEventListener("selectstart", I), r.addEventListener("selectend", I), r.addEventListener("squeeze", I), r.addEventListener("squeezestart", I), r.addEventListener("squeezeend", I), r.addEventListener("end", k), r.addEventListener("inputsourceschange", H), _.xrCompatible !== !0 && await t.makeXRCompatible(), y = e.getPixelRatio(), e.getSize(w), v && "createProjectionLayer" in XRWebGLBinding.prototype) { 24305 let te = null, ie = null, fe = null; 24306 _.depth && (fe = _.stencil ? t.DEPTH24_STENCIL8 : t.DEPTH_COMPONENT24, te = _.stencil ? Tr : Fi, ie = _.stencil ? oa : gi); 24307 const Se = { 24308 colorFormat: t.RGBA8, 24309 depthFormat: fe, 24310 scaleFactor: s 24311 }; 24312 h = this.getBinding(), d = h.createProjectionLayer(Se), r.updateRenderState({ layers: [d] }), e.setPixelRatio(1), e.setSize(d.textureWidth, d.textureHeight, !1), E = new fi( 24313 d.textureWidth, 24314 d.textureHeight, 24315 { 24316 format: ni, 24317 type: Pn, 24318 depthTexture: new vs(d.textureWidth, d.textureHeight, ie, void 0, void 0, void 0, void 0, void 0, void 0, te), 24319 stencilBuffer: _.stencil, 24320 colorSpace: e.outputColorSpace, 24321 samples: _.antialias ? 4 : 0, 24322 resolveDepthBuffer: d.ignoreDepthValues === !1, 24323 resolveStencilBuffer: d.ignoreDepthValues === !1 24324 } 24325 ); 24326 } else { 24327 const te = { 24328 antialias: _.antialias, 24329 alpha: !0, 24330 depth: _.depth, 24331 stencil: _.stencil, 24332 framebufferScaleFactor: s 24333 }; 24334 f = new XRWebGLLayer(r, t, te), r.updateRenderState({ baseLayer: f }), e.setPixelRatio(1), e.setSize(f.framebufferWidth, f.framebufferHeight, !1), E = new fi( 24335 f.framebufferWidth, 24336 f.framebufferHeight, 24337 { 24338 format: ni, 24339 type: Pn, 24340 colorSpace: e.outputColorSpace, 24341 stencilBuffer: _.stencil, 24342 resolveDepthBuffer: f.ignoreDepthValues === !1, 24343 resolveStencilBuffer: f.ignoreDepthValues === !1 24344 } 24345 ); 24346 } 24347 E.isXRRenderTarget = !0, this.setFoveation(o), c = null, a = await r.requestReferenceSpace(l), Ee.setContext(r), Ee.start(), i.isPresenting = !0, i.dispatchEvent({ type: "sessionstart" }); 24348 } 24349 }, this.getEnvironmentBlendMode = function() { 24350 if (r !== null) 24351 return r.environmentBlendMode; 24352 }, this.getDepthTexture = function() { 24353 return m.getDepthTexture(); 24354 }; 24355 function H(J) { 24356 for (let le = 0; le < J.removed.length; le++) { 24357 const te = J.removed[le], ie = T.indexOf(te); 24358 ie >= 0 && (T[ie] = null, R[ie].disconnect(te)); 24359 } 24360 for (let le = 0; le < J.added.length; le++) { 24361 const te = J.added[le]; 24362 let ie = T.indexOf(te); 24363 if (ie === -1) { 24364 for (let Se = 0; Se < R.length; Se++) 24365 if (Se >= T.length) { 24366 T.push(te), ie = Se; 24367 break; 24368 } else if (T[Se] === null) { 24369 T[Se] = te, ie = Se; 24370 break; 24371 } 24372 if (ie === -1) break; 24373 } 24374 const fe = R[ie]; 24375 fe && fe.connect(te); 24376 } 24377 } 24378 const X = new W(), K = new W(); 24379 function ae(J, le, te) { 24380 X.setFromMatrixPosition(le.matrixWorld), K.setFromMatrixPosition(te.matrixWorld); 24381 const ie = X.distanceTo(K), fe = le.projectionMatrix.elements, Se = te.projectionMatrix.elements, Fe = fe[14] / (fe[10] - 1), Me = fe[14] / (fe[10] + 1), Ke = (fe[9] + 1) / fe[5], at = (fe[9] - 1) / fe[5], Ue = (fe[8] - 1) / fe[0], lt = (Se[8] + 1) / Se[0], ut = Fe * Ue, Tt = Fe * lt, D = ie / (-Ue + lt), Rt = D * -Ue; 24382 if (le.matrixWorld.decompose(J.position, J.quaternion, J.scale), J.translateX(Rt), J.translateZ(D), J.matrixWorld.compose(J.position, J.quaternion, J.scale), J.matrixWorldInverse.copy(J.matrixWorld).invert(), fe[10] === -1) 24383 J.projectionMatrix.copy(le.projectionMatrix), J.projectionMatrixInverse.copy(le.projectionMatrixInverse); 24384 else { 24385 const Qe = Fe + D, dt = Me + D, pe = ut - Rt, At = Tt + (ie - Rt), A = Ke * Me / dt * Qe, b = at * Me / dt * Qe; 24386 J.projectionMatrix.makePerspective(pe, At, A, b, Qe, dt), J.projectionMatrixInverse.copy(J.projectionMatrix).invert(); 24387 } 24388 } 24389 function se(J, le) { 24390 le === null ? J.matrixWorld.copy(J.matrix) : J.matrixWorld.multiplyMatrices(le.matrixWorld, J.matrix), J.matrixWorldInverse.copy(J.matrixWorld).invert(); 24391 } 24392 this.updateCamera = function(J) { 24393 if (r === null) return; 24394 let le = J.near, te = J.far; 24395 m.texture !== null && (m.depthNear > 0 && (le = m.depthNear), m.depthFar > 0 && (te = m.depthFar)), U.near = L.near = M.near = le, U.far = L.far = M.far = te, (V !== U.near || F !== U.far) && (r.updateRenderState({ 24396 depthNear: U.near, 24397 depthFar: U.far 24398 }), V = U.near, F = U.far), U.layers.mask = J.layers.mask | 6, M.layers.mask = U.layers.mask & -5, L.layers.mask = U.layers.mask & -3; 24399 const ie = J.parent, fe = U.cameras; 24400 se(U, ie); 24401 for (let Se = 0; Se < fe.length; Se++) 24402 se(fe[Se], ie); 24403 fe.length === 2 ? ae(U, M, L) : U.projectionMatrix.copy(M.projectionMatrix), he(J, U, ie); 24404 }; 24405 function he(J, le, te) { 24406 te === null ? J.matrix.copy(le.matrixWorld) : (J.matrix.copy(te.matrixWorld), J.matrix.invert(), J.matrix.multiply(le.matrixWorld)), J.matrix.decompose(J.position, J.quaternion, J.scale), J.updateMatrixWorld(!0), J.projectionMatrix.copy(le.projectionMatrix), J.projectionMatrixInverse.copy(le.projectionMatrixInverse), J.isPerspectiveCamera && (J.fov = Jc * 2 * Math.atan(1 / J.projectionMatrix.elements[5]), J.zoom = 1); 24407 } 24408 this.getCamera = function() { 24409 return U; 24410 }, this.getFoveation = function() { 24411 if (!(d === null && f === null)) 24412 return o; 24413 }, this.setFoveation = function(J) { 24414 o = J, d !== null && (d.fixedFoveation = J), f !== null && f.fixedFoveation !== void 0 && (f.fixedFoveation = J); 24415 }, this.hasDepthSensing = function() { 24416 return m.texture !== null; 24417 }, this.getDepthSensingMesh = function() { 24418 return m.getMesh(U); 24419 }, this.getCameraTexture = function(J) { 24420 return g[J]; 24421 }; 24422 let Ce = null; 24423 function Ie(J, le) { 24424 if (u = le.getViewerPose(c || a), p = le, u !== null) { 24425 const te = u.views; 24426 f !== null && (e.setRenderTargetFramebuffer(E, f.framebuffer), e.setRenderTarget(E)); 24427 let ie = !1; 24428 te.length !== U.cameras.length && (U.cameras.length = 0, ie = !0); 24429 for (let Me = 0; Me < te.length; Me++) { 24430 const Ke = te[Me]; 24431 let at = null; 24432 if (f !== null) 24433 at = f.getViewport(Ke); 24434 else { 24435 const lt = h.getViewSubImage(d, Ke); 24436 at = lt.viewport, Me === 0 && (e.setRenderTargetTextures( 24437 E, 24438 lt.colorTexture, 24439 lt.depthStencilTexture 24440 ), e.setRenderTarget(E)); 24441 } 24442 let Ue = C[Me]; 24443 Ue === void 0 && (Ue = new mn(), Ue.layers.enable(Me), Ue.viewport = new Gt(), C[Me] = Ue), Ue.matrix.fromArray(Ke.transform.matrix), Ue.matrix.decompose(Ue.position, Ue.quaternion, Ue.scale), Ue.projectionMatrix.fromArray(Ke.projectionMatrix), Ue.projectionMatrixInverse.copy(Ue.projectionMatrix).invert(), Ue.viewport.set(at.x, at.y, at.width, at.height), Me === 0 && (U.matrix.copy(Ue.matrix), U.matrix.decompose(U.position, U.quaternion, U.scale)), ie === !0 && U.cameras.push(Ue); 24444 } 24445 const fe = r.enabledFeatures; 24446 if (fe && fe.includes("depth-sensing") && r.depthUsage == "gpu-optimized" && v) { 24447 h = i.getBinding(); 24448 const Me = h.getDepthInformation(te[0]); 24449 Me && Me.isValid && Me.texture && m.init(Me, r.renderState); 24450 } 24451 if (fe && fe.includes("camera-access") && v) { 24452 e.state.unbindTexture(), h = i.getBinding(); 24453 for (let Me = 0; Me < te.length; Me++) { 24454 const Ke = te[Me].camera; 24455 if (Ke) { 24456 let at = g[Ke]; 24457 at || (at = new Vp(), g[Ke] = at); 24458 const Ue = h.getCameraImage(Ke); 24459 at.sourceTexture = Ue; 24460 } 24461 } 24462 } 24463 } 24464 for (let te = 0; te < R.length; te++) { 24465 const ie = T[te], fe = R[te]; 24466 ie !== null && fe !== void 0 && fe.update(ie, le, c || a); 24467 } 24468 Ce && Ce(J, le), le.detectedPlanes && i.dispatchEvent({ type: "planesdetected", data: le }), p = null; 24469 } 24470 const Ee = new qp(); 24471 Ee.setAnimationLoop(Ie), this.setAnimationLoop = function(J) { 24472 Ce = J; 24473 }, this.dispose = function() { 24474 }; 24475 } 24476} 24477const QS = /* @__PURE__ */ new kt(), tm = /* @__PURE__ */ new ot(); 24478tm.set(-1, 0, 0, 0, 1, 0, 0, 0, 1); 24479function eE(n, e) { 24480 function t(m, g) { 24481 m.matrixAutoUpdate === !0 && m.updateMatrix(), g.value.copy(m.matrix); 24482 } 24483 function i(m, g) { 24484 g.color.getRGB(m.fogColor.value, Wp(n)), g.isFog ? (m.fogNear.value = g.near, m.fogFar.value = g.far) : g.isFogExp2 && (m.fogDensity.value = g.density); 24485 } 24486 function r(m, g, _, x, E) { 24487 g.isNodeMaterial ? g.uniformsNeedUpdate = !1 : g.isMeshBasicMaterial ? s(m, g) : g.isMeshLambertMaterial ? (s(m, g), g.envMap && (m.envMapIntensity.value = g.envMapIntensity)) : g.isMeshToonMaterial ? (s(m, g), h(m, g)) : g.isMeshPhongMaterial ? (s(m, g), u(m, g), g.envMap && (m.envMapIntensity.value = g.envMapIntensity)) : g.isMeshStandardMaterial ? (s(m, g), d(m, g), g.isMeshPhysicalMaterial && f(m, g, E)) : g.isMeshMatcapMaterial ? (s(m, g), p(m, g)) : g.isMeshDepthMaterial ? s(m, g) : g.isMeshDistanceMaterial ? (s(m, g), v(m, g)) : g.isMeshNormalMaterial ? s(m, g) : g.isLineBasicMaterial ? (a(m, g), g.isLineDashedMaterial && l(m, g)) : g.isPointsMaterial ? o(m, g, _, x) : g.isSpriteMaterial ? c(m, g) : g.isShadowMaterial ? (m.color.value.copy(g.color), m.opacity.value = g.opacity) : g.isShaderMaterial && (g.uniformsNeedUpdate = !1); 24488 } 24489 function s(m, g) { 24490 m.opacity.value = g.opacity, g.color && m.diffuse.value.copy(g.color), g.emissive && m.emissive.value.copy(g.emissive).multiplyScalar(g.emissiveIntensity), g.map && (m.map.value = g.map, t(g.map, m.mapTransform)), g.alphaMap && (m.alphaMap.value = g.alphaMap, t(g.alphaMap, m.alphaMapTransform)), g.bumpMap && (m.bumpMap.value = g.bumpMap, t(g.bumpMap, m.bumpMapTransform), m.bumpScale.value = g.bumpScale, g.side === Mn && (m.bumpScale.value *= -1)), g.normalMap && (m.normalMap.value = g.normalMap, t(g.normalMap, m.normalMapTransform), m.normalScale.value.copy(g.normalScale), g.side === Mn && m.normalScale.value.negate()), g.displacementMap && (m.displacementMap.value = g.displacementMap, t(g.displacementMap, m.displacementMapTransform), m.displacementScale.value = g.displacementScale, m.displacementBias.value = g.displacementBias), g.emissiveMap && (m.emissiveMap.value = g.emissiveMap, t(g.emissiveMap, m.emissiveMapTransform)), g.specularMap && (m.specularMap.value = g.specularMap, t(g.specularMap, m.specularMapTransform)), g.alphaTest > 0 && (m.alphaTest.value = g.alphaTest); 24491 const _ = e.get(g), x = _.envMap, E = _.envMapRotation; 24492 x && (m.envMap.value = x, m.envMapRotation.value.setFromMatrix4(QS.makeRotationFromEuler(E)).transpose(), x.isCubeTexture && x.isRenderTargetTexture === !1 && m.envMapRotation.value.premultiply(tm), m.reflectivity.value = g.reflectivity, m.ior.value = g.ior, m.refractionRatio.value = g.refractionRatio), g.lightMap && (m.lightMap.value = g.lightMap, m.lightMapIntensity.value = g.lightMapIntensity, t(g.lightMap, m.lightMapTransform)), g.aoMap && (m.aoMap.value = g.aoMap, m.aoMapIntensity.value = g.aoMapIntensity, t(g.aoMap, m.aoMapTransform)); 24493 } 24494 function a(m, g) { 24495 m.diffuse.value.copy(g.color), m.opacity.value = g.opacity, g.map && (m.map.value = g.map, t(g.map, m.mapTransform)); 24496 } 24497 function l(m, g) { 24498 m.dashSize.value = g.dashSize, m.totalSize.value = g.dashSize + g.gapSize, m.scale.value = g.scale; 24499 } 24500 function o(m, g, _, x) { 24501 m.diffuse.value.copy(g.color), m.opacity.value = g.opacity, m.size.value = g.size * _, m.scale.value = x * 0.5, g.map && (m.map.value = g.map, t(g.map, m.uvTransform)), g.alphaMap && (m.alphaMap.value = g.alphaMap, t(g.alphaMap, m.alphaMapTransform)), g.alphaTest > 0 && (m.alphaTest.value = g.alphaTest); 24502 } 24503 function c(m, g) { 24504 m.diffuse.value.copy(g.color), m.opacity.value = g.opacity, m.rotation.value = g.rotation, g.map && (m.map.value = g.map, t(g.map, m.mapTransform)), g.alphaMap && (m.alphaMap.value = g.alphaMap, t(g.alphaMap, m.alphaMapTransform)), g.alphaTest > 0 && (m.alphaTest.value = g.alphaTest); 24505 } 24506 function u(m, g) { 24507 m.specular.value.copy(g.specular), m.shininess.value = Math.max(g.shininess, 1e-4); 24508 } 24509 function h(m, g) { 24510 g.gradientMap && (m.gradientMap.value = g.gradientMap); 24511 } 24512 function d(m, g) { 24513 m.metalness.value = g.metalness, g.metalnessMap && (m.metalnessMap.value = g.metalnessMap, t(g.metalnessMap, m.metalnessMapTransform)), m.roughness.value = g.roughness, g.roughnessMap && (m.roughnessMap.value = g.roughnessMap, t(g.roughnessMap, m.roughnessMapTransform)), g.envMap && (m.envMapIntensity.value = g.envMapIntensity); 24514 } 24515 function f(m, g, _) { 24516 m.ior.value = g.ior, g.sheen > 0 && (m.sheenColor.value.copy(g.sheenColor).multiplyScalar(g.sheen), m.sheenRoughness.value = g.sheenRoughness, g.sheenColorMap && (m.sheenColorMap.value = g.sheenColorMap, t(g.sheenColorMap, m.sheenColorMapTransform)), g.sheenRoughnessMap && (m.sheenRoughnessMap.value = g.sheenRoughnessMap, t(g.sheenRoughnessMap, m.sheenRoughnessMapTransform))), g.clearcoat > 0 && (m.clearcoat.value = g.clearcoat, m.clearcoatRoughness.value = g.clearcoatRoughness, g.clearcoatMap && (m.clearcoatMap.value = g.clearcoatMap, t(g.clearcoatMap, m.clearcoatMapTransform)), g.clearcoatRoughnessMap && (m.clearcoatRoughnessMap.value = g.clearcoatRoughnessMap, t(g.clearcoatRoughnessMap, m.clearcoatRoughnessMapTransform)), g.clearcoatNormalMap && (m.clearcoatNormalMap.value = g.clearcoatNormalMap, t(g.clearcoatNormalMap, m.clearcoatNormalMapTransform), m.clearcoatNormalScale.value.copy(g.clearcoatNormalScale), g.side === Mn && m.clearcoatNormalScale.value.negate())), g.dispersion > 0 && (m.dispersion.value = g.dispersion), g.iridescence > 0 && (m.iridescence.value = g.iridescence, m.iridescenceIOR.value = g.iridescenceIOR, m.iridescenceThicknessMinimum.value = g.iridescenceThicknessRange[0], m.iridescenceThicknessMaximum.value = g.iridescenceThicknessRange[1], g.iridescenceMap && (m.iridescenceMap.value = g.iridescenceMap, t(g.iridescenceMap, m.iridescenceMapTransform)), g.iridescenceThicknessMap && (m.iridescenceThicknessMap.value = g.iridescenceThicknessMap, t(g.iridescenceThicknessMap, m.iridescenceThicknessMapTransform))), g.transmission > 0 && (m.transmission.value = g.transmission, m.transmissionSamplerMap.value = _.texture, m.transmissionSamplerSize.value.set(_.width, _.height), g.transmissionMap && (m.transmissionMap.value = g.transmissionMap, t(g.transmissionMap, m.transmissionMapTransform)), m.thickness.value = g.thickness, g.thicknessMap && (m.thicknessMap.value = g.thicknessMap, t(g.thicknessMap, m.thicknessMapTransform)), m.attenuationDistance.value = g.attenuationDistance, m.attenuationColor.value.copy(g.attenuationColor)), g.anisotropy > 0 && (m.anisotropyVector.value.set(g.anisotropy * Math.cos(g.anisotropyRotation), g.anisotropy * Math.sin(g.anisotropyRotation)), g.anisotropyMap && (m.anisotropyMap.value = g.anisotropyMap, t(g.anisotropyMap, m.anisotropyMapTransform))), m.specularIntensity.value = g.specularIntensity, m.specularColor.value.copy(g.specularColor), g.specularColorMap && (m.specularColorMap.value = g.specularColorMap, t(g.specularColorMap, m.specularColorMapTransform)), g.specularIntensityMap && (m.specularIntensityMap.value = g.specularIntensityMap, t(g.specularIntensityMap, m.specularIntensityMapTransform)); 24517 } 24518 function p(m, g) { 24519 g.matcap && (m.matcap.value = g.matcap); 24520 } 24521 function v(m, g) { 24522 const _ = e.get(g).light; 24523 m.referencePosition.value.setFromMatrixPosition(_.matrixWorld), m.nearDistance.value = _.shadow.camera.near, m.farDistance.value = _.shadow.camera.far; 24524 } 24525 return { 24526 refreshFogUniforms: i, 24527 refreshMaterialUniforms: r 24528 }; 24529} 24530function tE(n, e, t, i) { 24531 let r = {}, s = {}, a = []; 24532 const l = n.getParameter(n.MAX_UNIFORM_BUFFER_BINDINGS); 24533 function o(_, x) { 24534 const E = x.program; 24535 i.uniformBlockBinding(_, E); 24536 } 24537 function c(_, x) { 24538 let E = r[_.id]; 24539 E === void 0 && (p(_), E = u(_), r[_.id] = E, _.addEventListener("dispose", m)); 24540 const R = x.program; 24541 i.updateUBOMapping(_, R); 24542 const T = e.render.frame; 24543 s[_.id] !== T && (d(_), s[_.id] = T); 24544 } 24545 function u(_) { 24546 const x = h(); 24547 _.__bindingPointIndex = x; 24548 const E = n.createBuffer(), R = _.__size, T = _.usage; 24549 return n.bindBuffer(n.UNIFORM_BUFFER, E), n.bufferData(n.UNIFORM_BUFFER, R, T), n.bindBuffer(n.UNIFORM_BUFFER, null), n.bindBufferBase(n.UNIFORM_BUFFER, x, E), E; 24550 } 24551 function h() { 24552 for (let _ = 0; _ < l; _++) 24553 if (a.indexOf(_) === -1) 24554 return a.push(_), _; 24555 return xt("WebGLRenderer: Maximum number of simultaneously usable uniforms groups reached."), 0; 24556 } 24557 function d(_) { 24558 const x = r[_.id], E = _.uniforms, R = _.__cache; 24559 n.bindBuffer(n.UNIFORM_BUFFER, x); 24560 for (let T = 0, w = E.length; T < w; T++) { 24561 const y = Array.isArray(E[T]) ? E[T] : [E[T]]; 24562 for (let M = 0, L = y.length; M < L; M++) { 24563 const C = y[M]; 24564 if (f(C, T, M, R) === !0) { 24565 const U = C.__offset, V = Array.isArray(C.value) ? C.value : [C.value]; 24566 let F = 0; 24567 for (let I = 0; I < V.length; I++) {
24568 const k = V[I], H = v(k); 24569 typeof k == "number" || typeof k == "boolean" ? (C.__data[0] = k, n.bufferSubData(n.UNIFORM_BUFFER, U + F, C.__data)) : k.isMatrix3 ? (C.__data[0] = k.elements[0], C.__data[1] = k.elements[1], C.__data[2] = k.elements[2], C.__data[3] = 0, C.__data[4] = k.elements[3], C.__data[5] = k.elements[4], C.__data[6] = k.elements[5], C.__data[7] = 0, C.__data[8] = k.elements[6], C.__data[9] = k.elements[7], C.__data[10] = k.elements[8], C.__data[11] = 0) : ArrayBuffer.isView(k) ? C.__data.set(new k.constructor(k.buffer, k.byteOffset, C.__data.length)) : (k.toArray(C.__data, F), F += H.storage / Float32Array.BYTES_PER_ELEMENT); 24570 } 24571 n.bufferSubData(n.UNIFORM_BUFFER, U, C.__data); 24572 } 24573 } 24574 } 24575 n.bindBuffer(n.UNIFORM_BUFFER, null); 24576 } 24577 function f(_, x, E, R) { 24578 const T = _.value, w = x + "_" + E; 24579 if (R[w] === void 0) 24580 return typeof T == "number" || typeof T == "boolean" ? R[w] = T : ArrayBuffer.isView(T) ? R[w] = T.slice() : R[w] = T.clone(), !0; 24581 { 24582 const y = R[w]; 24583 if (typeof T == "number" || typeof T == "boolean") { 24584 if (y !== T) 24585 return R[w] = T, !0; 24586 } else { 24587 if (ArrayBuffer.isView(T)) 24588 return !0; 24589 if (y.equals(T) === !1) 24590 return y.copy(T), !0; 24591 } 24592 } 24593 return !1; 24594 } 24595 function p(_) { 24596 const x = _.uniforms; 24597 let E = 0; 24598 const R = 16; 24599 for (let w = 0, y = x.length; w < y; w++) { 24600 const M = Array.isArray(x[w]) ? x[w] : [x[w]]; 24601 for (let L = 0, C = M.length; L < C; L++) { 24602 const U = M[L], V = Array.isArray(U.value) ? U.value : [U.value]; 24603 for (let F = 0, I = V.length; F < I; F++) { 24604 const k = V[F], H = v(k), X = E % R, K = X % H.boundary, ae = X + K; 24605 E += K, ae !== 0 && R - ae < H.storage && (E += R - ae), U.__data = new Float32Array(H.storage / Float32Array.BYTES_PER_ELEMENT), U.__offset = E, E += H.storage; 24606 } 24607 } 24608 } 24609 const T = E % R; 24610 return T > 0 && (E += R - T), _.__size = E, _.__cache = {}, this; 24611 } 24612 function v(_) { 24613 const x = { 24614 boundary: 0, 24615 // bytes 24616 storage: 0 24617 // bytes 24618 }; 24619 return typeof _ == "number" || typeof _ == "boolean" ? (x.boundary = 4, x.storage = 4) : _.isVector2 ? (x.boundary = 8, x.storage = 8) : _.isVector3 || _.isColor ? (x.boundary = 16, x.storage = 12) : _.isVector4 ? (x.boundary = 16, x.storage = 16) : _.isMatrix3 ? (x.boundary = 48, x.storage = 48) : _.isMatrix4 ? (x.boundary = 64, x.storage = 64) : _.isTexture ? tt("WebGLRenderer: Texture samplers can not be part of an uniforms group.") : ArrayBuffer.isView(_) ? (x.boundary = 16, x.storage = _.byteLength) : tt("WebGLRenderer: Unsupported uniform value type.", _), x; 24620 } 24621 function m(_) { 24622 const x = _.target; 24623 x.removeEventListener("dispose", m); 24624 const E = a.indexOf(x.__bindingPointIndex); 24625 a.splice(E, 1), n.deleteBuffer(r[x.id]), delete r[x.id], delete s[x.id]; 24626 } 24627 function g() { 24628 for (const _ in r) 24629 n.deleteBuffer(r[_]); 24630 a = [], r = {}, s = {}; 24631 } 24632 return { 24633 bind: o, 24634 update: c, 24635 dispose: g 24636 }; 24637} 24638const nE = new Uint16Array([ 24639 12469, 24640 15057, 24641 12620, 24642 14925, 24643 13266, 24644 14620, 24645 13807, 24646 14376, 24647 14323, 24648 13990, 24649 14545, 24650 13625, 24651 14713, 24652 13328, 24653 14840, 24654 12882, 24655 14931, 24656 12528, 24657 14996, 24658 12233, 24659 15039, 24660 11829, 24661 15066, 24662 11525, 24663 15080, 24664 11295, 24665 15085, 24666 10976, 24667 15082, 24668 10705, 24669 15073, 24670 10495, 24671 13880, 24672 14564, 24673 13898, 24674 14542, 24675 13977, 24676 14430, 24677 14158, 24678 14124, 24679 14393, 24680 13732, 24681 14556, 24682 13410, 24683 14702, 24684 12996, 24685 14814, 24686 12596, 24687 14891, 24688 12291, 24689 14937, 24690 11834, 24691 14957, 24692 11489, 24693 14958, 24694 11194, 24695 14943, 24696 10803, 24697 14921, 24698 10506, 24699 14893, 24700 10278, 24701 14858, 24702 9960, 24703 14484, 24704 14039, 24705 14487, 24706 14025, 24707 14499, 24708 13941, 24709 14524, 24710 13740, 24711 14574, 24712 13468, 24713 14654, 24714 13106, 24715 14743, 24716 12678, 24717 14818, 24718 12344, 24719 14867, 24720 11893, 24721 14889, 24722 11509, 24723 14893, 24724 11180, 24725 14881, 24726 10751, 24727 14852, 24728 10428, 24729 14812, 24730 10128, 24731 14765, 24732 9754, 24733 14712, 24734 9466, 24735 14764, 24736 13480, 24737 14764, 24738 13475, 24739 14766, 24740 13440, 24741 14766, 24742 13347, 24743 14769, 24744 13070, 24745 14786, 24746 12713, 24747 14816, 24748 12387, 24749 14844, 24750 11957, 24751 14860, 24752 11549, 24753 14868, 24754 11215, 24755 14855, 24756 10751, 24757 14825, 24758 10403, 24759 14782, 24760 10044, 24761 14729, 24762 9651, 24763 14666, 24764 9352, 24765 14599, 24766 9029, 24767 14967, 24768 12835, 24769 14966, 24770 12831, 24771 14963, 24772 12804, 24773 14954, 24774 12723, 24775 14936, 24776 12564, 24777 14917, 24778 12347, 24779 14900, 24780 11958, 24781 14886, 24782 11569, 24783 14878, 24784 11247, 24785 14859, 24786 10765, 24787 14828, 24788 10401, 24789 14784, 24790 10011, 24791 14727, 24792 9600, 24793 14660, 24794 9289, 24795 14586, 24796 8893, 24797 14508, 24798 8533, 24799 15111, 24800 12234, 24801 15110, 24802 12234, 24803 15104, 24804 12216, 24805 15092, 24806 12156, 24807 15067, 24808 12010, 24809 15028, 24810 11776, 24811 14981, 24812 11500, 24813 14942, 24814 11205, 24815 14902, 24816 10752, 24817 14861, 24818 10393, 24819 14812, 24820 9991, 24821 14752, 24822 9570, 24823 14682, 24824 9252, 24825 14603, 24826 8808, 24827 14519, 24828 8445, 24829 14431, 24830 8145, 24831 15209, 24832 11449, 24833 15208, 24834 11451, 24835 15202, 24836 11451, 24837 15190,
vendor: 4,227 bytes, lines 24838-25204
24838 11438, 24839 15163, 24840 11384, 24841 15117, 24842 11274, 24843 15055, 24844 10979, 24845 14994, 24846 10648, 24847 14932, 24848 10343, 24849 14871, 24850 9936, 24851 14803, 24852 9532, 24853 14729, 24854 9218, 24855 14645, 24856 8742, 24857 14556, 24858 8381, 24859 14461, 24860 8020, 24861 14365, 24862 7603, 24863 15273, 24864 10603, 24865 15272, 24866 10607, 24867 15267, 24868 10619, 24869 15256, 24870 10631, 24871 15231, 24872 10614, 24873 15182, 24874 10535, 24875 15118, 24876 10389, 24877 15042, 24878 10167, 24879 14963, 24880 9787, 24881 14883, 24882 9447, 24883 14800, 24884 9115, 24885 14710, 24886 8665, 24887 14615, 24888 8318, 24889 14514, 24890 7911, 24891 14411, 24892 7507, 24893 14279, 24894 7198, 24895 15314, 24896 9675, 24897 15313, 24898 9683, 24899 15309, 24900 9712, 24901 15298, 24902 9759, 24903 15277, 24904 9797, 24905 15229, 24906 9773, 24907 15166, 24908 9668, 24909 15084, 24910 9487, 24911 14995, 24912 9274, 24913 14898, 24914 8910, 24915 14800, 24916 8539, 24917 14697, 24918 8234, 24919 14590, 24920 7790, 24921 14479, 24922 7409, 24923 14367, 24924 7067, 24925 14178, 24926 6621, 24927 15337, 24928 8619, 24929 15337, 24930 8631, 24931 15333, 24932 8677, 24933 15325, 24934 8769, 24935 15305, 24936 8871, 24937 15264, 24938 8940, 24939 15202, 24940 8909, 24941 15119, 24942 8775, 24943 15022, 24944 8565, 24945 14916, 24946 8328, 24947 14804, 24948 8009, 24949 14688, 24950 7614, 24951 14569, 24952 7287, 24953 14448, 24954 6888, 24955 14321, 24956 6483, 24957 14088, 24958 6171, 24959 15350, 24960 7402, 24961 15350, 24962 7419, 24963 15347, 24964 7480, 24965 15340, 24966 7613, 24967 15322, 24968 7804, 24969 15287, 24970 7973, 24971 15229, 24972 8057, 24973 15148, 24974 8012, 24975 15046, 24976 7846, 24977 14933, 24978 7611, 24979 14810, 24980 7357, 24981 14682, 24982 7069, 24983 14552, 24984 6656, 24985 14421, 24986 6316, 24987 14251, 24988 5948, 24989 14007, 24990 5528, 24991 15356, 24992 5942, 24993 15356, 24994 5977, 24995 15353, 24996 6119, 24997 15348, 24998 6294, 24999 15332, 25000 6551, 25001 15302, 25002 6824, 25003 15249, 25004 7044, 25005 15171, 25006 7122, 25007 15070, 25008 7050, 25009 14949, 25010 6861, 25011 14818, 25012 6611, 25013 14679, 25014 6349, 25015 14538, 25016 6067, 25017 14398, 25018 5651, 25019 14189, 25020 5311, 25021 13935, 25022 4958, 25023 15359, 25024 4123, 25025 15359, 25026 4153, 25027 15356, 25028 4296, 25029 15353, 25030 4646, 25031 15338, 25032 5160, 25033 15311, 25034 5508, 25035 15263, 25036 5829, 25037 15188, 25038 6042, 25039 15088, 25040 6094, 25041 14966, 25042 6001, 25043 14826, 25044 5796, 25045 14678, 25046 5543, 25047 14527, 25048 5287, 25049 14377, 25050 4985, 25051 14133, 25052 4586, 25053 13869, 25054 4257, 25055 15360, 25056 1563, 25057 15360, 25058 1642, 25059 15358, 25060 2076, 25061 15354, 25062 2636, 25063 15341, 25064 3350, 25065 15317, 25066 4019, 25067 15273, 25068 4429, 25069 15203, 25070 4732, 25071 15105, 25072 4911, 25073 14981, 25074 4932, 25075 14836, 25076 4818, 25077 14679, 25078 4621, 25079 14517, 25080 4386, 25081 14359, 25082 4156, 25083 14083, 25084 3795, 25085 13808, 25086 3437, 25087 15360, 25088 122, 25089 15360, 25090 137, 25091 15358, 25092 285, 25093 15355, 25094 636, 25095 15344, 25096 1274, 25097 15322, 25098 2177, 25099 15281, 25100 2765, 25101 15215, 25102 3223, 25103 15120, 25104 3451, 25105 14995, 25106 3569, 25107 14846, 25108 3567, 25109 14681, 25110 3466, 25111 14511, 25112 3305, 25113 14344, 25114 3121, 25115 14037, 25116 2800, 25117 13753, 25118 2467, 25119 15360, 25120 0, 25121 15360, 25122 1, 25123 15359, 25124 21, 25125 15355, 25126 89, 25127 15346, 25128 253, 25129 15325, 25130 479, 25131 15287, 25132 796, 25133 15225, 25134 1148, 25135 15133, 25136 1492, 25137 15008, 25138 1749, 25139 14856, 25140 1882, 25141 14685, 25142 1886, 25143 14506, 25144 1783, 25145 14324, 25146 1608, 25147 13996, 25148 1398, 25149 13702, 25150 1183 25151]); 25152let ai = null; 25153function iE() { 25154 return ai === null && (ai = new Hp(nE, 16, 16, Pr, ki), ai.name = "DFG_LUT", ai.minFilter = fn, ai.magFilter = fn, ai.wrapS = Di, ai.wrapT = Di, ai.generateMipmaps = !1, ai.needsUpdate = !0), ai; 25155} 25156class Jo { 25157 /** 25158 * Constructs a new WebGL renderer. 25159 * 25160 * @param {WebGLRenderer~Options} [parameters] - The configuration parameter. 25161 */ 25162 constructor(e = {}) { 25163 const { 25164 canvas: t = S_(), 25165 context: i = null, 25166 depth: r = !0, 25167 stencil: s = !1, 25168 alpha: a = !1, 25169 antialias: l = !1, 25170 premultipliedAlpha: o = !0, 25171 preserveDrawingBuffer: c = !1, 25172 powerPreference: u = "default", 25173 failIfMajorPerformanceCaveat: h = !1, 25174 reversedDepthBuffer: d = !1, 25175 outputBufferType: f = Pn 25176 } = e; 25177 this.isWebGLRenderer = !0; 25178 let p; 25179 if (i !== null) { 25180 if (typeof WebGLRenderingContext < "u" && i instanceof WebGLRenderingContext) 25181 throw new Error("THREE.WebGLRenderer: WebGL 1 is not supported since r163."); 25182 p = i.getContextAttributes().alpha; 25183 } else 25184 p = a; 25185 const v = f, m = /* @__PURE__ */ new Set([ 25186 Bu, 25187 Fu, 25188 ku 25189 ]), g = /* @__PURE__ */ new Set([ 25190 Pn, 25191 gi, 25192 aa, 25193 oa, 25194 Du, 25195 Uu 25196 ]), _ = new Uint32Array(4), x = new Int32Array(4), E = new W(); 25197 let R = null, T = null; 25198 const w = [], y = []; 25199 let M = null; 25200 this.domElement = t, this.debug = { 25201 /** 25202 * Enables error checking and reporting when shader programs are being compiled. 25203 * @type {boolean} 25204 */
25205 checkShaderErrors: !0, 25206 /** 25207 * Callback for custom error reporting. 25208 * @type {?Function} 25209 */ 25210 onShaderError: null 25211 }, this.autoClear = !0, this.autoClearColor = !0, this.autoClearDepth = !0, this.autoClearStencil = !0, this.sortObjects = !0, this.clippingPlanes = [], this.localClippingEnabled = !1, this.toneMapping = di, this.toneMappingExposure = 1, this.transmissionResolutionScale = 1; 25212 const L = this; 25213 let C = !1, U = null; 25214 this._outputColorSpace = Hn; 25215 let V = 0, F = 0, I = null, k = -1, H = null; 25216 const X = new Gt(), K = new Gt(); 25217 let ae = null; 25218 const se = new Et(0); 25219 let he = 0, Ce = t.width, Ie = t.height, Ee = 1, J = null, le = null; 25220 const te = new Gt(0, 0, Ce, Ie), ie = new Gt(0, 0, Ce, Ie); 25221 let fe = !1; 25222 const Se = new ju(); 25223 let Fe = !1, Me = !1; 25224 const Ke = new kt(), at = new W(), Ue = new Gt(), lt = { background: null, fog: null, environment: null, overrideMaterial: null, isScene: !0 }; 25225 let ut = !1; 25226 function Tt() { 25227 return I === null ? Ee : 1; 25228 } 25229 let D = i; 25230 function Rt(S, z) { 25231 return t.getContext(S, z); 25232 } 25233 try { 25234 const S = { 25235 alpha: !0, 25236 depth: r, 25237 stencil: s, 25238 antialias: l, 25239 premultipliedAlpha: o, 25240 preserveDrawingBuffer: c, 25241 powerPreference: u, 25242 failIfMajorPerformanceCaveat: h 25243 }; 25244 if ("setAttribute" in t && t.setAttribute("data-engine", `three.js r${Lu}`), t.addEventListener("webglcontextlost", ce, !1), t.addEventListener("webglcontextrestored", Ge, !1), t.addEventListener("webglcontextcreationerror", it, !1), D === null) { 25245 const z = "webgl2"; 25246 if (D = Rt(z, S), D === null) 25247 throw Rt(z) ? new Error("Error creating WebGL context with your selected attributes.") : new Error("Error creating WebGL context."); 25248 } 25249 } catch (S) { 25250 throw xt("WebGLRenderer: " + S.message), S; 25251 } 25252 let Qe, dt, pe, At, A, b, G, Q, oe, me, ve, Z, ee, Ae, De, xe, _e, et, nt, gt, O, ye, ne; 25253 function Ne() { 25254 Qe = new iw(D), Qe.init(), O = new qS(D, Qe), dt = new Yb(D, Qe, e, O), pe = new jS(D, Qe), dt.reversedDepthBuffer && d && pe.buffers.depth.setReversed(!0), At = new aw(D), A = new NS(), b = new XS(D, Qe, pe, A, dt, O, At), G = new nw(L), Q = new uy(D), ye = new Xb(D, Q), oe = new rw(D, Q, At, ye), me = new lw(D, oe, Q, ye, At), et = new ow(D, dt, b), De = new Kb(A), ve = new LS(L, G, Qe, dt, ye, De), Z = new eE(L, A), ee = new DS(), Ae = new zS(Qe), _e = new jb(L, G, pe, me, p, o), xe = new $S(L, me, dt), ne = new tE(D, At, dt, pe), nt = new qb(D, Qe, At), gt = new sw(D, Qe, At), At.programs = ve.programs, L.capabilities = dt, L.extensions = Qe, L.properties = A, L.renderLists = ee, L.shadowMap = xe, L.state = pe, L.info = At; 25255 } 25256 Ne(), v !== Pn && (M = new uw(v, t.width, t.height, r, s)); 25257 const be = new ZS(L, D); 25258 this.xr = be, this.getContext = function() { 25259 return D; 25260 }, this.getContextAttributes = function() { 25261 return D.getContextAttributes(); 25262 }, this.forceContextLoss = function() { 25263 const S = Qe.get("WEBGL_lose_context"); 25264 S && S.loseContext(); 25265 }, this.forceContextRestore = function() { 25266 const S = Qe.get("WEBGL_lose_context"); 25267 S && S.restoreContext(); 25268 }, this.getPixelRatio = function() { 25269 return Ee; 25270 }, this.setPixelRatio = function(S) { 25271 S !== void 0 && (Ee = S, this.setSize(Ce, Ie, !1)); 25272 }, this.getSize = function(S) { 25273 return S.set(Ce, Ie); 25274 }, this.setSize = function(S, z, q = !0) { 25275 if (be.isPresenting) { 25276 tt("WebGLRenderer: Can't change size while VR device is presenting."); 25277 return; 25278 } 25279 Ce = S, Ie = z, t.width = Math.floor(S * Ee), t.height = Math.floor(z * Ee), q === !0 && (t.style.width = S + "px", t.style.height = z + "px"), M !== null && M.setSize(t.width, t.height), this.setViewport(0, 0, S, z); 25280 }, this.getDrawingBufferSize = function(S) { 25281 return S.set(Ce * Ee, Ie * Ee).floor(); 25282 }, this.setDrawingBufferSize = function(S, z, q) { 25283 Ce = S, Ie = z, Ee = q, t.width = Math.floor(S * q), t.height = Math.floor(z * q), this.setViewport(0, 0, S, z); 25284 }, this.setEffects = function(S) { 25285 if (v === Pn) { 25286 xt("THREE.WebGLRenderer: setEffects() requires outputBufferType set to HalfFloatType or FloatType."); 25287 return; 25288 } 25289 if (S) { 25290 for (let z = 0; z < S.length; z++) 25291 if (S[z].isOutputPass === !0) { 25292 tt("THREE.WebGLRenderer: OutputPass is not needed in setEffects(). Tone mapping and color space conversion are applied automatically."); 25293 break; 25294 } 25295 } 25296 M.setEffects(S || []); 25297 }, this.getCurrentViewport = function(S) { 25298 return S.copy(X); 25299 }, this.getViewport = function(S) { 25300 return S.copy(te); 25301 }, this.setViewport = function(S, z, q, $) { 25302 S.isVector4 ? te.set(S.x, S.y, S.z, S.w) : te.set(S, z, q, $), pe.viewport(X.copy(te).multiplyScalar(Ee).round()); 25303 }
vendor: 6,421 bytes, lines 25303-25433
25303, this.getScissor = function(S) { 25304 return S.copy(ie); 25305 }, this.setScissor = function(S, z, q, $) { 25306 S.isVector4 ? ie.set(S.x, S.y, S.z, S.w) : ie.set(S, z, q, $), pe.scissor(K.copy(ie).multiplyScalar(Ee).round()); 25307 }, this.getScissorTest = function() { 25308 return fe; 25309 }, this.setScissorTest = function(S) { 25310 pe.setScissorTest(fe = S); 25311 }, this.setOpaqueSort = function(S) { 25312 J = S; 25313 }, this.setTransparentSort = function(S) { 25314 le = S; 25315 }, this.getClearColor = function(S) { 25316 return S.copy(_e.getClearColor()); 25317 }, this.setClearColor = function() { 25318 _e.setClearColor(...arguments); 25319 }, this.getClearAlpha = function() { 25320 return _e.getClearAlpha(); 25321 }, this.setClearAlpha = function() { 25322 _e.setClearAlpha(...arguments); 25323 }, this.clear = function(S = !0, z = !0, q = !0) { 25324 let $ = 0; 25325 if (S) { 25326 let j = !1; 25327 if (I !== null) { 25328 const Te = I.texture.format; 25329 j = m.has(Te); 25330 } 25331 if (j) { 25332 const Te = I.texture.type, ue = g.has(Te), ge = _e.getClearColor(), Oe = _e.getClearAlpha(), Be = ge.r, ze = ge.g, rt = ge.b; 25333 ue ? (_[0] = Be, _[1] = ze, _[2] = rt, _[3] = Oe, D.clearBufferuiv(D.COLOR, 0, _)) : (x[0] = Be, x[1] = ze, x[2] = rt, x[3] = Oe, D.clearBufferiv(D.COLOR, 0, x)); 25334 } else 25335 $ |= D.COLOR_BUFFER_BIT; 25336 } 25337 z && ($ |= D.DEPTH_BUFFER_BIT, this.state.buffers.depth.setMask(!0)), q && ($ |= D.STENCIL_BUFFER_BIT, this.state.buffers.stencil.setMask(4294967295)), $ !== 0 && D.clear($); 25338 }, this.clearColor = function() { 25339 this.clear(!0, !1, !1); 25340 }, this.clearDepth = function() { 25341 this.clear(!1, !0, !1); 25342 }, this.clearStencil = function() { 25343 this.clear(!1, !1, !0); 25344 }, this.setNodesHandler = function(S) { 25345 S.setRenderer(this), U = S; 25346 }, this.dispose = function() { 25347 t.removeEventListener("webglcontextlost", ce, !1), t.removeEventListener("webglcontextrestored", Ge, !1), t.removeEventListener("webglcontextcreationerror", it, !1), _e.dispose(), ee.dispose(), Ae.dispose(), A.dispose(), G.dispose(), me.dispose(), ye.dispose(), ne.dispose(), ve.dispose(), be.dispose(), be.removeEventListener("sessionstart", we), be.removeEventListener("sessionend", We), Le.stop(); 25348 }; 25349 function ce(S) { 25350 S.preventDefault(), Xh("WebGLRenderer: Context Lost."), C = !0; 25351 } 25352 function Ge() { 25353 Xh("WebGLRenderer: Context Restored."), C = !1; 25354 const S = At.autoReset, z = xe.enabled, q = xe.autoUpdate, $ = xe.needsUpdate, j = xe.type; 25355 Ne(), At.autoReset = S, xe.enabled = z, xe.autoUpdate = q, xe.needsUpdate = $, xe.type = j; 25356 } 25357 function it(S) { 25358 xt("WebGLRenderer: A WebGL context could not be created. Reason: ", S.statusMessage); 25359 } 25360 function Ft(S) { 25361 const z = S.target; 25362 z.removeEventListener("dispose", Ft), Ct(z); 25363 } 25364 function Ct(S) { 25365 N(S), A.remove(S); 25366 } 25367 function N(S) { 25368 const z = A.get(S).programs; 25369 z !== void 0 && (z.forEach(function(q) { 25370 ve.releaseProgram(q); 25371 }), S.isShaderMaterial && ve.releaseShaderCache(S)); 25372 } 25373 this.renderBufferDirect = function(S, z, q, $, j, Te) { 25374 z === null && (z = lt); 25375 const ue = j.isMesh && j.matrixWorld.determinant() < 0, ge = rn(S, z, q, $, j); 25376 pe.setMaterial($, ue); 25377 let Oe = q.index, Be = 1; 25378 if ($.wireframe === !0) { 25379 if (Oe = oe.getWireframeAttribute(q), Oe === void 0) return; 25380 Be = 2; 25381 } 25382 const ze = q.drawRange, rt = q.attributes.position; 25383 let je = ze.start * Be, Lt = (ze.start + ze.count) * Be; 25384 Te !== null && (je = Math.max(je, Te.start * Be), Lt = Math.min(Lt, (Te.start + Te.count) * Be)), Oe !== null ? (je = Math.max(je, 0), Lt = Math.min(Lt, Oe.count)) : rt != null && (je = Math.max(je, 0), Lt = Math.min(Lt, rt.count)); 25385 const Vt = Lt - je; 25386 if (Vt < 0 || Vt === 1 / 0) return; 25387 ye.setup(j, $, ge, q, Oe); 25388 let Bt, It = nt; 25389 if (Oe !== null && (Bt = Q.get(Oe), It = gt, It.setIndex(Bt)), j.isMesh) 25390 $.wireframe === !0 ? (pe.setLineWidth($.wireframeLinewidth * Tt()), It.setMode(D.LINES)) : It.setMode(D.TRIANGLES); 25391 else if (j.isLine) { 25392 let ln = $.linewidth; 25393 ln === void 0 && (ln = 1), pe.setLineWidth(ln * Tt()), j.isLineSegments ? It.setMode(D.LINES) : j.isLineLoop ? It.setMode(D.LINE_LOOP) : It.setMode(D.LINE_STRIP); 25394 } else j.isPoints ? It.setMode(D.POINTS) : j.isSprite && It.setMode(D.TRIANGLES); 25395 if (j.isBatchedMesh) 25396 if (Qe.get("WEBGL_multi_draw")) 25397 It.renderMultiDraw(j._multiDrawStarts, j._multiDrawCounts, j._multiDrawCount); 25398 else { 25399 const ln = j._multiDrawStarts, ke = j._multiDrawCounts, Tn = j._multiDrawCount, St = Oe ? Q.get(Oe).bytesPerElement : 1, On = A.get($).currentProgram.getUniforms(); 25400 for (let ri = 0; ri < Tn; ri++) 25401 On.setValue(D, "_gl_DrawID", ri), It.render(ln[ri] / St, ke[ri]); 25402 } 25403 else if (j.isInstancedMesh) 25404 It.renderInstances(je, Vt, j.count); 25405 else if (q.isInstancedBufferGeometry) { 25406 const ln = q._maxInstanceCount !== void 0 ? q._maxInstanceCount : 1 / 0, ke = Math.min(q.instanceCount, ln); 25407 It.renderInstances(je, Vt, ke); 25408 } else 25409 It.render(je, Vt); 25410 }; 25411 function B(S, z, q) { 25412 S.transparent === !0 && S.side === Ni && S.forceSinglePass === !1 ? (S.side = Mn, S.needsUpdate = !0, ft(S, z, q), S.side = sr, S.needsUpdate = !0, ft(S, z, q), S.side = Ni) : ft(S, z, q); 25413 } 25414 this.compile = function(S, z, q = null) { 25415 q === null && (q = S), T = Ae.get(q), T.init(z), y.push(T), q.traverseVisible(function(j) { 25416 j.isLight && j.layers.test(z.layers) && (T.pushLight(j), j.castShadow && T.pushShadow(j)); 25417 }), S !== q && S.traverseVisible(function(j) { 25418 j.isLight && j.layers.test(z.layers) && (T.pushLight(j), j.castShadow && T.pushShadow(j)); 25419 }), T.setupLights(); 25420 const $ = /* @__PURE__ */ new Set(); 25421 return S.traverse(function(j) { 25422 if (!(j.isMesh || j.isPoints || j.isLine || j.isSprite)) 25423 return; 25424 const Te = j.material; 25425 if (Te) 25426 if (Array.isArray(Te)) 25427 for (let ue = 0; ue < Te.length; ue++) { 25428 const ge = Te[ue]; 25429 B(ge, q, j), $.add(ge); 25430 } 25431 else 25432 B(Te, q, j), $.add(Te); 25433 }), T = y.pop(), $;
25434 }, this.compileAsync = function(S, z, q = null) { 25435 const $ = this.compile(S, z, q); 25436 return new Promise((j) => { 25437 function Te() { 25438 if ($.forEach(function(ue) { 25439 A.get(ue).currentProgram.isReady() && $.delete(ue); 25440 }), $.size === 0) { 25441 j(S); 25442 return; 25443 } 25444 setTimeout(Te, 10); 25445 } 25446 Qe.get("KHR_parallel_shader_compile") !== null ? Te() : setTimeout(Te, 10); 25447 }); 25448 }; 25449 let Y = null; 25450 function de(S) { 25451 Y && Y(S); 25452 } 25453 function we() { 25454 Le.stop(); 25455 } 25456 function We() { 25457 Le.start(); 25458 } 25459 const Le = new qp(); 25460 Le.setAnimationLoop(de), typeof self < "u" && Le.setContext(self), this.setAnimationLoop = function(S) { 25461 Y = S, be.setAnimationLoop(S), S === null ? Le.stop() : Le.start(); 25462 }, be.addEventListener("sessionstart", we), be.addEventListener("sessionend", We), this.render = function(S, z) { 25463 if (z !== void 0 && z.isCamera !== !0) { 25464 xt("WebGLRenderer.render: camera is not an instance of THREE.Camera."); 25465 return; 25466 } 25467 if (C === !0) return; 25468 U !== null && U.renderStart(S, z); 25469 const q = be.enabled === !0 && be.isPresenting === !0, $ = M !== null && (I === null || q) && M.begin(L, I); 25470 if (S.matrixWorldAutoUpdate === !0 && S.updateMatrixWorld(), z.parent === null && z.matrixWorldAutoUpdate === !0 && z.updateMatrixWorld(), be.enabled === !0 && be.isPresenting === !0 && (M === null || M.isCompositing() === !1) && (be.cameraAutoUpdate === !0 && be.updateCamera(z), z = be.getCamera()), S.isScene === !0 && S.onBeforeRender(L, S, z, I), T = Ae.get(S, y.length), T.init(z), T.state.textureUnits = b.getTextureUnits(), y.push(T), Ke.multiplyMatrices(z.projectionMatrix, z.matrixWorldInverse), Se.setFromProjectionMatrix(Ke, ui, z.reversedDepth), Me = this.localClippingEnabled, Fe = De.init(this.clippingPlanes, Me), R = ee.get(S, w.length), R.init(), w.push(R), be.enabled === !0 && be.isPresenting === !0) { 25471 const ue = L.xr.getDepthSensingMesh(); 25472 ue !== null && Ve(ue, z, -1 / 0, L.sortObjects); 25473 } 25474 Ve(S, z, 0, L.sortObjects), R.finish(), L.sortObjects === !0 && R.sort(J, le), ut = be.enabled === !1 || be.isPresenting === !1 || be.hasDepthSensing() === !1, ut && _e.addToRenderList(R, S), this.info.render.frame++, Fe === !0 && De.beginShadows(); 25475 const j = T.state.shadowsArray; 25476 if (xe.render(j, S, z), Fe === !0 && De.endShadows(), this.info.autoReset === !0 && this.info.reset(), ($ && M.hasRenderPass()) === !1) { 25477 const ue = R.opaque, ge = R.transmissive; 25478 if (T.setupLights(), z.isArrayCamera) { 25479 const Oe = z.cameras; 25480 if (ge.length > 0) 25481 for (let Be = 0, ze = Oe.length; Be < ze; Be++) { 25482 const rt = Oe[Be]; 25483 Ye(ue, ge, S, rt); 25484 } 25485 ut && _e.render(S); 25486 for (let Be = 0, ze = Oe.length; Be < ze; Be++) { 25487 const rt = Oe[Be]; 25488 $e(R, S, rt, rt.viewport); 25489 } 25490 } else 25491 ge.length > 0 && Ye(ue, ge, S, z), ut && _e.render(S), $e(R, S, z); 25492 } 25493 I !== null && F === 0 && (b.updateMultisampleRenderTarget(I), b.updateRenderTargetMipmap(I)), $ && M.end(L), S.isScene === !0 && S.onAfterRender(L, S, z), ye.resetDefaultState(), k = -1, H = null, y.pop(), y.length > 0 ? (T = y[y.length - 1], b.setTextureUnits(T.state.textureUnits), Fe === !0 && De.setGlobalState(L.clippingPlanes, T.state.camera)) : T = null, w.pop(), w.length > 0 ? R = w[w.length - 1] : R = null, U !== null && U.renderEnd(); 25494 }; 25495 function Ve(S, z, q, $) { 25496 if (S.visible === !1) return; 25497 if (S.layers.test(z.layers)) { 25498 if (S.isGroup) 25499 q = S.renderOrder; 25500 else if (S.isLOD) 25501 S.autoUpdate === !0 && S.update(z); 25502 else if (S.isLightProbeGrid) 25503 T.pushLightProbeGrid(S); 25504 else if (S.isLight) 25505 T.pushLight(S), S.castShadow && T.pushShadow(S); 25506 else if (S.isSprite) { 25507 if (!S.frustumCulled || Se.intersectsSprite(S)) { 25508 $ && Ue.setFromMatrixPosition(S.matrixWorld).applyMatrix4(Ke); 25509 const ue = me.update(S), ge = S.material; 25510 ge.visible && R.push(S, ue, ge, q, Ue.z, null); 25511 } 25512 } else if ((S.isMesh || S.isLine || S.isPoints) && (!S.frustumCulled || Se.intersectsObject(S))) { 25513 const ue = me.update(S), ge = S.material; 25514 if ($ && (S.boundingSphere !== void 0 ? (S.boundingSphere === null && S.computeBoundingSphere(), Ue.copy(S.boundingSphere.center)) : (ue.boun
vendor: 4,212 bytes, lines 25514-25581
25514dingSphere === null && ue.computeBoundingSphere(), Ue.copy(ue.boundingSphere.center)), Ue.applyMatrix4(S.matrixWorld).applyMatrix4(Ke)), Array.isArray(ge)) { 25515 const Oe = ue.groups; 25516 for (let Be = 0, ze = Oe.length; Be < ze; Be++) { 25517 const rt = Oe[Be], je = ge[rt.materialIndex]; 25518 je && je.visible && R.push(S, ue, je, q, Ue.z, rt); 25519 } 25520 } else ge.visible && R.push(S, ue, ge, q, Ue.z, null); 25521 } 25522 } 25523 const Te = S.children; 25524 for (let ue = 0, ge = Te.length; ue < ge; ue++) 25525 Ve(Te[ue], z, q, $); 25526 } 25527 function $e(S, z, q, $) { 25528 const { opaque: j, transmissive: Te, transparent: ue } = S; 25529 T.setupLightsView(q), Fe === !0 && De.setGlobalState(L.clippingPlanes, q), $ && pe.viewport(X.copy($)), j.length > 0 && Je(j, z, q), Te.length > 0 && Je(Te, z, q), ue.length > 0 && Je(ue, z, q), pe.buffers.depth.setTest(!0), pe.buffers.depth.setMask(!0), pe.buffers.color.setMask(!0), pe.setPolygonOffset(!1); 25530 } 25531 function Ye(S, z, q, $) { 25532 if ((q.isScene === !0 ? q.overrideMaterial : null) !== null) 25533 return; 25534 if (T.state.transmissionRenderTarget[$.id] === void 0) { 25535 const je = Qe.has("EXT_color_buffer_half_float") || Qe.has("EXT_color_buffer_float"); 25536 T.state.transmissionRenderTarget[$.id] = new fi(1, 1, { 25537 generateMipmaps: !0, 25538 type: je ? ki : Pn, 25539 minFilter: Mr, 25540 samples: Math.max(4, dt.samples), 25541 // to avoid feedback loops, the transmission render target requires a resolve, see #26177 25542 stencilBuffer: s, 25543 resolveDepthBuffer: !1, 25544 resolveStencilBuffer: !1, 25545 colorSpace: _t.workingColorSpace 25546 }); 25547 } 25548 const Te = T.state.transmissionRenderTarget[$.id], ue = $.viewport || X; 25549 Te.setSize(ue.z * L.transmissionResolutionScale, ue.w * L.transmissionResolutionScale); 25550 const ge = L.getRenderTarget(), Oe = L.getActiveCubeFace(), Be = L.getActiveMipmapLevel(); 25551 L.setRenderTarget(Te), L.getClearColor(se), he = L.getClearAlpha(), he < 1 && L.setClearColor(16777215, 0.5), L.clear(), ut && _e.render(q); 25552 const ze = L.toneMapping; 25553 L.toneMapping = di; 25554 const rt = $.viewport; 25555 if ($.viewport !== void 0 && ($.viewport = void 0), T.setupLightsView($), Fe === !0 && De.setGlobalState(L.clippingPlanes, $), Je(S, q, $), b.updateMultisampleRenderTarget(Te), b.updateRenderTargetMipmap(Te), Qe.has("WEBGL_multisampled_render_to_texture") === !1) { 25556 let je = !1; 25557 for (let Lt = 0, Vt = z.length; Lt < Vt; Lt++) { 25558 const Bt = z[Lt], { object: It, geometry: ln, material: ke, group: Tn } = Bt; 25559 if (ke.side === Ni && It.layers.test($.layers)) { 25560 const St = ke.side; 25561 ke.side = Mn, ke.needsUpdate = !0, qe(It, q, $, ln, ke, Tn), ke.side = St, ke.needsUpdate = !0, je = !0; 25562 } 25563 } 25564 je === !0 && (b.updateMultisampleRenderTarget(Te), b.updateRenderTargetMipmap(Te)); 25565 } 25566 L.setRenderTarget(ge, Oe, Be), L.setClearColor(se, he), rt !== void 0 && ($.viewport = rt), L.toneMapping = ze; 25567 } 25568 function Je(S, z, q) { 25569 const $ = z.isScene === !0 ? z.overrideMaterial : null; 25570 for (let j = 0, Te = S.length; j < Te; j++) { 25571 const ue = S[j], { object: ge, geometry: Oe, group: Be } = ue; 25572 let ze = ue.material; 25573 ze.allowOverride === !0 && $ !== null && (ze = $), ge.layers.test(q.layers) && qe(ge, z, q, Oe, ze, Be); 25574 } 25575 } 25576 function qe(S, z, q, $, j, Te) { 25577 S.onBeforeRender(L, z, q, $, j, Te), S.modelViewMatrix.multiplyMatrices(q.matrixWorldInverse, S.matrixWorld), S.normalMatrix.getNormalMatrix(S.modelViewMatrix), j.onBeforeRender(L, z, q, $, S, Te), j.transparent === !0 && j.side === Ni && j.forceSinglePass === !1 ? (j.side = Mn, j.needsUpdate = !0, L.renderBufferDirect(q, z, $, j, S, Te), j.side = sr, j.needsUpdate = !0, L.renderBufferDirect(q, z, $, j, S, Te), j.side = Ni) : L.renderBufferDirect(q, z, $, j, S, Te), S.onAfterRender(L, z, q, $, j, Te); 25578 } 25579 function ft(S, z, q) { 25580 z.isScene !== !0 && (z = lt); 25581 const $ = A.get(S), j = T.state.lights, Te = T.state.shadowsArray, ue = j.state.ver
25581sion, ge = ve.getParameters(S, j.state, Te, z, q, T.state.lightProbeGridArray), Oe = ve.getProgramCacheKey(ge); 25582 let Be = $.programs; 25583 $.environment = S.isMeshStandardMaterial || S.isMeshLambertMaterial || S.isMeshPhongMaterial ? z.environment : null, $.fog = z.fog; 25584 const ze = S.isMeshStandardMaterial || S.isMeshLambertMaterial && !S.envMap || S.isMeshPhongMaterial && !S.envMap; 25585 $.envMap = G.get(S.envMap || $.environment, ze), $.envMapRotation = $.environment !== null && S.envMap === null ? z.environmentRotation : S.envMapRotation, Be === void 0 && (S.addEventListener("dispose", Ft), Be = /* @__PURE__ */ new Map(), $.programs = Be); 25586 let rt = Be.get(Oe); 25587 if (rt !== void 0) { 25588 if ($.currentProgram === rt && $.lightsStateVersion === ue) 25589 return Xt(S, ge), rt; 25590 } else 25591 ge.uniforms = ve.getUniforms(S), U !== null && S.isNodeMaterial && U.build(S, q, ge), S.onBeforeCompile(ge, L), rt = ve.acquireProgram(ge, Oe), Be.set(Oe, rt), $.uniforms = ge.uniforms; 25592 const je = $.uniforms; 25593 return (!S.isShaderMaterial && !S.isRawShaderMaterial || S.clipping === !0) && (je.clippingPlanes = De.uniform), Xt(S, ge), $.needsLights = bn(S), $.lightsStateVersion = ue, $.needsLights && (je.ambientLightColor.value = j.state.ambient, je.lightProbe.value = j.state.probe, je.directionalLights.value = j.state.directional, je.directionalLightShadows.value = j.state.directionalShadow, je.spotLights.value = j.state.spot, je.spotLightShadows.value = j.state.spotShadow, je.rectAreaLights.value = j.state.rectArea, je.ltc_1.value = j.state.rectAreaLTC1, je.ltc_2.value = j.state.rectAreaLTC2, je.pointLights.value = j.state.point, je.pointLightShadows.value = j.state.pointShadow, je.hemisphereLights.value = j.state.hemi, je.directionalShadowMatrix.value = j.state.directionalShadowMatrix, je.spotLightMatrix.value = j.state.spotLightMatrix, je.spotLightMap.value = j.state.spotLightMap, je.pointShadowMatrix.value = j.state.pointShadowMatrix), $.lightProbeGrid = T.state.lightProbeGridArray.length > 0, $.currentProgram = rt, $.uniformsList = null, rt; 25594 } 25595 function vt(S) { 25596 if (S.uniformsList === null) { 25597 const z = S.currentProgram.getUniforms(); 25598 S.uniformsList = So.seqWithValue(z.seq, S.uniforms); 25599 } 25600 return S.uniformsList; 25601 } 25602 function Xt(S, z) { 25603 const q = A.get(S); 25604 q.outputColorSpace = z.outputColorSpace, q.batching = z.batching, q.batchingColor = z.batchingColor, q.instancing = z.instancing, q.instancingColor = z.instancingColor, q.instancingMorph = z.instancingMorph, q.skinning = z.skinning, q.morphTargets = z.morphTargets, q.morphNormals = z.morphNormals, q.morphColors = z.morphColors, q.morphTargetsCount = z.morphTargetsCount, q.numClippingPlanes = z.numClippingPlanes, q.numIntersection = z.numClipIntersection, q.vertexAlphas = z.vertexAlphas, q.vertexTangents = z.vertexTangents, q.toneMapping = z.toneMapping; 25605 } 25606 function qt(S, z) { 25607 if (S.length === 0) return null; 25608 if (S.length === 1) 25609 return S[0].texture !== null ? S[0] : null; 25610 E.setFromMatrixPosition(z.matrixWorld); 25611 for (let q = 0, $ = S.length; q < $; q++) { 25612 const j = S[q]; 25613 if (j.texture !== null && j.boundingBox.containsPoint(E)) return j; 25614 } 25615 return null; 25616 } 25617 function rn(S, z, q, $, j) { 25618 z.isScene !== !0 && (z = lt), b.resetTextureUnits(); 25619 const Te = z.fog, ue = $.isMeshStandardMaterial || $.isMeshLambertMaterial || $.isMeshPhongMaterial ? z.environment : null, ge = I === null ? L.outputColorSpace : I.isXRRenderTarget === !0 ? I.texture.colorSpace : _t.workingColorSpace, Oe = $.isMeshStandardMaterial || $.isMeshLambertMaterial && !$.envMap || $.isMeshPhongMaterial && !$.envMap, Be = G.get($.envMap || ue, Oe), ze = $.vertexColors === !0 && !!q.attributes.color && q.attributes.color.itemSize === 4, rt = !!q.attributes.tangent && (!!$.normalMap || $.anisotropy > 0), je = !!q.morphAttributes.position, Lt = !!q.morphAttributes.normal, Vt = !!q.morphAttributes.color; 25620 let Bt = di; 25621 $.toneMapped && (I === null || I.isXRRenderTarget === !0) && (Bt = L.toneMapping); 25622 const It = q.morphAttributes.position || q.morphAttributes.normal || q.morphAttributes.color, ln = It !== void 0 ? It.length : 0, ke = A.get($), Tn = T.state.lights; 25623 if (Fe === !0 && (Me === !0 || S !== H)) { 25624 const Ut = S === H && $.id === k; 25625 De.setState($, S, Ut); 25626 } 25627 let St = !1; 25628 $.version === ke.__version ? (ke.needsLights && ke.lightsStateVersion !== Tn.state.ver
vendor: 5,008 bytes, lines 25628-25663
25628sion || ke.outputColorSpace !== ge || j.isBatchedMesh && ke.batching === !1 || !j.isBatchedMesh && ke.batching === !0 || j.isBatchedMesh && ke.batchingColor === !0 && j.colorTexture === null || j.isBatchedMesh && ke.batchingColor === !1 && j.colorTexture !== null || j.isInstancedMesh && ke.instancing === !1 || !j.isInstancedMesh && ke.instancing === !0 || j.isSkinnedMesh && ke.skinning === !1 || !j.isSkinnedMesh && ke.skinning === !0 || j.isInstancedMesh && ke.instancingColor === !0 && j.instanceColor === null || j.isInstancedMesh && ke.instancingColor === !1 && j.instanceColor !== null || j.isInstancedMesh && ke.instancingMorph === !0 && j.morphTexture === null || j.isInstancedMesh && ke.instancingMorph === !1 && j.morphTexture !== null || ke.envMap !== Be || $.fog === !0 && ke.fog !== Te || ke.numClippingPlanes !== void 0 && (ke.numClippingPlanes !== De.numPlanes || ke.numIntersection !== De.numIntersection) || ke.vertexAlphas !== ze || ke.vertexTangents !== rt || ke.morphTargets !== je || ke.morphNormals !== Lt || ke.morphColors !== Vt || ke.toneMapping !== Bt || ke.morphTargetsCount !== ln || !!ke.lightProbeGrid != T.state.lightProbeGridArray.length > 0) && (St = !0) : (St = !0, ke.__version = $.version); 25629 let On = ke.currentProgram; 25630 St === !0 && (On = ft($, z, j), U && $.isNodeMaterial && U.onUpdateProgram($, On, ke)); 25631 let ri = !1, Bi = !1, Ur = !1; 25632 const Dt = On.getUniforms(), Wt = ke.uniforms; 25633 if (pe.useProgram(On.program) && (ri = !0, Bi = !0, Ur = !0), $.id !== k && (k = $.id, Bi = !0), ke.needsLights) { 25634 const Ut = qt(T.state.lightProbeGridArray, j); 25635 ke.lightProbeGrid !== Ut && (ke.lightProbeGrid = Ut, Bi = !0); 25636 } 25637 if (ri || H !== S) { 25638 pe.buffers.depth.getReversed() && S.reversedDepth !== !0 && (S._reversedDepth = !0, S.updateProjectionMatrix()), Dt.setValue(D, "projectionMatrix", S.projectionMatrix), Dt.setValue(D, "viewMatrix", S.matrixWorldInverse); 25639 const Hi = Dt.map.cameraPosition; 25640 Hi !== void 0 && Hi.setValue(D, at.setFromMatrixPosition(S.matrixWorld)), dt.logarithmicDepthBuffer && Dt.setValue( 25641 D, 25642 "logDepthBufFC", 25643 2 / (Math.log(S.far + 1) / Math.LN2) 25644 ), ($.isMeshPhongMaterial || $.isMeshToonMaterial || $.isMeshLambertMaterial || $.isMeshBasicMaterial || $.isMeshStandardMaterial || $.isShaderMaterial) && Dt.setValue(D, "isOrthographic", S.isOrthographicCamera === !0), H !== S && (H = S, Bi = !0, Ur = !0); 25645 } 25646 if (ke.needsLights && (Tn.state.directionalShadowMap.length > 0 && Dt.setValue(D, "directionalShadowMap", Tn.state.directionalShadowMap, b), Tn.state.spotShadowMap.length > 0 && Dt.setValue(D, "spotShadowMap", Tn.state.spotShadowMap, b), Tn.state.pointShadowMap.length > 0 && Dt.setValue(D, "pointShadowMap", Tn.state.pointShadowMap, b)), j.isSkinnedMesh) { 25647 Dt.setOptional(D, j, "bindMatrix"), Dt.setOptional(D, j, "bindMatrixInverse"); 25648 const Ut = j.skeleton; 25649 Ut && (Ut.boneTexture === null && Ut.computeBoneTexture(), Dt.setValue(D, "boneTexture", Ut.boneTexture, b)); 25650 } 25651 j.isBatchedMesh && (Dt.setOptional(D, j, "batchingTexture"), Dt.setValue(D, "batchingTexture", j._matricesTexture, b), Dt.setOptional(D, j, "batchingIdTexture"), Dt.setValue(D, "batchingIdTexture", j._indirectTexture, b), Dt.setOptional(D, j, "batchingColorTexture"), j._colorsTexture !== null && Dt.setValue(D, "batchingColorTexture", j._colorsTexture, b)); 25652 const zi = q.morphAttributes; 25653 if ((zi.position !== void 0 || zi.normal !== void 0 || zi.color !== void 0) && et.update(j, q, On), (Bi || ke.receiveShadow !== j.receiveShadow) && (ke.receiveShadow = j.receiveShadow, Dt.setValue(D, "receiveShadow", j.receiveShadow)), ($.isMeshStandardMaterial || $.isMeshLambertMaterial || $.isMeshPhongMaterial) && $.envMap === null && z.environment !== null && (Wt.envMapIntensity.value = z.environmentIntensity), Wt.dfgLUT !== void 0 && (Wt.dfgLUT.value = iE()), Bi) { 25654 if (Dt.setValue(D, "toneMappingExposure", L.toneMappingExposure), ke.needsLights && Pt(Wt, Ur), Te && $.fog === !0 && Z.refreshFogUniforms(Wt, Te), Z.refreshMaterialUniforms(Wt, $, Ee, Ie, T.state.transmissionRenderTarget[S.id]), ke.needsLights && ke.lightProbeGrid) { 25655 const Ut = ke.lightProbeGrid; 25656 Wt.probesSH.value = Ut.texture, Wt.probesMin.value.copy(Ut.boundingBox.min), Wt.probesMax.value.copy(Ut.boundingBox.max), Wt.probesResolution.value.copy(Ut.resolution); 25657 } 25658 So.upload(D, vt(ke), Wt, b); 25659 } 25660 if ($.isShaderMaterial && $.uniformsNeedUpdate === !0 && (So.upload(D, vt(ke), Wt, b), $.uniformsNeedUpdate = !1), $.isSpriteMaterial && Dt.setValue(D, "center", j.center), Dt.setValue(D, "modelViewMatrix", j.modelViewMatrix), Dt.setValue(D, "normalMatrix", j.normalMatrix), Dt.setValue(D, "modelMatrix", j.matrixWorld), $.uniformsGroups !== void 0) { 25661 const Ut = $.uniformsGroups; 25662 for (let Hi = 0, Or = Ut.length; Hi < Or; Hi++) { 25663 const ch = Ut[Hi];
25664 ne.update(ch, On), ne.bind(ch, On); 25665 } 25666 } 25667 return On; 25668 } 25669 function Pt(S, z) { 25670 S.ambientLightColor.needsUpdate = z, S.lightProbe.needsUpdate = z, S.directionalLights.needsUpdate = z, S.directionalLightShadows.needsUpdate = z, S.pointLights.needsUpdate = z, S.pointLightShadows.needsUpdate = z, S.spotLights.needsUpdate = z, S.spotLightShadows.needsUpdate = z, S.rectAreaLights.needsUpdate = z, S.hemisphereLights.needsUpdate = z; 25671 } 25672 function bn(S) { 25673 return S.isMeshLambertMaterial || S.isMeshToonMaterial || S.isMeshPhongMaterial || S.isMeshStandardMaterial || S.isShadowMaterial || S.isShaderMaterial && S.lights === !0; 25674 } 25675 this.getActiveCubeFace = function() { 25676 return V; 25677 }, this.getActiveMipmapLevel = function() { 25678 return F; 25679 }, this.getRenderTarget = function() { 25680 return I; 25681 }, this.setRenderTargetTextures = function(S, z, q) { 25682 const $ = A.get(S); 25683 $.__autoAllocateDepthBuffer = S.resolveDepthBuffer === !1, $.__autoAllocateDepthBuffer === !1 && ($.__useRenderToTexture = !1), A.get(S.texture).__webglTexture = z, A.get(S.depthTexture).__webglTexture = $.__autoAllocateDepthBuffer ? void 0 : q, $.__hasExternalTextures = !0; 25684 }, this.setRenderTargetFramebuffer = function(S, z) { 25685 const q = A.get(S); 25686 q.__webglFramebuffer = z, q.__useDefaultFramebuffer = z === void 0; 25687 }; 25688 const bi = D.createFramebuffer(); 25689 this.setRenderTarget = function(S, z = 0, q = 0) { 25690 I = S, V = z, F = q; 25691 let $ = null, j = !1, Te = !1; 25692 if (S) { 25693 const ge = A.get(S); 25694 if (ge.__useDefaultFramebuffer !== void 0) { 25695 pe.bindFramebuffer(D.FRAMEBUFFER, ge.__webglFramebuffer), X.copy(S.viewport), K.copy(S.scissor), ae = S.scissorTest, pe.viewport(X), pe.scissor(K), pe.setScissorTest(ae), k = -1; 25696 return; 25697 } else if (ge.__webglFramebuffer === void 0) 25698 b.setupRenderTarget(S); 25699 else if (ge.__hasExternalTextures) 25700 b.rebindTextures(S, A.get(S.texture).__webglTexture, A.get(S.depthTexture).__webglTexture); 25701 else if (S.depthBuffer) { 25702 const ze = S.depthTexture; 25703 if (ge.__boundDepthTexture !== ze) { 25704 if (ze !== null && A.has(ze) && (S.width !== ze.image.width || S.height !== ze.image.height)) 25705 throw new Error("WebGLRenderTarget: Attached DepthTexture is initialized to the incorrect size."); 25706 b.setupDepthRenderbuffer(S); 25707 } 25708 } 25709 const Oe = S.texture; 25710 (Oe.isData3DTexture || Oe.isDataArrayTexture || Oe.isCompressedArrayTexture) && (Te = !0); 25711 const Be = A.get(S).__webglFramebuffer; 25712 S.isWebGLCubeRenderTarget ? (Array.isArray(Be[z]) ? $ = Be[z][q] : $ = Be[z], j = !0) : S.samples > 0 && b.useMultisampledRTT(S) === !1 ? $ = A.get(S).__webglMultisampledFramebuffer : Array.isArray(Be) ? $ = Be[q] : $ = Be, X.copy(S.viewport), K.copy(S.scissor), ae = S.scissorTest; 25713 } else 25714 X.copy(te).multiplyScalar(Ee).floor(), K.copy(ie).multiplyScalar(Ee).floor(), ae = fe; 25715 if (q !== 0 && ($ = bi), pe.bindFramebuffer(D.FRAMEBUFFER, $) && pe.drawBuffers(S, $), pe.viewport(X), pe.scissor(K), pe.setScissorTest(ae), j) { 25716 const ge = A.get(S.texture); 25717 D.framebufferTexture2D(D.FRAMEBUFFER, D.COLOR_ATTACHMENT0, D.TEXTURE_CUBE_MAP_POSITIVE_X + z, ge.__webglTexture, q); 25718 } else if (Te) { 25719 const ge = z; 25720 for (let Oe = 0; Oe < S.textures.length; Oe++) { 25721 const Be = A.get(S.textures[Oe]); 25722 D.framebufferTextureLayer(D.FRAMEBUFFER, D.COLOR_ATTACHMENT0 + Oe, Be.__webglTexture, q, ge); 25723 } 25724 } else if (S !== null && q !== 0) { 25725 const ge = A.get(S.texture); 25726 D.framebufferTexture2D(D.FRAMEBUFFER, D.COLOR_ATTACHMENT0, D.TEXTURE_2D, ge.__webglTexture, q); 25727 } 25728 k = -1; 25729 }, this.readRenderTargetPixels = function(S, z, q, $, j, Te, ue, ge = 0) { 25730 if (!(S && S.isWebGLRenderTarget)) { 25731 xt("WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); 25732 return; 25733 } 25734 let Oe = A.get(S).__webglFramebuffer;
25735 if (S.isWebGLCubeRenderTarget && ue !== void 0 && (Oe = Oe[ue]), Oe) { 25736 pe.bindFramebuffer(D.FRAMEBUFFER, Oe); 25737 try { 25738 const Be = S.textures[ge], ze = Be.format, rt = Be.type; 25739 if (S.textures.length > 1 && D.readBuffer(D.COLOR_ATTACHMENT0 + ge), !dt.textureFormatReadable(ze)) { 25740 xt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in RGBA or implementation defined format."); 25741 return; 25742 } 25743 if (!dt.textureTypeReadable(rt)) { 25744 xt("WebGLRenderer.readRenderTargetPixels: renderTarget is not in UnsignedByteType or implementation defined type."); 25745 return; 25746 } 25747 z >= 0 && z <= S.width - $ && q >= 0 && q <= S.height - j && D.readPixels(z, q, $, j, O.convert(ze), O.convert(rt), Te); 25748 } finally { 25749 const Be = I !== null ? A.get(I).__webglFramebuffer : null; 25750 pe.bindFramebuffer(D.FRAMEBUFFER, Be); 25751 } 25752 } 25753 }, this.readRenderTargetPixelsAsync = async function(S, z, q, $, j, Te, ue, ge = 0) { 25754 if (!(S && S.isWebGLRenderTarget)) 25755 throw new Error("THREE.WebGLRenderer.readRenderTargetPixels: renderTarget is not THREE.WebGLRenderTarget."); 25756 let Oe = A.get(S).__webglFramebuffer; 25757 if (S.isWebGLCubeRenderTarget && ue !== void 0 && (Oe = Oe[ue]), Oe) 25758 if (z >= 0 && z <= S.width - $ && q >= 0 && q <= S.height - j) { 25759 pe.bindFramebuffer(D.FRAMEBUFFER, Oe); 25760 const Be = S.textures[ge], ze = Be.format, rt = Be.type; 25761 if (S.textures.length > 1 && D.readBuffer(D.COLOR_ATTACHMENT0 + ge), !dt.textureFormatReadable(ze)) 25762 throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in RGBA or implementation defined format."); 25763 if (!dt.textureTypeReadable(rt)) 25764 throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: renderTarget is not in UnsignedByteType or implementation defined type."); 25765 const je = D.createBuffer(); 25766 D.bindBuffer(D.PIXEL_PACK_BUFFER, je), D.bufferData(D.PIXEL_PACK_BUFFER, Te.byteLength, D.STREAM_READ), D.readPixels(z, q, $, j, O.convert(ze), O.convert(rt), 0); 25767 const Lt = I !== null ? A.get(I).__webglFramebuffer : null; 25768 pe.bindFramebuffer(D.FRAMEBUFFER, Lt); 25769 const Vt = D.fenceSync(D.SYNC_GPU_COMMANDS_COMPLETE, 0); 25770 return D.flush(), await E_(D, Vt, 4), D.bindBuffer(D.PIXEL_PACK_BUFFER, je), D.getBufferSubData(D.PIXEL_PACK_BUFFER, 0, Te), D.deleteBuffer(je), D.deleteSync(Vt), Te; 25771 } else 25772 throw new Error("THREE.WebGLRenderer.readRenderTargetPixelsAsync: requested read bounds are out of range."); 25773 }, this.copyFramebufferToTexture = function(S, z = null, q = 0) { 25774 const $ = Math.pow(2, -q), j = Math.floor(S.image.width * $), Te = Math.floor(S.image.height * $), ue = z !== null ? z.x : 0, ge = z !== null ? z.y : 0; 25775 b.setTexture2D(S, 0), D.copyTexSubImage2D(D.TEXTURE_2D, q, 0, 0, ue, ge, j, Te), pe.unbindTexture(); 25776 }; 25777 const dr = D.createFramebuffer(), ii = D.createFramebuffer(); 25778 this.copyTextureToTexture = function(S, z, q = null, $ = null, j = 0, Te = 0) { 25779 let ue, ge, Oe, Be, ze, rt, je, Lt, Vt; 25780 const Bt = S.isCompressedTexture ? S.mipmaps[Te] : S.image; 25781 if (q !== null) 25782 ue = q.max.x - q.min.x, ge = q.max.y - q.min.y, Oe = q.isBox3 ? q.max.z - q.min.z : 1, Be = q.min.x, ze = q.min.y, rt = q.isBox3 ? q.min.z : 0; 25783 else { 25784 const Wt = Math.pow(2, -j); 25785 ue = Math.floor(Bt.width * Wt), ge = Math.floor(Bt.height * Wt), S.isDataArrayTexture ? Oe = Bt.depth : S.isData3DTexture ? Oe = Math.floor(Bt.depth * Wt) : Oe = 1, Be = 0, ze = 0, rt = 0; 25786 } 25787 $ !== null ? (je = $.x, Lt = $.y, Vt = $.z) : (je = 0, Lt = 0, Vt = 0); 25788 const It = O.convert(z.format), ln = O.convert(z.type); 25789 let ke; 25790 z.isData3DTexture ? (b.setTexture3D(z, 0), ke = D.TEXTURE_3D) : z.isDataArrayTexture || z.isCompressedArrayTexture ? (b.setTexture2DArray(z, 0), ke = D.TEXTURE_2D_ARRAY) : (b.setTexture2D(z, 0), ke = D.TEXTURE_2D), pe.activeTexture(D.TEXTURE0), pe.pixelStorei(D.UNPACK_FLIP_Y_WEBGL, z.flipY), pe.pixelStorei(D.UNPACK_PREMULTIPLY_ALPHA_WEBGL, z.premultiplyAlpha), pe.pixelStorei(D.UNPACK_ALIGNMENT, z.unpackAlignment); 25791 const Tn = pe.getParameter(D.UNPACK_ROW_LENGTH), St = pe.getParameter(D.UNPACK_IMAGE_HEIGHT), On = pe.getParameter(D.UNPACK_SKIP_PIXELS), ri = pe.getParameter(D.UNPACK_SKIP_ROWS), Bi = pe.getParameter(D.UNPACK_SKIP_IMAGES); 25792 pe.pixelStorei(D.UNPACK_ROW_LENGTH, Bt.width), pe.pixelStorei(D.UNPACK_IMAGE_HEIGHT, Bt.height), pe.pixelStorei(D.UNPACK_SKIP_PIXELS, Be), pe.pixelStorei(D.UNPACK_SKIP_ROWS, ze), pe.pixelStorei(D.UNPACK_SKIP_IMAGES, rt); 25793 const Ur = S.isDataArrayTexture || S.isData3DTexture, Dt = z.isDataArrayTexture || z.isData3DTexture; 25794 if (S.isDepthTexture) { 25795 const Wt = A.get(S), zi = A.get(z), Ut = A.get(Wt.__renderTarget), Hi = A.get(zi.__renderTarget); 25796 pe.bindFramebuffer(D.READ_FRAMEBUFFER, Ut.__webglFramebuffer), pe.bindFramebuffer(D.DRAW_FRAMEBUFFER, Hi.__webglFramebuffer); 25797 for (let Or = 0; Or < Oe; Or++) 25798 Ur && (D.framebufferTextureLayer(D.READ_FRAMEBUFFER, D.COLOR_ATTACHMENT0, A.get(S).__webglTexture, j, rt + Or), D.framebufferTextureLayer(D.DRAW_FRAMEBUFFER, D.COLOR_ATTACHMENT0, A.get(z).__webglTexture, Te, Vt + Or)), D.blitFramebuffer(Be, ze, ue, ge, je, Lt, ue, ge, D.DEPTH_BUFFER_BIT, D.NEAREST); 25799 pe.bindFramebuffer(D.READ_FRAMEBUFFER, null), pe.bindFramebuffer(D.DRAW_FRAMEBUFFER, null); 25800 } else if (j !== 0 || S.isRenderTargetTexture || A.has(S)) { 25801 const Wt = A.get(S), zi = A.get(z); 25802 pe.bindFramebuffer(D.READ_FRAMEBUFFER, dr), pe.bindFramebuffer(D.DRAW_FRAMEBUFFER, ii); 25803 for (let Ut = 0; Ut < Oe; Ut++) 25804 Ur ? D.framebufferTextureLayer(D.READ_FRAMEBUFFER, D.COLOR_ATTACHMENT0, Wt.__webglTexture, j, rt + Ut) : D.framebufferTexture2D(D.READ_FRAMEBUFFER, D.COLOR_ATTACHMENT0, D.TEXTURE_2D, Wt.__webglTexture, j), Dt ? D.framebufferTextureLayer(D.DRAW_FRAMEBUFFER, D.COLOR_ATTACHMENT0, zi.__webglTexture, Te, Vt + Ut) : D.framebufferTexture2D(D.DRAW_FRAMEBUFFER, D.COLOR_ATTACHMENT0, D.TEXTURE_2D, zi.__webglTexture, Te), j !== 0 ? D.blitFramebuffer(Be, ze, ue, ge, je, Lt, ue, ge, D.COLOR_BUFFER_BIT, D.NEAREST) : Dt ? D.copyTexSubImage3D(ke, Te, je, Lt, Vt + Ut, Be, ze, ue, ge) : D.copyTexSubImage2D(ke, Te, je, Lt, Be, ze, ue, ge); 25805 pe.bindFramebuffer(D.READ_FRAMEBUFFER, null), pe.bindFramebuffer(D.DRAW_FRAMEBUFFER, null); 25806 } else 25807 Dt ? S.isDataTexture || S.isData3DTexture ? D.texSubImage3D(ke, Te, je, Lt, Vt, ue, ge, Oe, It, ln, Bt.data) : z.isCompressedArrayTexture ? D.compressedTexSubImage3D(ke, Te, je, Lt, Vt, ue, ge, Oe, It, Bt.data) : D.texSubImage3D(ke, Te, je, Lt, Vt, ue, ge, Oe, It, ln, Bt) : S.isDataTexture ? D.texSubImage2D(D.TEXTURE_2D, Te, je, Lt, ue, ge, It, ln, Bt.data) : S.isCompressedTexture ? D.compressedTexSubImage2D(D.TEXTURE_2D, Te, je, Lt, Bt.width, Bt.height, It, Bt.data) : D.texSubImage2D(D.TEXTURE_2D, Te, je, Lt, ue, ge, It, ln, Bt); 25808 pe.pixelStorei(D.UNPACK_ROW_LENGTH, Tn), pe.pixelStorei(D.UNPACK_IMAGE_HEIGHT, St), pe.pixelStorei(D.UNPACK_SKIP_PIXELS, On), pe.pixelStorei(D.UNPACK_SKIP_ROWS, ri), pe.pixelStorei(D.UNPACK_SKIP_IMAGES, Bi), Te === 0 && z.generateMipmaps && D.generateMipmap(ke), pe.unbindTexture(); 25809 }, this.initRenderTarget = function(S) { 25810 A.get(S).__webglFramebuffer === void 0 && b.setupRenderTarget(S); 25811 }, this.initTexture = function(S) { 25812 S.isCubeTexture ? b.setTextureCube(S, 0) : S.isData3DTexture ? b.setTexture3D(S, 0) : S.isDataArrayTexture || S.isCompressedArrayTexture ? b.setTexture2DArray(S, 0) : b.setTexture2D(S, 0), pe.unbindTexture(); 25813 }, this.resetState = function() { 25814 V = 0, F = 0, I = null, pe.reset(), ye.reset(); 25815 }, typeof __THREE_DEVTOOLS__ < "u" && __THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe", { detail: this })); 25816 } 25817 /** 25818 * Defines the coordinate system of the renderer. 25819 * 25820 * In `WebGLRenderer`, the value is always `WebGLCoordinateSystem`. 25821 * 25822 * @type {WebGLCoordinateSystem|WebGPUCoordinateSystem} 25823 * @default WebGLCoordinateSystem 25824 * @readonly 25825 */ 25826 get coordinateSystem() { 25827 return ui; 25828 } 25829 /** 25830 * Defines the output color space of the renderer. 25831 * 25832 * @type {SRGBColorSpace|LinearSRGBColorSpace} 25833 * @default SRGBColorSpace 25834 */ 25835 get outputColorSpace() { 25836 return this._outputColorSpace; 25837 } 25838 set outputColorSpace(e) { 25839 this._outputColorSpace = e; 25840 const t = this.getContext(); 25841 t.drawingBufferColorSpace = _t._getDrawingBufferColorSpace(e), t.unpackColorSpace = _t._getUnpackColorSpace(); 25842 } 25843} 25844function nm(n, e = !1) { 25845 const t = n[0].index !== null, i = new Set(Object.keys(n[0].attributes)), r = new Set(Object.keys(n[0].morphAttributes)), s = {}, a = {}, l = n[0].morphTargetsRelative, o = new xn(); 25846 let c = 0; 25847 for (let u = 0; u < n.length; ++u) { 25848 const h = n[u]; 25849 let d = 0; 25850 if (t !== (h.index !== null)) 25851 return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index " + u + ". All geometries must have compatible attributes; make sure index attribute exists among all geometries, or in none of them."), null; 25852 for (const f in h.attributes) { 25853 if (!i.has(f)) 25854 return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index " + u + '. All geometries must have compatible attributes; make sure "' + f + '" attribute exists among all geometries, or in none of them.'), null; 25855 s[f] === void 0 && (s[f] = []), s[f].push(h.attributes[f]), d++; 25856 } 25857 if (d !== i.size) 25858 return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index " + u + ". Make sure all geometries have the same number of attributes."), null; 25859 if (l !== h.morphTargetsRelative) 25860 return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index " + u + ". .morphTargetsRelative must be consistent throughout all geometries."), null; 25861 for (const f in h.morphAttributes) { 25862 if (!r.has(f)) 25863 return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index " + u + ". .morphAttributes must be consistent throughout all geometries."), null; 25864 a[f] === void 0 && (a[f] = []), a[f].push(h.morphAttributes[f]); 25865 } 25866 if (e) { 25867 let f; 25868 if (t) 25869 f = h.index.count; 25870 else if (h.attributes.position !== void 0) 25871 f = h.attributes.position.count; 25872 else 25873 return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed with geometry at index " + u + ". The geometry must have either an index or a position attribute"), null; 25874 o.addGroup(c, f, u), c += f; 25875 } 25876 } 25877 if (t) { 25878 let u = 0; 25879 const h = []; 25880 for (let d = 0; d < n.length; ++d) { 25881 const f = n[d].index; 25882 for (let p = 0; p < f.count; ++p) 25883 h.push(f.getX(p) + u); 25884 u += n[d].attributes.position.count; 25885 } 25886 o.setIndex(h); 25887 } 25888 for (const u in s) { 25889 const h = $d(s[u]); 25890 if (!h) 25891 return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the " + u + " attribute."), null; 25892 o.setAttribute(u, h); 25893 } 25894 for (const u in a) { 25895 const h = a[u][0].length; 25896 if (h !== 0) { 25897 o.morphAttributes = o.morphAttributes || {}, o.morphAttributes[u] = []; 25898 for (let d = 0; d < h; ++d) { 25899 const f = []; 25900 for (let v = 0; v < a[u].length; ++v) 25901 f.push(a[u][v][d]); 25902 const p = $d(f); 25903 if (!p) 25904 return console.error("THREE.BufferGeometryUtils: .mergeGeometries() failed while trying to merge the " + u + " morphAttribute."), null; 25905 o.morphAttributes[u].push(p); 25906 } 25907 } 25908 } 25909 return o; 25910} 25911function $d(n) { 25912 let e, t, i, r = -1, s = 0; 25913 for (let c = 0; c < n.length; ++c) { 25914 const u = n[c]; 25915 if (e === void 0 && (e = u.array.constructor), e !== u.array.constructor) 25916 return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.array must be of consistent array types across matching attributes."), null; 25917 if (t === void 0 && (t = u.itemSize), t !== u.itemSize) 25918 return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.itemSize must be consistent across matching attributes."), null; 25919 if (i === void 0 && (i = u.normalized), i !== u.normalized) 25920 return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.normalized must be consistent across matching attributes."), null; 25921 if (r === -1 && (r = u.gpuType), r !== u.gpuType) 25922 return console.error("THREE.BufferGeometryUtils: .mergeAttributes() failed. BufferAttribute.gpuType must be consistent across matching attributes."), null; 25923 s += u.count * t; 25924 } 25925 const a = new e(s), l = new on(a, t, i); 25926 let o = 0; 25927 for (let c = 0; c < n.length; ++c) { 25928 const u = n[c]; 25929 if (u.isInterleavedBufferAttribute) { 25930 const h = o / t; 25931 for (let d = 0, f = u.count; d < f; d++) 25932 for (let p = 0; p < t; p++) { 25933 const v = u.getComponent(d, p); 25934 l.setComponent(d + h, p, v); 25935 } 25936 } else 25937 a.set(u.array, o); 25938 o += u.count * t; 25939 } 25940 return r !== void 0 && (l.gpuType = r), l; 25941} 25942function im(n) { 25943 const e = [], t = Math.PI * (3 - Math.sqrt(5)); 25944 for (let i = 0; i < n; i++) { 25945 const r = 1 - i / (n - 1) * 2, s = Math.sqrt(Math.max(0, 1 - r * r)), a = t * i; 25946 e.push([Math.cos(a) * s, r, Math.sin(a) * s]); 25947 } 25948 return e; 25949} 25950const Zs = 1.5, rE = 70, jd = { dead: 0, thriving: 1 }, Zo = ` 25951vec3 mod289v3(vec3 x){return x-floor(x*(1./289.))*289.;} 25952vec4 mod289v4(vec4 x){return x-floor(x*(1./289.))*289.;} 25953vec4 permute4(vec4 x){return mod289v4((34.*x+1.)*x);} 25954vec4 taylorInvSqrt4(vec4 r){return 1.79284291400159-r*0.85373472095314;} 25955float snoise(vec3 v){ 25956 const vec2 C=vec2(1./6.,1./3.); 25957 const vec4 D=vec4(0.,.5,1.,2.);
25958 vec3 i=floor(v+dot(v,C.yyy)); 25959 vec3 x0=v-i+dot(i,C.xxx); 25960 vec3 g=step(x0.yzx,x0.xyz); 25961 vec3 l=1.-g; 25962 vec3 i1=min(g.xyz,l.zxy); 25963 vec3 i2=max(g.xyz,l.zxy); 25964 vec3 x1=x0-i1+C.xxx; 25965 vec3 x2=x0-i2+C.yyy; 25966 vec3 x3=x0-D.yyy; 25967 i=mod289v3(i); 25968 vec4 p=permute4(permute4(permute4( 25969 i.z+vec4(0.,i1.z,i2.z,1.)) 25970 +i.y+vec4(0.,i1.y,i2.y,1.)) 25971 +i.x+vec4(0.,i1.x,i2.x,1.)); 25972 float n_=0.142857142857; 25973 vec3 ns=n_*D.wyz-D.xzx; 25974 vec4 j=p-49.*floor(p*ns.z*ns.z); 25975 vec4 x_=floor(j*ns.z); 25976 vec4 y_=floor(j-7.*x_); 25977 vec4 x=x_*ns.x+ns.yyyy; 25978 vec4 y=y_*ns.x+ns.yyyy; 25979 vec4 h=1.-abs(x)-abs(y); 25980 vec4 b0=vec4(x.xy,y.xy); 25981 vec4 b1=vec4(x.zw,y.zw); 25982 vec4 s0=floor(b0)*2.+1.; 25983 vec4 s1=floor(b1)*2.+1.; 25984 vec4 sh=-step(h,vec4(0.)); 25985 vec4 a0=b0.xzyw+s0.xzyw*sh.xxyy; 25986 vec4 a1=b1.xzyw+s1.xzyw*sh.zzww; 25987 vec3 p0=vec3(a0.xy,h.x); 25988 vec3 p1=vec3(a0.zw,h.y); 25989 vec3 p2=vec3(a1.xy,h.z); 25990 vec3 p3=vec3(a1.zw,h.w); 25991 vec4 norm=taylorInvSqrt4(vec4(dot(p0,p0),dot(p1,p1),dot(p2,p2),dot(p3,p3))); 25992 p0*=norm.x;p1*=norm.y;p2*=norm.z;p3*=norm.w; 25993 vec4 m=max(.6-vec4(dot(x0,x0),dot(x1,x1),dot(x2,x2),dot(x3,x3)),0.); 25994 m=m*m; 25995 return 42.*dot(m*m,vec4(dot(p0,x0),dot(p1,x1),dot(p2,x2),dot(p3,x3))); 25996} 25997`, Ku = ` 25998${Zo} 25999varying vec3 vNormal; 26000varying vec3 vWorldPos; 26001varying vec3 vDir; 26002varying float vElev; 26003void main(){ 26004 vDir=normalize(position); 26005 float n1=snoise(vDir*1.4); 26006 float n2=snoise(vDir*3.2)*0.45; 26007 float elev=n1*0.085+n2*0.04; 26008 vElev=elev; 26009 vec3 displaced=position+normal*elev; 26010 vNormal=normalize(normalMatrix*normal); 26011 vWorldPos=(modelMatrix*vec4(displaced,1.)).xyz; 26012 gl_Position=projectionMatrix*modelViewMatrix*vec4(displaced,1.); 26013} 26014`; 26015function rm(n) { 26016 return ` 26017${Zo} 26018uniform float uTime; 26019uniform float uHealth; 26020uniform float uHealthB; 26021uniform float uSplit; 26022varying vec3 vNormal; 26023varying vec3 vWorldPos; 26024varying vec3 vDir; 26025varying float vElev; 26026 26027float effectiveHealth(){ 26028 float blend=smoothstep(-0.12,0.12,vDir.x); 26029 float h=mix(uHealthB,uHealth,blend); 26030 return mix(uHealth,h,uSplit); 26031} 26032 26033// One winding river: distance from a sinuous great-circle path. 26034float riverDist(vec3 d){ 26035 float lat=asin(clamp(d.y,-1.,1.)); 26036 float lon=atan(d.z,d.x); 26037 float rLon=sin(lat*1.6+0.4)*0.55+sin(lat*4.1)*0.10; 26038 float diff=lon-rLon; 26039 diff=mod(diff+3.14159265,6.28318530)-3.14159265; 26040 return abs(diff)*cos(lat); 26041} 26042 26043void main(){ 26044 vec3 N=normalize(vNormal); 26045 float elev=vElev; 26046 26047 // Rock palette â dead state. 26048 vec3 rockLow =vec3(0.28,0.22,0.18); 26049 vec3 rockMid =vec3(0.42,0.34,0.27); 26050 vec3 rockHigh=vec3(0.55,0.48,0.42); 26051 float rockMix=smoothstep(-0.08,0.10,elev); 26052 vec3 rock=mix(rockLow,rockMid,rockMix); 26053 rock=mix(rock,rockHigh,smoothstep(0.04,0.12,elev)); 26054 26055 // Grass palette â alive state. 26056 vec3 grassDark =vec3(0.16,0.36,0.10); 26057 vec3 grassMid =vec3(0.30,0.58,0.18); 26058 vec3 grassLight=vec3(0.52,0.78,0.30); 26059 float gMix=smoothstep(-0.06,0.10,elev); 26060 vec3 grass=mix(grassDark,grassMid,gMix); 26061 grass=mix(grass,grassLight,smoothstep(0.05,0.12,elev)); 26062 26063 // Soft grass-blade speckle (cheap, only used where grass shows). 26064 float speckle=snoise(vDir*38.)*0.5+0.5; 26065 grass+=(speckle-0.5)*vec3(0.05,0.08,0.04); 26066 26067 // Grass coverage: patchy noise gated by health. 26068 // 0%: no grass. 20%: small patches. 40%: spread. 100%: full. 26069 float hEff=effectiveHealth(); 26070 float patchN=snoise(vDir*2.6+vec3(1.7))*0.5+0.5; 26071 float coverThresh=mix(1.05,-0.05,smoothstep(0.05,1.0,hEff)); 26072 float grassCov=smoothstep(coverThresh-0.18,coverThresh+0.05,patchN); 26073 // Suppress grass on steepest peaks for variety. 26074 grassCov*=smoothstep(0.14,0.08,elev); 26075 grassCov=clamp(grassCov,0.,1.); 26076 26077 vec3 surface=mix(rock,grass,grassCov); 26078 26079 // River: only appears once life is established (>= ~70%). 26080 float riverGate=smoothstep(0.70,0.88,hEff); 26081 float rd=riverDist(vDir); 26082 // River prefers low ground. 26083 float lowland=smoothstep(0.04,-0.06,elev); 26084 float river=smoothstep(0.045,0.012,rd)*lowland*riverGate; 26085 vec3 waterDeep=vec3(0.04,0.22,0.42); 26086 vec3 waterShallow=vec3(0.18,0.55,0.78); 26087 vec3 water=mix(waterDeep,waterShallow,smoothstep(0.,0.04,rd)); 26088 surface=mix(surface,water,river); 26089 26090 // Lighting â strong key + soft fill + cool rim. 26091 vec3 L=normalize(vec3(0.75,0.55,0.45)); 26092 float ndl=dot(N,L); 26093 float diff=max(ndl,0.); 26094 // Wrap a touch for softer terminator. 26095 float wrap=clamp(ndl*0.5+0.5,0.,1.); 26096 vec3 keyCol=vec3(1.00,0.94,0.82); 26097 vec3 fillCol=vec3(0.18,0.26,0.42); 26098 vec3 lit=surface*(keyCol*(0.20+0.80*diff)+fillCol*(0.25*wrap)); 26099 26100 // Specular highlight on water only. 26101 vec3 V=normalize(cameraPosition-vWorldPos); 26102 vec3 H=normalize(L+V); 26103 float spec=pow(max(dot(H,N),0.),90.);
26104 lit+=spec*river*0.9; 26105 26106 // Subtle rim on the lit side for cinematic edge. 26107 float rim=pow(1.0-max(dot(V,N),0.),3.0)*smoothstep(-0.2,0.4,ndl); 26108 lit+=vec3(0.55,0.70,0.95)*rim*0.10; 26109 26110 // Gentle AO in low ground. 26111 float ao=smoothstep(0.06,-0.10,elev)*0.18; 26112 lit*=(1.0-ao); 26113 26114 vec3 color=lit; 26115 ${n ? "float lum=dot(color,vec3(0.299,0.587,0.114));color=vec3(lum*0.78);" : ""} 26116 gl_FragColor=vec4(color,1.); 26117} 26118`; 26119} 26120function sE(n) { 26121 return ` 26122${Zo} 26123uniform float uTime; 26124uniform vec3 uRegionSeeds[${n}]; 26125uniform float uRegionStates[${n}]; 26126uniform float uClickTimes[${n}]; 26127varying vec3 vNormal; 26128varying vec3 vWorldPos; 26129varying vec3 vDir; 26130varying float vElev; 26131 26132void main(){ 26133 vec3 N=normalize(vNormal); 26134 float elev=vElev; 26135 vec3 rock=mix(vec3(0.30,0.23,0.18),vec3(0.52,0.45,0.38),smoothstep(-0.06,0.10,elev)); 26136 vec3 grass=mix(vec3(0.18,0.40,0.12),vec3(0.46,0.74,0.28),smoothstep(-0.06,0.10,elev)); 26137 26138 float d0=100.,d1=100.; 26139 int near0=0; 26140 for(int i=0;i<${n};i++){ 26141 float d=distance(vDir,uRegionSeeds[i]); 26142 if(d<d0){d1=d0;d0=d;near0=i;} 26143 else if(d<d1){d1=d;} 26144 } 26145 float rs=uRegionStates[near0]; 26146 vec3 surface=mix(rock,grass,smoothstep(0.0,1.0,rs)); 26147 26148 vec3 L=normalize(vec3(0.75,0.55,0.45)); 26149 float diff=max(dot(N,L),0.); 26150 vec3 color=surface*(vec3(1.0,0.94,0.82)*(0.22+0.78*diff)+vec3(0.18,0.26,0.42)*0.25); 26151 26152 float edge=1.-smoothstep(0.006,0.030,d1-d0); 26153 vec3 borderCol=mix(vec3(.30,.10,.02),vec3(.20,.65,.35),rs); 26154 color=mix(color,borderCol*.5+color*.5,edge*.45); 26155 26156 float clickAge=uTime-uClickTimes[near0]; 26157 if(clickAge>0.&&clickAge<2.0){ 26158 float t=clickAge/2.0; 26159 float pulse=sin(t*3.14159)*(1.-t*t); 26160 vec3 pulseCol=rs>0.5?vec3(.55,.95,.45):vec3(.80,.45,.15); 26161 color=mix(color,pulseCol,pulse*.35); 26162 } 26163 gl_FragColor=vec4(color,1.); 26164} 26165`; 26166} 26167function Ju(n) { 26168 n.traverse((e) => { 26169 const t = e, i = t.geometry; 26170 i && typeof i.dispose == "function" && i.dispose(); 26171 const r = t.material; 26172 Array.isArray(r) ? r.forEach((s) => s.dispose?.()) : r && r.dispose?.(); 26173 }); 26174} 26175const aE = ` 26176attribute float aSize; 26177void main(){ 26178 gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.); 26179 gl_PointSize=aSize; 26180} 26181`, oE = ` 26182void main(){ 26183 vec2 uv=gl_PointCoord-.5; 26184 float alpha=smoothstep(.5,.1,length(uv)); 26185 gl_FragColor=vec4(1.,1.,1.,alpha); 26186} 26187`, lE = ` 26188${Zo} 26189attribute float aHealth; 26190varying float vHealth; 26191varying vec3 vNormal; 26192varying vec3 vDir; 26193void main(){ 26194 vDir=normalize(position); 26195 vHealth=aHealth; 26196 vNormal=normalize(normalMatrix*normal); 26197 gl_Position=projectionMatrix*modelViewMatrix*vec4(position,1.); 26198} 26199`, cE = ` 26200varying float vHealth; 26201varying vec3 vNormal; 26202varying vec3 vDir; 26203void main(){ 26204 vec3 dead=vec3(0.35,0.27,0.20); 26205 vec3 alive=vec3(0.28,0.62,0.20); 26206 vec3 color=mix(dead,alive,smoothstep(0.,1.,vHealth)); 26207 vec3 L=normalize(vec3(0.75,0.55,0.45)); 26208 float diff=max(dot(normalize(vNormal),L),0.); 26209 color*=0.30+0.70*diff; 26210 gl_FragColor=vec4(color,1.); 26211} 26212`; 26213function nu(n, e, t) { 26214 const i = Math.max(0, Math.min(1, (t - n) / (e - n))); 26215 return i * i * (3 - 2 * i); 26216} 26217function Xd(n, e) { 26218 let t = 0, i = 1 / 0; 26219 for (let r = 0; r < e.length; r++) { 26220 const s = n.distanceTo(e[r]); 26221 s < i && (i = s, t = r); 26222 } 26223 return t; 26224} 26225function sm() { 26226 const n = new Ea(0.01, 0.016, 0.07, 5); 26227 n.translate(0, 0.035, 0); 26228 const e = new Xo(0.075, 0.16, 7); 26229 return e.translate(0, 0.135, 0), nm([n, e]); 26230} 26231function Zu(n) { 26232 const t = new Float32Array(1050), i = new Float32Array(350); 26233 for (let s = 0; s < 350; s++) { 26234 let a, l, o; 26235 do 26236 a = Math.random() * 2 - 1, l = Math.random() * 2 - 1, o = a * a + l * l; 26237 while (o >= 1); 26238 const c = Math.sqrt(1 - o), u = 38 + Math.random() * 12; 26239 t[s * 3] = 2 * a * c * u, t[s * 3 + 1] = 2 * l * c * u, t[s * 3 + 2] = (1 - 2 * o) * u, i[s] = 0.5 + Math.random() * 2; 26240 } 26241 const r = new xn(); 26242 r.setAttribute("position", new on(t, 3)), r.setAttribute("aSize", new on(i, 1)), n.add(new K_(r, new yn({ 26243 vertexShader: aE, 26244 fragmentShader: oE, 26245 transparent: !0, 26246 blending: oc, 26247 depthWrite: !1 26248 }))); 26249} 26250function uE(n, e, t, i, r = !1, s) { 26251 const a = n.clientWidth || 800, l = n.clientHeight || 600, o = new Jo({ canvas: n, antialias: !t, alpha: !t, powerPreference: "high-performance" }); 26252 o.setPixelRatio(Math.min(window.devicePixelRatio, t ? 1 : 1.25)), o.setSize(a, l, !1), o.setClearColor(t ? 1184274 : 0, t ? 1 : 0); 26253 const c = new jo(), u = new mn(38, a / l, 0.1, 200); 26254 u.position.set(0, 0.4, 7.2), u.lookAt(0, 0, 0), c.add(new Yu(2243
26254157, 0.4)); 26255 const h = new ys(16773848, 1.8); 26256 h.position.set(3, 2.2, 2), c.add(h); 26257 const d = new ys(4880584, 0.35); 26258 d.position.set(-2.5, -0.5, -1.5), c.add(d), Zu(c); 26259 const f = new Ar(); 26260 c.add(f); 26261 const p = new yn({ 26262 uniforms: { 26263 uTime: { value: 0 }, 26264 uHealth: { value: e.current }, 26265 uHealthB: { value: e.current }, 26266 uSplit: { value: 0 } 26267 }, 26268 vertexShader: Ku, 26269 fragmentShader: rm(t) 26270 }); 26271 f.add(new _n(new Ms(Zs, 48, 48), p)); 26272 const v = [], m = new Zt(), g = new W(0, 1, 0), _ = im(rE); 26273 let x = 919; 26274 const E = () => (x = x * 1664525 + 1013904223 >>> 0, x / 4294967296); 26275 for (let te = 0; te < _.length; te++) { 26276 const ie = new W(..._[te]).normalize(); 26277 if (ie.x += (E() - 0.5) * 0.06, ie.y += (E() - 0.5) * 0.06, ie.z += (E() - 0.5) * 0.06, ie.normalize(), Math.abs(ie.y) > 0.86) continue; 26278 const fe = ie.clone(), Se = new Wn().setFromUnitVectors(g, fe); 26279 Se.premultiply(new Wn().setFromAxisAngle(fe, E() * Math.PI * 2)); 26280 const Fe = 0.55 + E() * 0.4; 26281 v.push({ 26282 pos: fe.clone().multiplyScalar(Zs + 5e-3), 26283 quat: Se, 26284 baseScale: 0.82 + E() * 0.45, 26285 threshold: Fe 26286 }); 26287 } 26288 const R = v.length, T = new Xu({ 26289 color: t ? 3815994 : 2779668, 26290 emissive: t ? 1052688 : 332803, 26291 shininess: 8, 26292 flatShading: !0 26293 }), w = new $u(sm(), T, R); 26294 w.frustumCulled = !1, f.add(w); 26295 function y(te, ie) { 26296 for (let fe = 0; fe < R; fe++) { 26297 const { pos: Se, quat: Fe, baseScale: Me, threshold: Ke } = v[fe]; 26298 let at = te; 26299 if (ie !== null) { 26300 const lt = nu(-0.12, 0.12, Se.x / Zs); 26301 at = ie + (te - ie) * lt; 26302 } 26303 const Ue = nu(Ke, Ke + 0.08, at); 26304 m.position.copy(Se), m.quaternion.copy(Fe), m.scale.setScalar(Math.max(1e-4, Ue * Me)), m.updateMatrix(), w.setMatrixAt(fe, m.matrix); 26305 } 26306 w.instanceMatrix.needsUpdate = !0; 26307 } 26308 let M = 0, L = 0, C = !1, U = 0, V = 0; 26309 n.style.cursor = "grab"; 26310 let F = 0, I = 0, k = 0, H = 0; 26311 function X(te) { 26312 const ie = te.clientX / window.innerWidth * 2 - 1, fe = te.clientY / window.innerHeight * 2 - 1; 26313 F = ie * 0.35, I = fe * 0.18; 26314 } 26315 r && window.addEventListener("pointermove", X, { passive: !0 }); 26316 function K(te) { 26317 n.setPointerCapture(te.pointerId), C = !0, U = te.clientX, V = te.clientY, M = 0, L = 0, n.style.cursor = "grabbing"; 26318 } 26319 function ae(te) { 26320 if (!C) return; 26321 const ie = te.clientX - U, fe = te.clientY - V; 26322 U = te.clientX, V = te.clientY, f.rotation.y += ie * 5e-3, f.rotation.x = Math.max(-1.3, Math.min(1.3, f.rotation.x + fe * 5e-3)), M = ie * 5e-3, L = fe * 5e-3; 26323 } 26324 function se() { 26325 C = !1, n.style.cursor = "grab"; 26326 } 26327 n.addEventListener("pointerdown", K), n.addEventListener("pointermove", ae), n.addEventListener("pointerup", se); 26328 let he = 0, Ce = performance.now(), Ie = e.current, Ee = e.current, J = 0; 26329 y(Ie, null); 26330 function le(te) { 26331 const ie = Math.min((te - Ce) / 1e3, 0.1); 26332 Ce = te; 26333 const fe = s?.current ?? null, Se = fe ? fe.alive : e.current, Fe = fe ? fe.dead : e.current, Me = fe ? 1 : 0, Ke = Ie, at = Ee, Ue = J, lt = Math.min(ie * 1.5, 1); 26334 if (Ie += (Se - Ie) * lt, Ee += (Fe - Ee) * lt, J += (Me - J) * Math.min(ie * 2, 1), p.uniforms.uTime.value = te / 1e3, p.uniforms.uHealth.value = Ie, p.uniforms.uHealthB.value = Ee, p.uniforms.uSplit.value = J, (Math.abs(Ie - Ke) > 5e-4 || Math.abs(Ee - at) > 5e-4 || Math.abs(J - Ue) > 5e-4) && (y(Ie, J > 0.01 ? Ee : null), i?.(Math.round(Ie * 100))), !C) { 26335 const D = Math.pow(0.88, ie * 60); 26336 M *= D, L *= D, Math.abs(M) < 5e-5 && (M = 0), Math.abs(L) < 5e-5 && (L = 0); 26337 const Rt = M === 0 && L === 0; 26338 if (f.rotation.y += M + (Rt ? ie * 0.08 : 0), f.rotation.x = Math.max(-1.3, Math.min(1.3, f.rotation.x + L)), r) { 26339 const Qe = Math.min(ie * 3.2, 1), dt = k + (F - k) * Qe, pe = H + (I - H) * Qe; 26340 f.rotation.y += dt - k, f.rotation.x = Math.max(-1.3, Math.min(1.3, f.rotation.x + (pe - H))), k = dt, H = pe; 26341 } 26342 } 26343 const ut = n.clientWidth, Tt = n.clientHeight; 26344 (n.width !== ut || n.height !== Tt) && (o.setSize(ut, Tt, !1), u.aspect = ut / Tt, u.updateProjectionMatrix()), o.render(c, u), he = requestAnimationFrame(le); 26345 } 26346 return he = requestAnimationFrame(le), () => { 26347 n.removeEventListener("pointerdown", K), n.removeEventListener("pointermove", ae), n.removeEventListener("pointerup", se), r && window.removeEventListener("pointermove",
26347X), cancelAnimationFrame(he), Ju(c), o.dispose(); 26348 }; 26349} 26350function hE(n, e, t) { 26351 const i = n.clientWidth || 800, r = n.clientHeight || 600, s = new Jo({ canvas: n, antialias: !0 }); 26352 s.setPixelRatio(Math.min(window.devicePixelRatio, 2)), s.setSize(i, r, !1), s.setClearColor(132104, 1); 26353 const a = new jo(), l = new mn(55, i / r, 0.1, 300); 26354 l.position.set(0, 0, 22), l.lookAt(0, 0, 0), Zu(a); 26355 const o = 400, c = im(o), u = 18, h = new Ms(0.4, 8, 8), d = h.attributes.position, f = h.attributes.normal, p = h.index, v = d.count, m = p.count, g = new Float32Array(o * v * 3), _ = new Float32Array(o * v * 3), x = new Float32Array(o * v), E = []; 26356 for (let se = 0; se < o; se++) { 26357 const [he, Ce, Ie] = c[se], Ee = he * u, J = Ce * u, le = Ie * u, te = e.current, ie = se < te.length ? te[se].health : Math.abs(Math.sin(se * 127.1 + 311.7)), fe = se * v * 3, Se = se * v; 26358 for (let Me = 0; Me < v; Me++) 26359 g[fe + Me * 3] = d.getX(Me) + Ee, g[fe + Me * 3 + 1] = d.getY(Me) + J, g[fe + Me * 3 + 2] = d.getZ(Me) + le, _[fe + Me * 3] = f.getX(Me), _[fe + Me * 3 + 1] = f.getY(Me), _[fe + Me * 3 + 2] = f.getZ(Me), x[Se + Me] = ie; 26360 const Fe = se * v; 26361 for (let Me = 0; Me < m; Me++) 26362 E.push(p.getX(Me) + Fe); 26363 } 26364 const R = new xn(); 26365 R.setAttribute("position", new on(g, 3)), R.setAttribute("normal", new on(_, 3)), R.setAttribute("aHealth", new on(x, 1)), R.setIndex(E); 26366 const T = new yn({ vertexShader: lE, fragmentShader: cE }), w = new _n(R, T); 26367 a.add(w); 26368 let y = !1, M = 0, L = 0, C = 0, U = 0; 26369 const V = new Xp(), F = new wt(); 26370 function I(se) { 26371 y = !0, M = se.clientX, L = se.clientY, C = U = 0; 26372 } 26373 function k(se) { 26374 if (!y) return; 26375 const he = se.clientX - M, Ce = se.clientY - L; 26376 M = se.clientX, L = se.clientY, a.rotation.y += he * 4e-3, a.rotation.x += Ce * 4e-3, U = he * 4e-3, C = Ce * 4e-3; 26377 } 26378 function H(se) { 26379 if (!y) return; 26380 y = !1; 26381 const he = n.getBoundingClientRect(); 26382 if (F.x = (se.clientX - he.left) / he.width * 2 - 1, F.y = -((se.clientY - he.top) / he.height) * 2 + 1, V.setFromCamera(F, l), w) { 26383 const Ce = V.intersectObject(w); 26384 if (Ce.length > 0 && Ce[0].faceIndex != null) { 26385 const Ie = Math.floor(Ce[0].faceIndex / (m / 3)), Ee = e.current[Ie]; 26386 Ee?.username && t.current?.(Ee.username); 26387 } 26388 } 26389 } 26390 n.addEventListener("pointerdown", I), n.addEventListener("pointermove", k), n.addEventListener("pointerup", H); 26391 let X = 0, K = performance.now(); 26392 function ae(se) { 26393 const he = Math.min((se - K) / 1e3, 0.1); 26394 K = se, y || (U *= Math.pow(0.9, he * 60), C *= Math.pow(0.9, he * 60), a.rotation.y += U + he * 0.02, a.rotation.x += C); 26395 const Ce = n.clientWidth, Ie = n.clientHeight; 26396 (n.width !== Ce || n.height !== Ie) && (s.setSize(Ce, Ie, !1), l.aspect = Ce / Ie, l.updateProjectionMatrix()), s.render(a, l), X = requestAnimationFrame(ae); 26397 } 26398 return X = requestAnimationFrame(ae), () => { 26399 n.removeEventListener("pointerdown", I), n.removeEventListener("pointermove", k), n.removeEventListener("pointerup", H), cancelAnimationFrame(X), Ju(a), s.dispose(); 26400 }; 26401} 26402function dE(n, e, t, i, r) { 26403 const s = n.clientWidth || 800, a = n.clientHeight || 600, l = new Jo({ canvas: n, antialias: !0 }); 26404 l.setPixelRatio(Math.min(window.devicePixelRatio, 2)), l.setSize(s, a, !1), l.setClearColor(132104, 1); 26405 const o = new jo(), c = new mn(42, s / a, 0.1, 200); 26406 c.position.set(0, 0.5, 5.8), c.lookAt(0, 0, 0), o.add(new Yu(2243157, 0.45)); 26407 const u = new ys(16773848, 1.7); 26408 u.position.set(3, 2.2, 2), o.add(u); 26409 const h = new ys(4880584, 0.3); 26410 h.position.set(-2, -1, -2), o.add(h), Zu(o); 26411 const d = t.current.slice(0, e), f = d.map((ie) => new W(...ie.seed)), p = new Float32Array(e), v = new Float32Array(e).fill(-1e3); 26412 for (let ie = 0; ie < e; ie++) p[ie] = jd[d[ie].state]; 26413 const m = new Float32Array(p), g = new Float32Array(v), _ = new Ar(); 26414 o.add(_); 26415 const x = new yn({ 26416 uniforms: { 26417 uTime: { value: 0 }, 26418 uRegionSeeds: { value: f }, 26419 uRegionStates: { value: m }, 26420 uClickTimes: { value: g } 26421 }, 26422 vertexShader: Ku, 26423 fragmentShader: sE(e) 26424 }), E = new _n(new Ms(Zs, 96, 96), x); 26425 _.add(E); 26426 const R = new Zt(), T = new W(0, 1, 0), w = [], y = 8; 26427 let M = 919; 26428 const L = () => (M = M * 1664525 + 1013904223 >>> 0, M / 4294967296), C = new Array(e).fill(0); 26429 for (let ie = 0; ie < 6e3 && w.length < e * y; ie++) { 26430 let fe, Se, Fe; 26431 do 26432 fe = L() * 2 - 1, Se = L() * 2 - 1, Fe = fe * fe + Se * Se; 26433 while (Fe >= 1); 26434 const Me = Math.sqrt(1 - Fe), Ke = new W(2 * fe * Me, 2 * Se * Me, 1 - 2 * Fe).normalize(); 26435 if (Math.abs(Ke.y) > 0.84) continue; 26436 const at = Xd(Ke, f); 26437 if (C[at] >= y) continue; 26438 const Ue = Ke.clone(), lt = new Wn().setFromUnitVectors(T, Ue); 26439 lt.premultiply(new Wn().setFromAxisAngle(Ue, L() * Math.PI * 2)), w.push({ regionIdx: at, pos: Ue.clone().multiplyScalar(Zs + 5e-3), quat: lt, baseScale: 0.82 + L() * 0.36 }), C[at]++; 26440 } 26441 const U = w.length, V = new Xu({ color: 2779668, emissive: 332803, shininess: 8, flatShading: !0 }), F = new $u(sm(), V, Math.max(U, 1)); 26442 F.frustumCulled = !1, _.add(F); 26443 function I() { 26444 for (let ie = 0; ie < U; ie++) { 26445 const { regionIdx: fe, pos: Se, quat: Fe, baseScale: Me } = w[ie], Ke = p[fe]; 26446 R.position.copy(Se), R.quaternion.copy(Fe), R.scale.setScalar(Math.max(1e-4, nu(0.4, 1, Ke) * Me)), R.updateMatrix(), F.setMatrixAt(ie, R.matrix
26446); 26447 } 26448 F.instanceMatrix.needsUpdate = !0; 26449 } 26450 I(); 26451 const k = new Xp(), H = new wt(); 26452 n.style.cursor = "grab"; 26453 const X = { active: !1, startX: 0, startY: 0, lastX: 0, lastY: 0, totalDist: 0 }, K = { rotX: 0, rotY: 0 }; 26454 let ae = 5.8; 26455 function se(ie, fe) { 26456 const Se = n.getBoundingClientRect(); 26457 H.x = (ie - Se.left) / Se.width * 2 - 1, H.y = -((fe - Se.top) / Se.height) * 2 + 1, k.setFromCamera(H, c); 26458 const Fe = k.intersectObject(E); 26459 if (Fe.length === 0) return; 26460 const Me = E.worldToLocal(Fe[0].point.clone()).normalize(), Ke = Xd(Me, f); 26461 r.current?.(t.current[Ke].id), v[Ke] = x.uniforms.uTime.value, g[Ke] = v[Ke]; 26462 } 26463 function he(ie) { 26464 n.setPointerCapture(ie.pointerId), n.style.cursor = "grabbing", X.active = !0, X.startX = ie.clientX, X.startY = ie.clientY, X.lastX = ie.clientX, X.lastY = ie.clientY, X.totalDist = 0, K.rotX = 0, K.rotY = 0; 26465 } 26466 function Ce(ie) { 26467 if (!X.active) return; 26468 const fe = ie.clientX - X.lastX, Se = ie.clientY - X.lastY; 26469 X.lastX = ie.clientX, X.lastY = ie.clientY, X.totalDist += Math.hypot(fe, Se), _.rotation.y += fe * 5e-3, _.rotation.x = Math.max(-1.3, Math.min(1.3, _.rotation.x + Se * 5e-3)), K.rotY = fe * 5e-3, K.rotX = Se * 5e-3; 26470 } 26471 function Ie(ie) { 26472 X.active && (X.active = !1, n.style.cursor = "grab", X.totalDist < 5 && se(ie.clientX, ie.clientY)); 26473 } 26474 function Ee(ie) { 26475 ie.preventDefault(), ae = Math.max(2.8, Math.min(10, ae + ie.deltaY * 4e-3)); 26476 } 26477 n.addEventListener("pointerdown", he), n.addEventListener("pointermove", Ce), n.addEventListener("pointerup", Ie), n.addEventListener("wheel", Ee, { passive: !1 }); 26478 let J = 0, le = performance.now(); 26479 function te(ie) { 26480 const fe = Math.min((ie - le) / 1e3, 0.1); 26481 le = ie; 26482 const Se = ie / 1e3; 26483 let Fe = 0; 26484 for (let Ue = 0; Ue < e; Ue++) { 26485 const lt = jd[t.current[Ue]?.state ?? "dead"]; 26486 p[Ue] += (lt - p[Ue]) * Math.min(fe * 1.6, 1), m[Ue] = p[Ue], Fe += p[Ue]; 26487 } 26488 const Me = Fe / e; 26489 if (i.current?.(Math.round(Me * 100)), x.uniforms.uTime.value = Se, c.position.z += (ae - c.position.z) * Math.min(fe * 8, 1), !X.active) { 26490 const Ue = Math.pow(0.88, fe * 60); 26491 K.rotY *= Ue, K.rotX *= Ue, Math.abs(K.rotY) < 5e-5 && (K.rotY = 0), Math.abs(K.rotX) < 5e-5 && (K.rotX = 0); 26492 const lt = K.rotY === 0 && K.rotX === 0; 26493 _.rotation.y += K.rotY + (lt ? fe * 0.08 : 0), _.rotation.x = Math.max(-1.3, Math.min(1.3, _.rotation.x + K.rotX)); 26494 } 26495 I(); 26496 const Ke = n.clientWidth, at = n.clientHeight; 26497 (n.width !== Ke || n.height !== at) && (l.setSize(Ke, at, !1), c.aspect = Ke / at, c.updateProjectionMatrix()), l.render(o, c), J = requestAnimationFrame(te); 26498 } 26499 return J = requestAnimationFrame(te), () => { 26500 n.removeEventListener("pointerdown", he), n.removeEventListener("pointermove", Ce), n.removeEventListener("pointerup", Ie), n.removeEventListener("wheel", Ee), cancelAnimationFrame(J), Ju(o), l.dispose(); 26501 }; 26502} 26503function As({ 26504 mode: n = "single", 26505 health: e = 0.5, 26506 onHealthChange: t, 26507 fieldPlanets: i = [], 26508 onPlanetClick: r, 26509 regions: s = [], 26510 numActive: a = 1, 26511 onRegionClick: l, 26512 parallax: o = !1, 26513 splitHealth: c = null 26514}) { 26515 const u = mt(null), h = mt(e), d = mt(i), f = mt(t), p = mt(l), v = mt(s), m = mt(r); 26516 bt(() => { 26517 h.current = e; 26518 }, [e]), bt(() => { 26519 d.current = i; 26520 }, [i]), bt(() => { 26521 f.current = t; 26522 }, [t]), bt(() => { 26523 p.current = l; 26524 }, [l]), bt(() => { 26525 v.current = s; 26526 }, [s]), bt(() => { 26527 m.current = r; 26528 }, [r]); 26529 const g = mt(c); 26530 bt(() => { 26531 g.current = c; 26532 }, [c]); 26533 const _ = mt(n), x = mt(a), E = mt(o); 26534 return bt(() => { 26535 const R = u.current, T = _.current; 26536 return T === "single" || T === "grayscale" || T === "demo" ? uE(R, h, T === "grayscale", f.current, E.current, g) : T === "field" ? hE(R, d, m) : dE(R, x.current, v, f, p); 26537 }
26537, []), /* @__PURE__ */ P("canvas", { ref: u, className: "w-full h-full block" }); 26538} 26539function am({ children: n, className: e = "", style: t }) { 26540 return /* @__PURE__ */ P("div", { className: `bg-[#32bb29] rounded-[48px] p-10 ${e}`, style: t, children: n }); 26541} 26542function or({ 26543 onClick: n, 26544 disabled: e, 26545 type: t = "button", 26546 variant: i = "dark", 26547 className: r = "", 26548 children: s 26549}) { 26550 const a = i === "dark" ? "#121212" : "#32bb29", l = i === "dark" ? "#ffffff" : "#121212", o = mt(null), c = mt(null), u = mt(null); 26551 function h(p) { 26552 const v = u.current; 26553 if (!v) return; 26554 const m = v.getBoundingClientRect(), g = p.clientX - m.left, _ = p.clientY - m.top; 26555 o.current && (o.current.style.transform = `translate(${g}px, ${_}px) translate(-50%, -50%) scale(1)`), c.current && (c.current.style.transform = `translate(${g}px, ${_}px) translate(-50%, -50%) scale(0.7)`); 26556 } 26557 function d(p) { 26558 h(p); 26559 } 26560 function f() { 26561 o.current && (o.current.style.transform = o.current.style.transform.replace(/scale\([^)]+\)/, "scale(0)") || "scale(0)"), c.current && (c.current.style.transform = c.current.style.transform.replace(/scale\([^)]+\)/, "scale(0)") || "scale(0)"); 26562 } 26563 return /* @__PURE__ */ re(rr, { children: [ 26564 /* @__PURE__ */ P("svg", { width: "0", height: "0", style: { position: "absolute" }, "aria-hidden": "true", children: /* @__PURE__ */ P("defs", { children: /* @__PURE__ */ re("filter", { id: "tg-goo-filter", children: [
26565 /* @__PURE__ */ P("feGaussianBlur", { in: "SourceGraphic", stdDeviation: "4", result: "blur" }), 26566 /* @__PURE__ */ P( 26567 "feColorMatrix", 26568 { 26569 in: "blur", 26570 mode: "matrix", 26571 values: "1 0 0 0 0 0 1 0 0 0 0 0 1 0 0 0 0 0 16 -7", 26572 result: "goo" 26573 } 26574 ), 26575 /* @__PURE__ */ P("feComposite", { in: "SourceGraphic", in2: "goo", operator: "atop" }) 26576 ] }) }) }), 26577 /* @__PURE__ */ P("style", { children: ` 26578 .tg-goo-btn .tg-blob { 26579 position: absolute; 26580 border-radius: 9999px; 26581 transform: translate(-50%, -50%) scale(0); 26582 transition: transform 280ms cubic-bezier(.2,.9,.2,1); 26583 pointer-events: none; 26584 will-change: transform; 26585 } 26586 .tg-goo-btn:active:not(:disabled) { 26587 transform: scale(0.98); 26588 } 26589 ` }), 26590 /* @__PURE__ */ re( 26591 "button", 26592 { 26593 ref: u, 26594 type: t, 26595 onClick: n, 26596 disabled: e, 26597 onMouseEnter: d, 26598 onMouseMove: h, 26599 onMouseLeave: f, 26600 className: `tg-goo-btn relative inline-flex items-center justify-center transition-transform disabled:opacity-40 ${r}`, 26601 children: [
26602 /* @__PURE__ */ re( 26603 "span", 26604 { 26605 "aria-hidden": "true", 26606 className: "absolute pointer-events-none", 26607 style: { inset: "-40px", filter: "url(#tg-goo-filter)" }, 26608 children: [ 26609 /* @__PURE__ */ P( 26610 "span", 26611 { 26612 className: "absolute rounded-full", 26613 style: { inset: "40px", background: a } 26614 } 26615 ), 26616 /* @__PURE__ */ P( 26617 "span", 26618 { 26619 ref: c, 26620 className: "tg-blob", 26621 style: { 26622 background: a, 26623 width: 56, 26624 height: 56, 26625 left: 40, 26626 top: 40, 26627 transitionDuration: "380ms" 26628 } 26629 } 26630 ), 26631 /* @__PURE__ */ P( 26632 "span", 26633 { 26634 ref: o, 26635 className: "tg-blob", 26636 style: { 26637 background: a, 26638 width: 40, 26639 height: 40, 26640 left: 40, 26641 top: 40, 26642 transitionDuration: "160ms" 26643 } 26644 } 26645 ) 26646 ] 26647 } 26648 ),
26649 /* @__PURE__ */ P( 26650 "span", 26651 { 26652 className: "relative z-10 font-['Fira_Mono:Regular',sans-serif] whitespace-nowrap", 26653 style: { color: l, padding: "16px 32px", fontSize: 16 }, 26654 children: s 26655 } 26656 ) 26657 ] 26658 } 26659 ) 26660 ] }); 26661} 26662function fE() { 26663 const n = hr(); 26664 return /* @__PURE__ */ re("div", { className: "size-full relative overflow-hidden bg-[#121212]", children: [ 26665 /* @__PURE__ */ P("div", { className: "absolute inset-0", children: /* @__PURE__ */ P(As, { mode: "grayscale", health: 0.5, parallax: !0 }) }), 26666 /* @__PURE__ */ P("div", { className: "absolute inset-0 flex items-center justify-center pointer-events-none p-6", children: /* @__PURE__ */ re(am, { className: "pointer-events-auto flex flex-col gap-10 items-center w-full max-w-[480px]", children: [ 26667 /* @__PURE__ */ re("div", { className: "flex flex-col gap-4 items-center text-[#121212]", children: [ 26668 /* @__PURE__ */ P("h1", { className: "font-['Boldonse:Regular',sans-serif] text-[48px] leading-none text-center whitespace-nowrap", children: "Touch Grass" }),
26669 /* @__PURE__ */ re("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[16px] text-center", children: [ 26670 "You spend 8 hours staring at screens.", 26671 /* @__PURE__ */ P("br", {}), 26672 "Go touch grass." 26673 ] }) 26674 ] }), 26675 /* @__PURE__ */ re("div", { className: "w-full flex flex-col gap-7 items-center", children: [ 26676 /* @__PURE__ */ P(or, { onClick: () => n("/how"), className: "w-full", children: "Fine. I'll touch grass." }), 26677 /* @__PURE__ */ P( 26678 "button", 26679 { 26680 onClick: () => n("/login"), 26681 className: "font-['Fira_Mono:Regular',sans-serif] text-[13px] text-[#121212]/70 hover:text-[#121212] underline underline-offset-4 transition-colors", 26682 children: "Log in to existing account" 26683 } 26684 ) 26685 ] }) 26686 ] }) }) 26687 ] }); 26688} 26689const pE = "/_components/v2/dfec6a6cec67b2de1eeda21cfe393b8c825ff76a/1a1198fe926b8cf424bc77e4bc23ce29ac023f09.1a1198fe.png", Wl = [ 26690 pE, 26691 "https://images.unsplash.com/photo-1597120590849-a1d5a743d155?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&q=80&w=400", 26692 "https://images.unsplash.com/photo-1617303484945-f7b0097604fb?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&q=80&w=400", 26693 "https://images.unsplash.com/photo-1599780930426-634ae627f25c?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&q=80&w=400" 26694], mE = 18, gE = 40, is = 0.04, Ii = 0.1, Qn = 0.16, In = 0.34, an = 0.4, lr = 0.54, vE = 0.6, _E = 0.98; 26695function Qu(n) { 26696 return n < 0.5 ? 2 * n * n : -1 + (4 - 2 * n) * n; 26697} 26698function ca(n) { 26699 return 1 - Math.pow(1 - n, 3); 26700} 26701function yE(n) { 26702 return n * n * n; 26703} 26704function pi(n) { 26705 return Math.max(0, Math.min(1, n)); 26706} 26707function om(n) { 26708 if (n < In) { 26709 const e = pi(n / In); 26710 return ca(e) * 0.4; 26711 } 26712 if (n < an) { 26713 const e = (n - In) / (an - In); 26714 return 0.4 + Qu(e) * 0.15; 26715 } 26716 if (n < lr) { 26717 const e = (n - an) / (lr - an); 26718 return 0.55 + ca(e) * 0.45; 26719 } 26720 return 1; 26721} 26722function xE(n) { 26723 if (n < an || n > lr) return 1; 26724 const e = (n - an) / (lr - an); 26725 return 1 + Math.sin(e * Math.PI) * 0.045; 26726} 26727function bE(n) { 26728 if (n < an - 0.04 || n > lr) return 0; 26729 const e = lr - (an - 0.04); 26730 return Math.sin((n - (an - 0.04)) / e * Math.PI); 26731} 26732function qd(n, e = 0.18) { 26733 return Math.max(0, Math.min(pi(n / e), pi((1 - n) / e))); 26734} 26735function wE(n) { 26736 const e = pi((n - an) / 0.05), t = Math.round(pi(om(n)) * 100), i = vE, r = 0.8, s = 0.78, a = _E, l = n >= i && n < r ? qd((n - i) / (r - i)) : 0, o = n >= s && n < a ? qd((n - s) / (a - s)) : 0, c = n > s + 0.04 ? pi(1 - (n - (s + 0.04)) / 0.08) : 1, u = e * c, h = Math.max(l, o) * 0.35; 26737 return { barOpacity: u, barPct: t, msg1: l, msg2: o, dim: h }; 26738} 26739const En = { x: 16, y: 76 }, nr = { x: 22, y: 18 }, ir = { x: 42, y: 6 }, xs = { x: 50, y: 50 }; 26740function iu(n) { 26741 const e = 1 - n; 26742 return { 26743 x: e * e * e * En.x + 3 * e * e * n * nr.x + 3 * e * n * n * ir.x + n * n * n * xs.x, 26744 y: e * e * e * En.y + 3 * e * e * n * nr.y + 3 * e * n * n * ir.y + n * n * n * xs.y 26745 }; 26746} 26747function SE(n) { 26748 const e = 1 - n, t = 3 * e * e * (nr.x - En.x) + 6 * e * n * (ir.x - nr.x) + 3 * n * n * (xs.x - ir.x), i = 3 * e * e * (nr.y - En.y) + 6 * e * n * (ir.y - nr.y) + 3 * n * n * (xs.y - ir.y); 26749 return Math.atan2(i, t) * 180 / Math.PI; 26750} 26751function EE(n) { 26752 if (n < Ii) return { visible: !1, x: En.x, y: En.y, scale: 0, rotate: 0, opacity: 0 }; 26753 if (n < Qn) { 26754 const e = ca((n - Ii) / (Qn - Ii)); 26755 return { visible: !0, x: En.x, y: En.y - 6 * e, scale: 0.4 + 0.6 * e, rotate: -8 + 4 * e, opacity: e }; 26756 } 26757 if (n < In) { 26758 const e = Qu((n - Qn) / (In - Qn)), t = iu(e), i = SE(e); 26759 return { visible: !0, x: t.x, y: t.y, scale: 1 - 0.15 * e, rotate: i * 0.35, opacity: 1 }; 26760 } 26761 if (n < an) { 26762 const e = yE((n - In) / (an - In)), t = iu(1); 26763 return { visible: !0, x: t.x, y: t.y, scale: 0.85 - 0.7 * e, rotate: 0, opacity: 1 - e }; 26764 } 26765 return { visible: !1, x: 50, y: 50, scale: 0, rotate: 0, opacity: 0 }; 26766} 26767function ME(n) { 26768 if (n > In + 0.04) return { visible: !1, slideIn: 0, pressed: 0, flash: 0, fade: 1 }; 26769 let e = 1; 26770 n < is && (e = ca(n / is)); 26771 let t = 0; 26772 if (n > is && n < Ii) { 26773 const s = (n - is) / (Ii - is); 26774 t = Math.sin(s * Math.PI); 26775 } 26776 let i = 0; 26777 if (n > Ii - 0.04 && n < Ii + 0.06) { 26778 const s = (n - (Ii - 0.04)) / 0.1; 26779 i = Math.sin(pi(s) * Math.PI); 26780 } 26781 let r = 0; 26782 return n > Qn && (r = pi((n - Qn) / 0.1)), { visible: !0, slideIn: e, pressed: t, flash: i, fade: r }; 26783} 26784function TE(n) { 26785 return n < is ? 0 : n < Ii ? 1 : n < an ? 2 : 3; 26786} 26787const Yd = 14, AE = Array.from({ length: Yd }, (n, e) => ({ 26788 angle: e / Yd * Math.PI * 2 + e % 3 * 0.3, 26789 speed: 60 + e * 7 % 30, 26790 size: 6 + e * 3 % 6 26791})); 26792function RE(n) { 26793 return n < an || n > lr ? { active: !1, p: 0 } : { active: !0, p: (n - an) / (lr - an) }; 26794} 26795function CE({ onStepChange: n }) { 26796 const e = mt(null), t = mt(null), [i, r] = Xe({ visible: !1, x: En.x, y: En.y, scale: 0, rotate: 0, opacity: 0 }), [s, a] = Xe({ visible: !0, slideIn: 0, pressed: 0, flash: 0, fade: 0 }), [l, o] = Xe(0), [c, u] = Xe(0), [h, d] = Xe(-1), [f, p] = Xe(0), [v, m] = Xe({ barOpacity: 0, barPct: 0, msg1: 0, msg2: 0, dim: 0 }), [g, _] = Xe(Wl[0]), x = mt(!1), E = mt(0), R = mt(n); 26797 bt(() => { 26798 R.current = n; 26799 }, [n]), bt(() => { 26800 const M = e.current, L = M.clientWidth || 600, C = M.clientHeight || 600, V = typeof window < "u" && window.matchMedia?.("(prefers-reduced-motion: reduce)").matches ? gE : mE, F = new Jo({ canvas: M, antialias: !0, alpha: !0, powerPreference: "high-performance" }); 26801 F.setPixelRatio(Math.min(window.devicePixelRatio, 1.5)), F.setSize(L, C, !1), F.setClearColor(0, 0); 26802 const I = new jo(), k = new mn(38, L / C, 0.1, 100); 26803 k.position.set(0, 0.2, 5.5), k.lookAt(0, 0, 0), I.add(new Yu(2243
26803157, 0.4)); 26804 const H = new ys(16773848, 1.8); 26805 H.position.set(3, 2.2, 2), I.add(H); 26806 const X = new ys(4880584, 0.35); 26807 X.position.set(-2.5, -0.5, -1.5), I.add(X); 26808 const K = new Ar(); 26809 I.add(K); 26810 const ae = new yn({ 26811 uniforms: { uTime: { value: 0 }, uHealth: { value: 0 } }, 26812 vertexShader: Ku, 26813 fragmentShader: rm(!1) 26814 }); 26815 K.add(new _n(new Ms(1.1, 64, 64), ae)); 26816 const se = new Zt(), he = new W(0, 1, 0), Ce = []; 26817 let Ie = 42; 26818 const Ee = () => (Ie = Ie * 1664525 + 1013904223 >>> 0, Ie / 4294967296); 26819 for (let lt = 0; lt < 80; lt++) { 26820 let ut, Tt, D; 26821 do 26822 ut = Ee() * 2 - 1, Tt = Ee() * 2 - 1, D = ut * ut + Tt * Tt; 26823 while (D >= 1); 26824 const Rt = Math.sqrt(1 - D), Qe = new W(2 * ut * Rt, 2 * Tt * Rt, 1 - 2 * D).normalize(); 26825 if (Math.abs(Qe.y) > 0.86) continue; 26826 const dt = Qe.clone(), pe = new Wn().setFromUnitVectors(he, dt); 26827 pe.premultiply(new Wn().setFromAxisAngle(dt, Ee() * Math.PI * 2)), Ce.push({ 26828 pos: dt.clone().multiplyScalar(1.1 + 5e-3), 26829 quat: pe, 26830 baseScale: 0.85 + Ee() * 0.45, 26831 threshold: 0.55 + Ee() * 0.4 26832 }); 26833 } 26834 const J = new Ea(8e-3, 0.013, 0.05, 5); 26835 J.translate(0, 0.025, 0); 26836 const le = new Xo(0.055, 0.12, 7); 26837 le.translate(0, 0.1, 0); 26838 const te = nm([J, le]), ie = new Xu({ color: 2779668, emissive: 332803, shininess: 8, flatShading: !0 }), fe = new $u(te, ie, Ce.length); 26839 fe.frustumCulled = !1, K.add(fe); 26840 function Se(lt, ut, Tt) { 26841 const D = Math.max(0, Math.min(1, (Tt - lt) / (ut - lt))); 26842 return D * D * (3 - D * 2); 26843 } 26844 let Fe = 0, Me = performance.now(), Ke = -1, at = -1; 26845 function Ue(lt) { 26846 const ut = (lt - Me) / 1e3; 26847 Me = lt, x.current || (E.current += ut); 26848 const Tt = E.current, D = Tt % V / V, Rt = Math.floor(Tt / V); 26849 Rt !== at && (at = Rt, _(Wl[Rt % Wl.length])); 26850 const Qe = om(D); 26851 ae.uniforms.uTime.value = Tt, ae.uniforms.uHealth.value = Qe; 26852 for (let oe = 0; oe < Ce.length; oe++) { 26853 const { pos: me, quat: ve, baseScale: Z, threshold: ee } = Ce[oe], Ae = Se(ee, ee + 0.08, Qe); 26854 se.position.copy(me), se.quaternion.copy(ve), se.scale.setScalar(Math.max(1e-4, Ae * Z)), se.updateMatrix(), fe.setMatrixAt(oe, se.matrix); 26855 } 26856 fe.instanceMatrix.needsUpdate = !0, r(EE(D)), a(ME(D)), o(bE(D)), m(wE(D)); 26857 const { active: dt, p: pe } = RE(D); 26858 p(dt ? pe : 0); 26859 let At = 0; 26860 if (D > Qn - 0.05 && D < In + 0.1) { 26861 const oe = pi((D - (Qn - 0.05)) / 0.15), me = pi((In + 0.1 - D) / 0.2); 26862 At = Math.min(oe, me) * 0.55; 26863 } 26864 u(At); 26865 let A = -1; 26866 D >= Qn && D < In && (A = Qu((D - Qn) / (In - Qn))), d(A); 26867 const b = TE(D); 26868 b !== Ke && (Ke = b, R.current?.(b)), K.scale.setScalar(xE(D)), K.rotation.y += x.current ? 0 : ut * 0.08; 26869 const G = M.clientWidth, Q = M.clientHeight; 26870 (M.width !== G || M.height !== Q) && (F.setSize(G, Q, !1), k.aspect = G / Q, k.updateProjectionMatrix()), F.render(I, k), Fe = requestAnimationFrame(Ue); 26871 } 26872 return Fe = requestAnimationFrame(Ue), () => { 26873 cancelAnimationFrame(Fe), F.dispose(); 26874 }; 26875 }, []); 26876 const T = `M ${En.x} ${En.y} C ${nr.x} ${nr.y}, ${ir.x} ${ir.y}, ${xs.x} ${xs.y}`, w = 6, y = h > 0 ? Array.from({ length: w }, (M, L) => { 26877 const C = (L + 1) * 0.045, U = h - C; 26878 if (U < 0) return null; 26879 const V = iu(U); 26880 return { x: V.x, y: V.y, opacity: (1 - L / w) * 0.35, scale: 0.85 - L * 0.07 }; 26881 }).filter(Boolean) : []; 26882 return /* @__PURE__ */ re( 26883 "div", 26884 { 26885 ref: t, 26886 className: "relative w-full h-full overflow-hidden", 26887 style: { cursor: "default" }, 26888 children: [
26889 /* @__PURE__ */ P("canvas", { ref: e, className: "w-full h-full block" }), 26890 /* @__PURE__ */ re( 26891 "svg", 26892 { 26893 className: "absolute inset-0 w-full h-full pointer-events-none", 26894 viewBox: "0 0 100 100", 26895 preserveAspectRatio: "none", 26896 style: { opacity: c }, 26897 children: [ 26898 /* @__PURE__ */ P("defs", { children: /* @__PURE__ */ re("linearGradient", { id: "arcGrad", x1: "0%", y1: "100%", x2: "100%", y2: "0%", children: [ 26899 /* @__PURE__ */ P("stop", { offset: "0%", stopColor: "#a8ff9c", stopOpacity: "0.9" }), 26900 /* @__PURE__ */ P("stop", { offset: "100%", stopColor: "#5ed47a", stopOpacity: "0.4" }) 26901 ] }) }), 26902 /* @__PURE__ */ P( 26903 "path", 26904 { 26905 d: T, 26906 fill: "none", 26907 stroke: "url(#arcGrad)", 26908 strokeWidth: "0.4", 26909 strokeDasharray: "1.2 1.4", 26910 strokeLinecap: "round", 26911 vectorEffect: "non-scaling-stroke" 26912 } 26913 ) 26914 ] 26915 } 26916 ), 26917 s.visible && /* @__PURE__ */ P( 26918 "div", 26919 { 26920 className: "absolute pointer-events-none", 26921 style: { 26922 left: `${En.x}%`, 26923 top: `${En.y}%`, 26924 transform: `translate(-50%, -50%) translateX(${(1 - s.slideIn) * -120}px) scale(${0.95 + s.pressed * 0.03})`, 26925 opacity: (1 - s.fade) * s.slideIn, 26926 filter: "drop-shadow(0 14px 20px rgba(0,0,0,0.55))" 26927 }, 26928 children: /* @__PURE__ */ P( 26929 "div", 26930 { 26931 style: { 26932 width: 120, 26933 height: 180, 26934 borderRadius: 18, 26935 background: "linear-gradient(160deg, #1c1c20, #0a0a0c)", 26936 border: "1px solid #2a2a2e", 26937 padding: 8, 26938 position: "relative", 26939 overflow: "hidden" 26940 }, 26941 children: /* @__PURE__ */ re( 26942 "div", 26943 { 26944 style: { 26945 width: "100%", 26946 height: "100%", 26947 borderRadius: 12, 26948 background: "linear-gradient(180deg, #2a2f3a, #14161c)", 26949 display: "flex", 26950 flexDirection: "column", 26951 alignItems: "center", 26952 justifyContent: "flex-end", 26953 padding: 8, 26954 gap: 6, 26955 position: "relative" 26956 }, 26957 children: [
26958 /* @__PURE__ */ P( 26959 "div", 26960 { 26961 style: { 26962 width: "90%", 26963 flex: 1, 26964 borderRadius: 8, 26965 backgroundImage: `url(${g})`, 26966 backgroundSize: "cover", 26967 backgroundPosition: "center", 26968 marginTop: 4, 26969 boxShadow: "inset 0 0 0 1px rgba(255,255,255,0.08)" 26970 } 26971 } 26972 ), 26973 /* @__PURE__ */ P( 26974 "div", 26975 { 26976 style: { 26977 width: "90%", 26978 padding: "6px 8px", 26979 borderRadius: 999, 26980 background: s.pressed > 0.2 ? "#1f8a18" : "#32bb29", 26981 color: "#fff", 26982 fontSize: 9, 26983 fontFamily: "ui-monospace, monospace", 26984 textAlign: "center", 26985 transform: `scale(${1 - s.pressed * 0.05})`, 26986 textTransform: "uppercase", 26987 letterSpacing: 0.5 26988 }, 26989 children: "Upload" 26990 } 26991 ),
26992 /* @__PURE__ */ P( 26993 "div", 26994 { 26995 style: { 26996 position: "absolute", 26997 inset: 0, 26998 background: "#fff", 26999 opacity: s.flash * 0.85, 27000 pointerEvents: "none", 27001 borderRadius: 12 27002 } 27003 } 27004 ) 27005 ] 27006 } 27007 ) 27008 } 27009 ) 27010 } 27011 ), 27012 y.map((M, L) => /* @__PURE__ */ P( 27013 "div", 27014 { 27015 className: "absolute pointer-events-none", 27016 style: { 27017 left: `${M.x}%`, 27018 top: `${M.y}%`, 27019 transform: `translate(-50%, -50%) scale(${M.scale})`, 27020 opacity: M.opacity, 27021 filter: "blur(1px)" 27022 }, 27023 children: /* @__PURE__ */ P("div", { className: "bg-white", style: { padding: "5px 5px 14px 5px" }, children: /* @__PURE__ */ P("img", { src: g, alt: "", style: { width: 60, height: 76, display: "block", objectFit: "cover" } }) }) 27024 }, 27025 L 27026 )),
27027 /* @__PURE__ */ P( 27028 "div", 27029 { 27030 className: "absolute inset-0 pointer-events-none flex items-center justify-center", 27031 style: { opacity: l }, 27032 children: /* @__PURE__ */ P( 27033 "div", 27034 { 27035 style: { 27036 width: "55%", 27037 aspectRatio: "1", 27038 borderRadius: "50%", 27039 background: "radial-gradient(circle, rgba(200,255,200,0.65) 0%, rgba(120,220,140,0.30) 35%, rgba(80,180,120,0) 65%)", 27040 transform: `scale(${0.55 + l * 0.85})`, 27041 filter: "blur(2px)" 27042 } 27043 } 27044 ) 27045 } 27046 ), 27047 f > 0 && /* @__PURE__ */ P("div", { className: "absolute inset-0 pointer-events-none flex items-center justify-center", children: AE.map((M, L) => { 27048 const C = M.speed * ca(f), U = 1 - f * f; 27049 return /* @__PURE__ */ P( 27050 "div", 27051 { 27052 style: { 27053 position: "absolute", 27054 width: M.size, 27055 height: M.size, 27056 borderRadius: "50%", 27057 background: "radial-gradient(circle, #c5ffae 0%, #4caf50 60%, rgba(76,175,80,0) 100%)", 27058 transform: `translate(${Math.cos(M.angle) * C}px, ${Math.sin(M.angle) * C}px) scale(${1 - f * 0.4})`, 27059 opacity: U, 27060 filter: "blur(0.6px)" 27061 } 27062 }, 27063 L 27064 ); 27065 }) }), 27066 i.visible && /* @__PURE__ */ P( 27067 "div", 27068 { 27069 className: "absolute pointer-events-none", 27070 style: { 27071 left: `${i.x}%`, 27072 top: `${i.y}%`, 27073 transform: `translate(-50%, -50%) rotate(${i.rotate}deg) scale(${i.scale})`, 27074 opacity: i.opacity, 27075 filter: "drop-shadow(0 14px 20px rgba(0,0,0,0.5))" 27076 }, 27077 children: /* @__PURE__ */ P("div", { className: "bg-white", style: { padding: "8px 8px 22px 8px" }, children: /* @__PURE__ */ P("img", { src: g, alt: "Outdoor photo", className: "block object-cover", style: { width: 100, height: 128 } }) }) 27078 } 27079 ),
27080 /* @__PURE__ */ P( 27081 "div", 27082 { 27083 className: "absolute inset-0 pointer-events-none", 27084 style: { background: `rgba(0,0,0,${v.dim})` } 27085 } 27086 ), 27087 /* @__PURE__ */ re( 27088 "div", 27089 { 27090 className: "absolute left-1/2 pointer-events-none", 27091 style: { 27092 bottom: "14%", 27093 transform: "translateX(-50%)", 27094 width: "min(60%, 320px)", 27095 opacity: v.barOpacity, 27096 transition: "opacity 220ms ease-out" 27097 }, 27098 children: [ 27099 /* @__PURE__ */ P("div", { className: "bg-white/20 rounded-full p-[3px] overflow-hidden", children: /* @__PURE__ */ P( 27100 "div", 27101 { 27102 className: "bg-[#32bb29] rounded-full", 27103 style: { width: `${v.barPct}%`, height: 8, transition: "width 140ms linear" } 27104 } 27105 ) }), 27106 /* @__PURE__ */ re( 27107 "p", 27108 { 27109 className: "font-['Fira_Mono:Regular',sans-serif] text-white/85 text-center mt-2", 27110 style: { fontSize: 12, letterSpacing: 0.4, textShadow: "0 2px 12px rgba(0,0,0,0.7)" }, 27111 children: [ 27112 v.barPct, 27113 "% thriving" 27114 ] 27115 } 27116 ) 27117 ] 27118 } 27119 ),
27120 /* @__PURE__ */ re("div", { className: "absolute inset-0 pointer-events-none flex items-center justify-center", children: [ 27121 /* @__PURE__ */ P( 27122 "p", 27123 { 27124 className: "font-['Fira_Mono:Regular',sans-serif] text-white text-center px-6", 27125 style: { 27126 opacity: v.msg1, 27127 fontSize: 20, 27128 letterSpacing: 0.5, 27129 textShadow: "0 2px 12px rgba(0,0,0,0.7)", 27130 transform: `translateY(${(1 - v.msg1) * 8}px)`, 27131 position: "absolute" 27132 }, 27133 children: "Your planet is thriving." 27134 } 27135 ), 27136 /* @__PURE__ */ P( 27137 "p", 27138 { 27139 className: "font-['Fira_Mono:Regular',sans-serif] text-white text-center px-6", 27140 style: { 27141 opacity: v.msg2, 27142 fontSize: 16, 27143 letterSpacing: 0.4, 27144 textShadow: "0 2px 12px rgba(0,0,0,0.7)", 27145 transform: `translateY(${(1 - v.msg2) * 8}px)`, 27146 position: "absolute", 27147 maxWidth: 360 27148 }, 27149 children: "Touch grass every day so your planet won't die." 27150 } 27151 ) 27152 ] }) 27153 ] 27154 } 27155 ); 27156} 27157function PE() { 27158 const n = hr(), [e, t] = Xe(0); 27159 return /* @__PURE__ */ re("div", { className: "size-full relative overflow-hidden bg-black flex", children: [ 27160 /* @__PURE__ */ P("div", { className: "flex-1 relative min-w-0", children: /* @__PURE__ */ P(CE, { onStepChange: t }) }), 27161 /* @__PURE__ */ re( 27162 "div", 27163 { 27164 className: "shrink-0 bg-[#32bb29] flex flex-col gap-10 items-start justify-center overflow-y-auto p-10", 27165 style: { 27166 width: "min(480px, 40vw)", 27167 minHeight: "100%", 27168 borderTopLeftRadius: "48px", 27169 borderBottomLeftRadius: "48px" 27170 }, 27171 children: [
27172 /* @__PURE__ */ re("div", { className: "flex flex-col gap-8 w-full text-black", children: [ 27173 /* @__PURE__ */ P("p", { className: "font-['Boldonse:Regular',sans-serif] text-[32px]", children: "Your daily mission:" }), 27174 /* @__PURE__ */ P("div", { className: "flex flex-col gap-6 w-full", children: [ 27175 { label: "Step 1", description: "Go outside" }, 27176 { label: "Step 2", description: "Take one photo" }, 27177 { label: "Step 3", description: "Bring the planet back to life" } 27178 ].map((r, s) => { 27179 const a = s + 1, l = e === a, o = e > a; 27180 return /* @__PURE__ */ P( 27181 LE, 27182 { 27183 label: r.label, 27184 description: r.description, 27185 active: l, 27186 done: o 27187 }, 27188 r.label 27189 ); 27190 }) }) 27191 ] }), 27192 /* @__PURE__ */ P("div", { className: "w-full", children: /* @__PURE__ */ P(or, { onClick: () => n("/start"), className: "w-full", children: "I'm in" }) }) 27193 ] 27194 } 27195 ) 27196 ] }); 27197} 27198function LE({ 27199 label: n, 27200 description: e, 27201 active: t, 27202 done: i 27203}) { 27204 return /* @__PURE__ */ re( 27205 "div", 27206 { 27207 className: "flex flex-col gap-1 items-start w-full transition-all duration-300", 27208 style: { opacity: t ? 1 : i ? 0.45 : 0.65, transform: t ? "translateX(6px)" : "translateX(0)" }, 27209 children: [
27210 /* @__PURE__ */ re("div", { className: "flex items-center gap-2", children: [ 27211 /* @__PURE__ */ P("p", { className: "font-['Boldonse:Regular',sans-serif] uppercase tracking-wider text-black text-[20px]", children: n }), 27212 i && /* @__PURE__ */ P("span", { className: "font-['Fira_Mono:Regular',sans-serif] text-black text-[14px]", children: "â" }), 27213 t && /* @__PURE__ */ P( 27214 "span", 27215 { 27216 className: "inline-block w-2 h-2 rounded-full bg-black", 27217 style: { animation: "pulse 1.2s ease-in-out infinite" } 27218 } 27219 ) 27220 ] }), 27221 /* @__PURE__ */ P( 27222 "p", 27223 { 27224 className: "font-['Fira_Mono:Regular',sans-serif] text-black text-[16px]", 27225 style: { textDecoration: i ? "line-through" : "none" }, 27226 children: e 27227 } 27228 ) 27229 ] 27230 } 27231 ); 27232} 27233var NE = Object.defineProperty, Io = Object.getOwnPropertySymbols, lm = Object.prototype.hasOwnProperty, cm = Object.prototype.propertyIsEnumerable, Kd = (n, e, t) => e in n ? NE(n, e, { enumerable: !0, configurable: !0, writable: !0, value: t }) : n[e] = t, ru = (n, e) => { 27234 for (var t in e || (e = {})) 27235 lm.call(e, t) && Kd(n, t, e[t]); 27236 if (Io) 27237 for (var t of Io(e)) 27238 cm.call(e, t) && Kd(n, t, e[t]); 27239 return n; 27240}, su = (n, e) => { 27241 var t = {}; 27242 for (var i in n) 27243 lm.call(n, i) && e.indexOf(i) < 0 && (t[i] = n[i]); 27244 if (n != null && Io) 27245 for (var i of Io(n)) 27246 e.indexOf(i) < 0 && cm.call(n, i) && (t[i] = n[i]); 27247 return t; 27248}; 27249/** 27250 * @license QR Code generator library (TypeScript) 27251 * Copyright (c) Project Nayuki. 27252 * SPDX-License-Identifier: MIT 27253 */ 27254var Lr; 27255((n) => { 27256 const e = class pt { 27257 /*-- Constructor (low level) and fields --*/ 27258 // Creates a new QR Code with the given version number, 27259 // error correction level, data codeword bytes, and mask number. 27260 // This is a low-level API that most users should not use directly. 27261 // A mid-level API is the encodeSegments() function. 27262 constructor(o, c, u, h) { 27263 if (this.version = o, this.errorCorrectionLevel = c, this.modules = [], this.isFunction = [], o < pt.MIN_VERSION || o > pt.MAX_VERSION) 27264 throw new RangeError("Version value out of range"); 27265 if (h < -1 || h > 7) 27266 throw new RangeError("Mask value out of range"); 27267 this.size = o * 4 + 17; 27268 let d = []; 27269 for (let p = 0; p < this.size; p++) 27270 d.push(!1); 27271 for (let p = 0; p < this.size; p++) 27272 this.modules.push(d.slice()), this.isFunction.push(d.slice()); 27273 this.drawFunctionPatterns(); 27274 const f = this.addEccAndInterleave(u); 27275 if (this.drawCodewords(f), h == -1) { 27276 let p = 1e9; 27277 for (let v = 0; v < 8; v++) { 27278 this.applyMask(v), this.drawFormatBits(v); 27279 const m = this.getPenaltyScore(); 27280 m < p && (h = v, p = m), this.applyMask(v); 27281 } 27282 } 27283 r(0 <= h && h <= 7), this.mask = h, this.applyMask(h), this.drawFormatBits(h), this.isFunction = []; 27284 } 27285 /*-- Static factory functions (high level) --*/ 27286 // Returns a QR Code representing the given Unicode text string at the given error correction level. 27287 // As a conservative upper bound, this function is guaranteed to succeed for strings that have 738 or fewer 27288 // Unicode code points (not UTF-16 code units) if the low error correction level is used. The smallest possible 27289 // QR Code version is automatically chosen for the output. The ECC level of the result may be higher than the 27290 // ecl argument if it can be done without increasing the version. 27291 static encodeText(o, c) { 27292 const u = n.QrSegment.makeSegments(o); 27293 return pt.encodeSegments(u, c); 27294 }
vendor: 22,665 bytes, lines 27295-27751
27295 // Returns a QR Code representing the given binary data at the given error correction level. 27296 // This function always encodes using the binary segment mode, not any text mode. The maximum number of 27297 // bytes allowed is 2953. The smallest possible QR Code version is automatically chosen for the output. 27298 // The ECC level of the result may be higher than the ecl argument if it can be done without increasing the version. 27299 static encodeBinary(o, c) { 27300 const u = n.QrSegment.makeBytes(o); 27301 return pt.encodeSegments([u], c); 27302 } 27303 /*-- Static factory functions (mid level) --*/ 27304 // Returns a QR Code representing the given segments with the given encoding parameters. 27305 // The smallest possible QR Code version within the given range is automatically 27306 // chosen for the output. Iff boostEcl is true, then the ECC level of the result 27307 // may be higher than the ecl argument if it can be done without increasing the 27308 // version. The mask number is either between 0 to 7 (inclusive) to force that 27309 // mask, or -1 to automatically choose an appropriate mask (which may be slow). 27310 // This function allows the user to create a custom sequence of segments that switches 27311 // between modes (such as alphanumeric and byte) to encode text in less space. 27312 // This is a mid-level API; the high-level API is encodeText() and encodeBinary(). 27313 static encodeSegments(o, c, u = 1, h = 40, d = -1, f = !0) { 27314 if (!(pt.MIN_VERSION <= u && u <= h && h <= pt.MAX_VERSION) || d < -1 || d > 7) 27315 throw new RangeError("Invalid value"); 27316 let p, v; 27317 for (p = u; ; p++) { 27318 const x = pt.getNumDataCodewords(p, c) * 8, E = a.getTotalBits(o, p); 27319 if (E <= x) { 27320 v = E; 27321 break; 27322 } 27323 if (p >= h) 27324 throw new RangeError("Data too long"); 27325 } 27326 for (const x of [pt.Ecc.MEDIUM, pt.Ecc.QUARTILE, pt.Ecc.HIGH]) 27327 f && v <= pt.getNumDataCodewords(p, x) * 8 && (c = x); 27328 let m = []; 27329 for (const x of o) { 27330 t(x.mode.modeBits, 4, m), t(x.numChars, x.mode.numCharCountBits(p), m); 27331 for (const E of x.getData()) 27332 m.push(E); 27333 } 27334 r(m.length == v); 27335 const g = pt.getNumDataCodewords(p, c) * 8; 27336 r(m.length <= g), t(0, Math.min(4, g - m.length), m), t(0, (8 - m.length % 8) % 8, m), r(m.length % 8 == 0); 27337 for (let x = 236; m.length < g; x ^= 253) 27338 t(x, 8, m); 27339 let _ = []; 27340 for (; _.length * 8 < m.length; ) 27341 _.push(0); 27342 return m.forEach((x, E) => _[E >>> 3] |= x << 7 - (E & 7)), new pt(p, c, _, d); 27343 } 27344 /*-- Accessor methods --*/ 27345 // Returns the color of the module (pixel) at the given coordinates, which is false 27346 // for light or true for dark. The top left corner has the coordinates (x=0, y=0). 27347 // If the given coordinates are out of bounds, then false (light) is returned. 27348 getModule(o, c) { 27349 return 0 <= o && o < this.size && 0 <= c && c < this.size && this.modules[c][o]; 27350 } 27351 // Modified to expose modules for easy access 27352 getModules() { 27353 return this.modules; 27354 } 27355 /*-- Private helper methods for constructor: Drawing function modules --*/ 27356 // Reads this object's version field, and draws and marks all function modules. 27357 drawFunctionPatterns() { 27358 for (let u = 0; u < this.size; u++) 27359 this.setFunctionModule(6, u, u % 2 == 0), this.setFunctionModule(u, 6, u % 2 == 0); 27360 this.drawFinderPattern(3, 3), this.drawFinderPattern(this.size - 4, 3), this.drawFinderPattern(3, this.size - 4); 27361 const o = this.getAlignmentPatternPositions(), c = o.length; 27362 for (let u = 0; u < c; u++) 27363 for (let h = 0; h < c; h++) 27364 u == 0 && h == 0 || u == 0 && h == c - 1 || u == c - 1 && h == 0 || this.drawAlignmentPattern(o[u], o[h]); 27365 this.drawFormatBits(0), this.drawVersion(); 27366 } 27367 // Draws two copies of the format bits (with its own error correction code) 27368 // based on the given mask and this object's error correction level field. 27369 drawFormatBits(o) { 27370 const c = this.errorCorrectionLevel.formatBits << 3 | o; 27371 let u = c; 27372 for (let d = 0; d < 10; d++) 27373 u = u << 1 ^ (u >>> 9) * 1335; 27374 const h = (c << 10 | u) ^ 21522; 27375 r(h >>> 15 == 0); 27376 for (let d = 0; d <= 5; d++) 27377 this.setFunctionModule(8, d, i(h, d)); 27378 this.setFunctionModule(8, 7, i(h, 6)), this.setFunctionModule(8, 8, i(h, 7)), this.setFunctionModule(7, 8, i(h, 8)); 27379 for (let d = 9; d < 15; d++) 27380 this.setFunctionModule(14 - d, 8, i(h, d)); 27381 for (let d = 0; d < 8; d++) 27382 this.setFunctionModule(this.size - 1 - d, 8, i(h, d)); 27383 for (let d = 8; d < 15; d++) 27384 this.setFunctionModule(8, this.size - 15 + d, i(h, d)); 27385 this.setFunctionModule(8, this.size - 8, !0); 27386 } 27387 // Draws two copies of the version bits (with its own error correction code), 27388 // based on this object's version field, iff 7 <= version <= 40. 27389 drawVersion() { 27390 if (this.version < 7) 27391 return; 27392 let o = this.version; 27393 for (let u = 0; u < 12; u++) 27394 o = o << 1 ^ (o >>> 11) * 7973; 27395 const c = this.version << 12 | o; 27396 r(c >>> 18 == 0); 27397 for (let u = 0; u < 18; u++) { 27398 const h = i(c, u), d = this.size - 11 + u % 3, f = Math.floor(u / 3); 27399 this.setFunctionModule(d, f, h), this.setFunctionModule(f, d, h); 27400 } 27401 } 27402 // Draws a 9*9 finder pattern including the border separator, 27403 // with the center module at (x, y). Modules can be out of bounds. 27404 drawFinderPattern(o, c) { 27405 for (let u = -4; u <= 4; u++) 27406 for (let h = -4; h <= 4; h++) { 27407 const d = Math.max(Math.abs(h), Math.abs(u)), f = o + h, p = c + u; 27408 0 <= f && f < this.size && 0 <= p && p < this.size && this.setFunctionModule(f, p, d != 2 && d != 4); 27409 } 27410 } 27411 // Draws a 5*5 alignment pattern, with the center module 27412 // at (x, y). All modules must be in bounds. 27413 drawAlignmentPattern(o, c) { 27414 for (let u = -2; u <= 2; u++) 27415 for (let h = -2; h <= 2; h++) 27416 this.setFunctionModule(o + h, c + u, Math.max(Math.abs(h), Math.abs(u)) != 1); 27417 } 27418 // Sets the color of a module and marks it as a function module. 27419 // Only used by the constructor. Coordinates must be in bounds. 27420 setFunctionModule(o, c, u) { 27421 this.modules[c][o] = u, this.isFunction[c][o] = !0; 27422 } 27423 /*-- Private helper methods for constructor: Codewords and masking --*/ 27424 // Returns a new byte string representing the given data with the appropriate error correction 27425 // codewords appended to it, based on this object's version and error correction level. 27426 addEccAndInterleave(o) { 27427 const c = this.version, u = this.errorCorrectionLevel; 27428 if (o.length != pt.getNumDataCodewords(c, u)) 27429 throw new RangeError("Invalid argument"); 27430 const h = pt.NUM_ERROR_CORRECTION_BLOCKS[u.ordinal][c], d = pt.ECC_CODEWORDS_PER_BLOCK[u.ordinal][c], f = Math.floor(pt.getNumRawDataModules(c) / 8), p = h - f % h, v = Math.floor(f / h); 27431 let m = []; 27432 const g = pt.reedSolomonComputeDivisor(d); 27433 for (let x = 0, E = 0; x < h; x++) { 27434 let R = o.slice(E, E + v - d + (x < p ? 0 : 1)); 27435 E += R.length; 27436 const T = pt.reedSolomonComputeRemainder(R, g); 27437 x < p && R.push(0), m.push(R.concat(T)); 27438 } 27439 let _ = []; 27440 for (let x = 0; x < m[0].length; x++) 27441 m.forEach((E, R) => { 27442 (x != v - d || R >= p) && _.push(E[x]); 27443 }); 27444 return r(_.length == f), _; 27445 } 27446 // Draws the given sequence of 8-bit codewords (data and error correction) onto the entire 27447 // data area of this QR Code. Function modules need to be marked off before this is called. 27448 drawCodewords(o) { 27449 if (o.length != Math.floor(pt.getNumRawDataModules(this.version) / 8)) 27450 throw new RangeError("Invalid argument"); 27451 let c = 0; 27452 for (let u = this.size - 1; u >= 1; u -= 2) { 27453 u == 6 && (u = 5); 27454 for (let h = 0; h < this.size; h++) 27455 for (let d = 0; d < 2; d++) { 27456 const f = u - d, v = (u + 1 & 2) == 0 ? this.size - 1 - h : h; 27457 !this.isFunction[v][f] && c < o.length * 8 && (this.modules[v][f] = i(o[c >>> 3], 7 - (c & 7)), c++); 27458 } 27459 } 27460 r(c == o.length * 8); 27461 } 27462 // XORs the codeword modules in this QR Code with the given mask pattern. 27463 // The function modules must be marked and the codeword bits must be drawn 27464 // before masking. Due to the arithmetic of XOR, calling applyMask() with 27465 // the same mask value a second time will undo the mask. A final well-formed 27466 // QR Code needs exactly one (not zero, two, etc.) mask applied. 27467 applyMask(o) { 27468 if (o < 0 || o > 7) 27469 throw new RangeError("Mask value out of range"); 27470 for (let c = 0; c < this.size; c++) 27471 for (let u = 0; u < this.size; u++) { 27472 let h; 27473 switch (o) { 27474 case 0: 27475 h = (u + c) % 2 == 0; 27476 break; 27477 case 1: 27478 h = c % 2 == 0; 27479 break; 27480 case 2: 27481 h = u % 3 == 0; 27482 break; 27483 case 3: 27484 h = (u + c) % 3 == 0; 27485 break; 27486 case 4: 27487 h = (Math.floor(u / 3) + Math.floor(c / 2)) % 2 == 0; 27488 break; 27489 case 5: 27490 h = u * c % 2 + u * c % 3 == 0; 27491 break; 27492 case 6: 27493 h = (u * c % 2 + u * c % 3) % 2 == 0; 27494 break; 27495 case 7: 27496 h = ((u + c) % 2 + u * c % 3) % 2 == 0; 27497 break; 27498 default: 27499 throw new Error("Unreachable"); 27500 } 27501 !this.isFunction[c][u] && h && (this.modules[c][u] = !this.modules[c][u]); 27502 } 27503 } 27504 // Calculates and returns the penalty score based on state of this QR Code's current modules. 27505 // This is used by the automatic mask choice algorithm to find the mask pattern that yields the lowest score. 27506 getPenaltyScore() { 27507 let o = 0; 27508 for (let d = 0; d < this.size; d++) { 27509 let f = !1, p = 0, v = [0, 0, 0, 0, 0, 0, 0]; 27510 for (let m = 0; m < this.size; m++) 27511 this.modules[d][m] == f ? (p++, p == 5 ? o += pt.PENALTY_N1 : p > 5 && o++) : (this.finderPenaltyAddHistory(p, v), f || (o += this.finderPenaltyCountPatterns(v) * pt.PENALTY_N3), f = this.modules[d][m], p = 1); 27512 o += this.finderPenaltyTerminateAndCount(f, p, v) * pt.PENALTY_N3; 27513 } 27514 for (let d = 0; d < this.size; d++) { 27515 let f = !1, p = 0, v = [0, 0, 0, 0, 0, 0, 0]; 27516 for (let m = 0; m < this.size; m++) 27517 this.modules[m][d] == f ? (p++, p == 5 ? o += pt.PENALTY_N1 : p > 5 && o++) : (this.finderPenaltyAddHistory(p, v), f || (o += this.finderPenaltyCountPatterns(v) * pt.PENALTY_N3), f = this.modules[m][d], p = 1); 27518 o += this.finderPenaltyTerminateAndCount(f, p, v) * pt.PENALTY_N3; 27519 } 27520 for (let d = 0; d < this.size - 1; d++) 27521 for (let f = 0; f < this.size - 1; f++) { 27522 const p = this.modules[d][f]; 27523 p == this.modules[d][f + 1] && p == this.modules[d + 1][f] && p == this.modules[d + 1][f + 1] && (o += pt.PENALTY_N2); 27524 } 27525 let c = 0; 27526 for (const d of this.modules) 27527 c = d.reduce((f, p) => f + (p ? 1 : 0), c); 27528 const u = this.size * this.size, h = Math.ceil(Math.abs(c * 20 - u * 10) / u) - 1; 27529 return r(0 <= h && h <= 9), o += h * pt.PENALTY_N4, r(0 <= o && o <= 2568888), o; 27530 } 27531 /*-- Private helper functions --*/ 27532 // Returns an ascending list of positions of alignment patterns for this version number. 27533 // Each position is in the range [0,177), and are used on both the x and y axes. 27534 // This could be implemented as lookup table of 40 variable-length lists of integers. 27535 getAlignmentPatternPositions() { 27536 if (this.version == 1) 27537 return []; 27538 { 27539 const o = Math.floor(this.version / 7) + 2, c = this.version == 32 ? 26 : Math.ceil((this.version * 4 + 4) / (o * 2 - 2)) * 2; 27540 let u = [6]; 27541 for (let h = this.size - 7; u.length < o; h -= c) 27542 u.splice(1, 0, h); 27543 return u; 27544 } 27545 } 27546 // Returns the number of data bits that can be stored in a QR Code of the given version number, after 27547 // all function modules are excluded. This includes remainder bits, so it might not be a multiple of 8. 27548 // The result is in the range [208, 29648]. This could be implemented as a 40-entry lookup table. 27549 static getNumRawDataModules(o) { 27550 if (o < pt.MIN_VERSION || o > pt.MAX_VERSION) 27551 throw new RangeError("Version number out of range"); 27552 let c = (16 * o + 128) * o + 64; 27553 if (o >= 2) { 27554 const u = Math.floor(o / 7) + 2; 27555 c -= (25 * u - 10) * u - 55, o >= 7 && (c -= 36); 27556 } 27557 return r(208 <= c && c <= 29648), c; 27558 } 27559 // Returns the number of 8-bit data (i.e. not error correction) codewords contained in any 27560 // QR Code of the given version number and error correction level, with remainder bits discarded. 27561 // This stateless pure function could be implemented as a (40*4)-cell lookup table. 27562 static getNumDataCodewords(o, c) { 27563 return Math.floor(pt.getNumRawDataModules(o) / 8) - pt.ECC_CODEWORDS_PER_BLOCK[c.ordinal][o] * pt.NUM_ERROR_CORRECTION_BLOCKS[c.ordinal][o]; 27564 } 27565 // Returns a Reed-Solomon ECC generator polynomial for the given degree. This could be 27566 // implemented as a lookup table over all possible parameter values, instead of as an algorithm. 27567 static reedSolomonComputeDivisor(o) { 27568 if (o < 1 || o > 255) 27569 throw new RangeError("Degree out of range"); 27570 let c = []; 27571 for (let h = 0; h < o - 1; h++) 27572 c.push(0); 27573 c.push(1); 27574 let u = 1; 27575 for (let h = 0; h < o; h++) { 27576 for (let d = 0; d < c.length; d++) 27577 c[d] = pt.reedSolomonMultiply(c[d], u), d + 1 < c.length && (c[d] ^= c[d + 1]); 27578 u = pt.reedSolomonMultiply(u, 2); 27579 } 27580 return c; 27581 } 27582 // Returns the Reed-Solomon error correction codeword for the given data and divisor polynomials. 27583 static reedSolomonComputeRemainder(o, c) { 27584 let u = c.map((h) => 0); 27585 for (const h of o) { 27586 const d = h ^ u.shift(); 27587 u.push(0), c.forEach((f, p) => u[p] ^= pt.reedSolomonMultiply(f, d)); 27588 } 27589 return u; 27590 } 27591 // Returns the product of the two given field elements modulo GF(2^8/0x11D). The arguments and result 27592 // are unsigned 8-bit integers. This could be implemented as a lookup table of 256*256 entries of uint8. 27593 static reedSolomonMultiply(o, c) { 27594 if (o >>> 8 || c >>> 8) 27595 throw new RangeError("Byte out of range"); 27596 let u = 0; 27597 for (let h = 7; h >= 0; h--) 27598 u = u << 1 ^ (u >>> 7) * 285, u ^= (c >>> h & 1) * o; 27599 return r(u >>> 8 == 0), u; 27600 } 27601 // Can only be called immediately after a light run is added, and 27602 // returns either 0, 1, or 2. A helper function for getPenaltyScore(). 27603 finderPenaltyCountPatterns(o) { 27604 const c = o[1]; 27605 r(c <= this.size * 3); 27606 const u = c > 0 && o[2] == c && o[3] == c * 3 && o[4] == c && o[5] == c; 27607 return (u && o[0] >= c * 4 && o[6] >= c ? 1 : 0) + (u && o[6] >= c * 4 && o[0] >= c ? 1 : 0); 27608 } 27609 // Must be called at the end of a line (row or column) of modules. A helper function for getPenaltyScore(). 27610 finderPenaltyTerminateAndCount(o, c, u) { 27611 return o && (this.finderPenaltyAddHistory(c, u), c = 0), c += this.size, this.finderPenaltyAddHistory(c, u), this.finderPenaltyCountPatterns(u); 27612 } 27613 // Pushes the given value to the front and drops the last value. A helper function for getPenaltyScore(). 27614 finderPenaltyAddHistory(o, c) { 27615 c[0] == 0 && (o += this.size), c.pop(), c.unshift(o); 27616 } 27617 }; 27618 e.MIN_VERSION = 1, e.MAX_VERSION = 40, e.PENALTY_N1 = 3, e.PENALTY_N2 = 3, e.PENALTY_N3 = 40, e.PENALTY_N4 = 10, e.ECC_CODEWORDS_PER_BLOCK = [ 27619 // Version: (note that index 0 is for padding, and is set to an illegal value) 27620 //0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level 27621 [-1, 7, 10, 15, 20, 26, 18, 20, 24, 30, 18, 20, 24, 26, 30, 22, 24, 28, 30, 28, 28, 28, 28, 30, 30, 26, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], 27622 // Low 27623 [-1, 10, 16, 26, 18, 24, 16, 18, 22, 22, 26, 30, 22, 22, 24, 24, 28, 28, 26, 26, 26, 26, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28], 27624 // Medium 27625 [-1, 13, 22, 18, 26, 18, 24, 18, 22, 20, 24, 28, 26, 24, 20, 30, 24, 28, 28, 26, 30, 28, 30, 30, 30, 30, 28, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30], 27626 // Quartile 27627 [-1, 17, 28, 22, 16, 22, 28, 26, 26, 24, 28, 24, 28, 22, 24, 24, 30, 28, 28, 26, 28, 30, 24, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30, 30] 27628 // High 27629 ], e.NUM_ERROR_CORRECTION_BLOCKS = [ 27630 // Version: (note that index 0 is for padding, and is set to an illegal value) 27631 //0, 1, 2, 3, 4, 5, 6, 7, 8, 9,10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40 Error correction level 27632 [-1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 4, 4, 4, 4, 4, 6, 6, 6, 6, 7, 8, 8, 9, 9, 10, 12, 12, 12, 13, 14, 15, 16, 17, 18, 19, 19, 20, 21, 22, 24, 25], 27633 // Low 27634 [-1, 1, 1, 1, 2, 2, 4, 4, 4, 5, 5, 5, 8, 9, 9, 10, 10, 11, 13, 14, 16, 17, 17, 18, 20, 21, 23, 25, 26, 28, 29, 31, 33, 35, 37, 38, 40, 43, 45, 47, 49], 27635 // Medium 27636 [-1, 1, 1, 2, 2, 4, 4, 6, 6, 8, 8, 8, 10, 12, 16, 12, 17, 16, 18, 21, 20, 23, 23, 25, 27, 29, 34, 34, 35, 38, 40, 43, 45, 48, 51, 53, 56, 59, 62, 65, 68], 27637 // Quartile 27638 [-1, 1, 1, 2, 4, 4, 4, 5, 6, 8, 8, 11, 11, 16, 16, 18, 16, 19, 21, 25, 25, 25, 34, 30, 32, 35, 37, 40, 42, 45, 48, 51, 54, 57, 60, 63, 66, 70, 74, 77, 81] 27639 // High 27640 ], n.QrCode = e; 27641 function t(l, o, c) { 27642 if (o < 0 || o > 31 || l >>> o) 27643 throw new RangeError("Value out of range"); 27644 for (let u = o - 1; u >= 0; u--) 27645 c.push(l >>> u & 1); 27646 } 27647 function i(l, o) { 27648 return (l >>> o & 1) != 0; 27649 } 27650 function r(l) { 27651 if (!l) 27652 throw new Error("Assertion error"); 27653 } 27654 const s = class zt { 27655 /*-- Constructor (low level) and fields --*/ 27656 // Creates a new QR Code segment with the given attributes and data. 27657 // The character count (numChars) must agree with the mode and the bit buffer length, 27658 // but the constraint isn't checked. The given bit buffer is cloned and stored. 27659 constructor(o, c, u) { 27660 if (this.mode = o, this.numChars = c, this.bitData = u, c < 0) 27661 throw new RangeError("Invalid argument"); 27662 this.bitData = u.slice(); 27663 } 27664 /*-- Static factory functions (mid level) --*/ 27665 // Returns a segment representing the given binary data encoded in 27666 // byte mode. All input byte arrays are acceptable. Any text string 27667 // can be converted to UTF-8 bytes and encoded as a byte mode segment. 27668 static makeBytes(o) { 27669 let c = []; 27670 for (const u of o) 27671 t(u, 8, c); 27672 return new zt(zt.Mode.BYTE, o.length, c); 27673 } 27674 // Returns a segment representing the given string of decimal digits encoded in numeric mode. 27675 static makeNumeric(o) { 27676 if (!zt.isNumeric(o)) 27677 throw new RangeError("String contains non-numeric characters"); 27678 let c = []; 27679 for (let u = 0; u < o.length; ) { 27680 const h = Math.min(o.length - u, 3); 27681 t(parseInt(o.substring(u, u + h), 10), h * 3 + 1, c), u += h; 27682 } 27683 return new zt(zt.Mode.NUMERIC, o.length, c); 27684 } 27685 // Returns a segment representing the given text string encoded in alphanumeric mode. 27686 // The characters allowed are: 0 to 9, A to Z (uppercase only), space, 27687 // dollar, percent, asterisk, plus, hyphen, period, slash, colon. 27688 static makeAlphanumeric(o) { 27689 if (!zt.isAlphanumeric(o)) 27690 throw new RangeError("String contains unencodable characters in alphanumeric mode"); 27691 let c = [], u; 27692 for (u = 0; u + 2 <= o.length; u += 2) { 27693 let h = zt.ALPHANUMERIC_CHARSET.indexOf(o.charAt(u)) * 45; 27694 h += zt.ALPHANUMERIC_CHARSET.indexOf(o.charAt(u + 1)), t(h, 11, c); 27695 } 27696 return u < o.length && t(zt.ALPHANUMERIC_CHARSET.indexOf(o.charAt(u)), 6, c), new zt(zt.Mode.ALPHANUMERIC, o.length, c); 27697 } 27698 // Returns a new mutable list of zero or more segments to represent the given Unicode text string. 27699 // The result may use various segment modes and switch modes to optimize the length of the bit stream. 27700 static makeSegments(o) { 27701 return o == "" ? [] : zt.isNumeric(o) ? [zt.makeNumeric(o)] : zt.isAlphanumeric(o) ? [zt.makeAlphanumeric(o)] : [zt.makeBytes(zt.toUtf8ByteArray(o))]; 27702 } 27703 // Returns a segment representing an Extended Channel Interpretation 27704 // (ECI) designator with the given assignment value. 27705 static makeEci(o) { 27706 let c = []; 27707 if (o < 0) 27708 throw new RangeError("ECI assignment value out of range"); 27709 if (o < 128) 27710 t(o, 8, c); 27711 else if (o < 16384) 27712 t(2, 2, c), t(o, 14, c); 27713 else if (o < 1e6) 27714 t(6, 3, c), t(o, 21, c); 27715 else 27716 throw new RangeError("ECI assignment value out of range"); 27717 return new zt(zt.Mode.ECI, 0, c); 27718 } 27719 // Tests whether the given string can be encoded as a segment in numeric mode. 27720 // A string is encodable iff each character is in the range 0 to 9. 27721 static isNumeric(o) { 27722 return zt.NUMERIC_REGEX.test(o); 27723 } 27724 // Tests whether the given string can be encoded as a segment in alphanumeric mode. 27725 // A string is encodable iff each character is in the following set: 0 to 9, A to Z 27726 // (uppercase only), space, dollar, percent, asterisk, plus, hyphen, period, slash, colon. 27727 static isAlphanumeric(o) { 27728 return zt.ALPHANUMERIC_REGEX.test(o); 27729 } 27730 /*-- Methods --*/ 27731 // Returns a new copy of the data bits of this segment. 27732 getData() { 27733 return this.bitData.slice(); 27734 } 27735 // (Package-private) Calculates and returns the number of bits needed to encode the given segments at 27736 // the given version. The result is infinity if a segment has too many characters to fit its length field. 27737 static getTotalBits(o, c) { 27738 let u = 0; 27739 for (const h of o) { 27740 const d = h.mode.numCharCountBits(c); 27741 if (h.numChars >= 1 << d) 27742 return 1 / 0; 27743 u += 4 + d + h.bitData.length; 27744 } 27745 return u; 27746 } 27747 // Returns a new array of bytes representing the given string encoded in UTF-8. 27748 static toUtf8ByteArray(o) { 27749 o = encodeURI(o); 27750 let c = []; 27751 for (let u = 0; u < o.length; u++)
27752 o.charAt(u) != "%" ? c.push(o.charCodeAt(u)) : (c.push(parseInt(o.substring(u + 1, u + 3), 16)), u += 2); 27753 return c; 27754 } 27755 }; 27756 s.NUMERIC_REGEX = /^[0-9]*$/, s.ALPHANUMERIC_REGEX = /^[A-Z0-9 $%*+.\/:-]*$/, s.ALPHANUMERIC_CHARSET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:"; 27757 let a = s; 27758 n.QrSegment = s; 27759})(Lr || (Lr = {})); 27760((n) => { 27761 ((e) => { 27762 const t = class { 27763 // The QR Code can tolerate about 30% erroneous codewords 27764 /*-- Constructor and fields --*/ 27765 constructor(r, s) { 27766 this.ordinal = r, this.formatBits = s; 27767 } 27768 }; 27769 t.LOW = new t(0, 1), t.MEDIUM = new t(1, 0), t.QUARTILE = new t(2, 3), t.HIGH = new t(3, 2), e.Ecc = t; 27770 })(n.QrCode || (n.QrCode = {})); 27771})(Lr || (Lr = {})); 27772((n) => { 27773 ((e) => { 27774 const t = class { 27775 /*-- Constructor and fields --*/ 27776 constructor(r, s) { 27777 this.modeBits = r, this.numBitsCharCount = s; 27778 } 27779 /*-- Method --*/ 27780 // (Package-private) Returns the bit width of the character count field for a segment in 27781 // this mode in a QR Code at the given version number. The result is in the range [0, 16]. 27782 numCharCountBits(r) { 27783 return this.numBitsCharCount[Math.floor((r + 7) / 17)]; 27784 } 27785 }; 27786 t.NUMERIC = new t(1, [10, 12, 14]), t.ALPHANUMERIC = new t(2, [9, 11, 13]), t.BYTE = new t(4, [8, 16, 16]), t.KANJI = new t(8, [8, 10, 12]), t.ECI = new t(7, [0, 0, 0]), e.Mode = t; 27787 })(n.QrSegment || (n.QrSegment = {})); 27788})(Lr || (Lr = {})); 27789var ls = Lr; 27790/** 27791 * @license qrcode.react 27792 * Copyright (c) Paul O'Shannessy 27793 * SPDX-License-Identifier: ISC 27794 */ 27795var IE = { 27796 L: ls.QrCode.Ecc.LOW, 27797 M: ls.QrCode.Ecc.MEDIUM, 27798 Q: ls.QrCode.Ecc.QUARTILE, 27799 H: ls.QrCode.Ecc.HIGH 27800}, um = 128, hm = "L", dm = "#FFFFFF", fm = "#000000", pm = !1, mm = 1, DE = 4, UE = 0, OE = 0.1; 27801function gm(n, e = 0) { 27802 const t = []; 27803 return n.forEach(function(i, r) { 27804 let s = null; 27805 i.forEach(function(a, l) { 27806 if (!a && s !== null) { 27807 t.push( 27808 `M${s + e} ${r + e}h${l - s}v1H${s + e}z` 27809 ), s = null; 27810 return; 27811 } 27812 if (l === i.length - 1) { 27813 if (!a) 27814 return; 27815 s === null ? t.push(`M${l + e},${r + e} h1v1H${l + e}z`) : t.push( 27816 `M${s + e},${r + e} h${l + 1 - s}v1H${s + e}z` 27817 ); 27818 return; 27819 } 27820 a && s === null && (s = l); 27821 }); 27822 }), t.join(""); 27823} 27824function vm(n, e) { 27825 return n.slice().map((t, i) => i < e.y || i >= e.y + e.h ? t : t.map((r, s) => s < e.x || s >= e.x + e.w ? r : !1)); 27826} 27827function kE(n, e, t, i) { 27828 if (i == null) 27829 return null; 27830 const r = n.length + t * 2, s = Math.floor(e * OE), a = r / e, l = (i.width || s) * a, o = (i.height || s) * a, c = i.x == null ? n.length / 2 - l / 2 : i.x * a, u = i.y == null ? n.length / 2 - o / 2 : i.y * a, h = i.opacity == null ? 1 : i.opacity; 27831 let d = null; 27832 if (i.excavate) { 27833 let p = Math.floor(c), v = Math.floor(u), m = Math.ceil(l + c - p), g = Math.ceil(o + u - v); 27834 d = { x: p, y: v, w: m, h: g }; 27835 } 27836 const f = i.crossOrigin; 27837 return { x: c, y: u, h: o, w: l, excavation: d, opacity: h, crossOrigin: f }; 27838} 27839function FE(n, e) { 27840 return e != null ? Math.max(Math.floor(e), 0) : n ? DE : UE; 27841} 27842function _m({ 27843 value: n, 27844 level: e, 27845 minVersion: t, 27846 includeMargin: i, 27847 marginSize: r, 27848 imageSettings: s, 27849 size: a, 27850 boostLevel: l 27851}) { 27852 let o = Jt.useMemo(() => { 27853 const p = (Array.isArray(n) ? n : [n]).reduce((v, m) => (v.push(...ls.QrSegment.makeSegments(m)), v), []); 27854 return ls.QrCode.encodeSegments( 27855 p, 27856 IE[e], 27857 t, 27858 void 0, 27859 void 0, 27860 l 27861 ); 27862 }, [n, e, t, l]); 27863 const { cells: c, margin: u, numCells: h, calculatedImageSettings: d } = Jt.useMemo(() => { 27864 let f = o.getModules(); 27865 const p = FE(i, r), v = f.length + p * 2, m = kE( 27866 f, 27867 a, 27868 p, 27869 s 27870 ); 27871 return { 27872 cells: f, 27873 margin: p, 27874 numCells: v, 27875 calculatedImageSettings: m 27876 }; 27877 }, [o, a, s, i, r]); 27878 return { 27879 qrcode: o, 27880 margin: u, 27881 cells: c, 27882 numCells: h, 27883 calculatedImageSettings: d 27884 }; 27885} 27886var BE = (function() { 27887 try { 27888 new Path2D().addPath(new Path2D()); 27889 } catch { 27890 return !1; 27891 } 27892 return !0; 27893})(), zE = Jt.forwardRef( 27894 function(e, t) { 27895 const i = e, { 27896 value: r, 27897 size: s = um, 27898 level: a = hm, 27899 bgColor: l = dm, 27900 fgColor: o = fm, 27901 includeMargin: c = pm, 27902 minVersion: u = mm, 27903 boostLevel: h, 27904 marginSize: d, 27905 imageSettings: f 27906 } = i, v = su(i, [ 27907 "value", 27908 "size", 27909 "level", 27910 "bgColor", 27911 "fgColor", 27912 "includeMargin", 27913 "minVersion", 27914 "boostLevel", 27915 "marginSize", 27916 "imageSettings" 27917 ]), { style: m } = v, g = su(v, ["style"]), _ = f?.src, x = Jt.useRef(null), E = Jt.useRef(null), R = Jt.useCallback( 27918 (F) => { 27919 x.current = F, typeof t == "function" ? t(F) : t && (t.current = F); 27920 }, 27921 [t] 27922 ), [T, w] = Jt.useState(!1), { margin: y, cells: M, numCells: L, calculatedImageSettings: C } = _m({ 27923 value: r, 27924 level: a, 27925 minVersion: u, 27926 boostLevel: h, 27927 includeMargin: c, 27928 marginSize: d, 27929 imageSettings: f, 27930 size: s 27931 }); 27932 Jt.useEffect(() => { 27933 if (x.current != null) { 27934 const F = x.current, I = F.getContext("2d"); 27935 if (!I) 27936 return; 27937 let k = M; 27938 const H = E.current, X = C != null && H !== null && H.complete && H.naturalHeight !== 0 && H.naturalWi
27938dth !== 0; 27939 X && C.excavation != null && (k = vm( 27940 M, 27941 C.excavation 27942 )); 27943 const K = window.devicePixelRatio || 1; 27944 F.height = F.width = s * K; 27945 const ae = s / L * K; 27946 I.scale(ae, ae), I.fillStyle = l, I.fillRect(0, 0, L, L), I.fillStyle = o, BE ? I.fill(new Path2D(gm(k, y))) : M.forEach(function(se, he) { 27947 se.forEach(function(Ce, Ie) { 27948 Ce && I.fillRect(Ie + y, he + y, 1, 1); 27949 }); 27950 }), C && (I.globalAlpha = C.opacity), X && I.drawImage( 27951 H, 27952 C.x + y, 27953 C.y + y, 27954 C.w, 27955 C.h 27956 ); 27957 } 27958 }), Jt.useEffect(() => { 27959 w(!1); 27960 }, [_]); 27961 const U = ru({ height: s, width: s }, m); 27962 let V = null; 27963 return _ != null && (V = /* @__PURE__ */ Jt.createElement( 27964 "img", 27965 { 27966 src: _, 27967 key: _, 27968 style: { display: "none" }, 27969 onLoad: () => { 27970 w(!0); 27971 }, 27972 ref: E, 27973 crossOrigin: C?.crossOrigin 27974 } 27975 )), /* @__PURE__ */ Jt.createElement(Jt.Fragment, null, /* @__PURE__ */ Jt.createElement( 27976 "canvas", 27977 ru({ 27978 style: U, 27979 height: s, 27980 width: s, 27981 ref: R, 27982 role: "img" 27983 }, g) 27984 ), V); 27985 } 27986); 27987zE.displayName = "QRCodeCanvas"; 27988var eh = Jt.forwardRef( 27989 function(e, t) { 27990 const i = e, { 27991 value: r, 27992 size: s = um, 27993 level: a = hm, 27994 bgColor: l = dm, 27995 fgColor: o = fm, 27996 includeMargin: c = pm, 27997 minVersion: u = mm, 27998 boostLevel: h, 27999 title: d, 28000 marginSize: f, 28001 imageSettings: p 28002 } = i, v = su(i, [ 28003 "value", 28004 "size", 28005 "level", 28006 "bgColor", 28007 "fgColor", 28008 "includeMargin", 28009 "minVersion", 28010 "boostLevel", 28011 "title", 28012 "marginSize", 28013 "imageSettings" 28014 ]), { margin: m, cells: g, numCells: _, calculatedImageSettings: x } = _m({ 28015 value: r, 28016 level: a, 28017 minVersion: u, 28018 boostLevel: h, 28019 includeMargin: c, 28020 marginSize: f, 28021 imageSettings: p, 28022 size: s 28023 }); 28024 let E = g, R = null; 28025 p != null && x != null && (x.excavation != null && (E = vm( 28026 g, 28027 x.excavation 28028 )), R = /* @__PURE__ */ Jt.createElement( 28029 "image", 28030 { 28031 href: p.src, 28032 height: x.h, 28033 width: x.w, 28034 x: x.x + m, 28035 y: x.y + m, 28036 preserveAspectRatio: "none", 28037 opacity: x.opacity, 28038 crossOrigin: x.crossOrigin 28039 } 28040 )); 28041 const T = gm(E, m); 28042 return /* @__PURE__ */ Jt.createElement( 28043 "svg", 28044 ru({ 28045 height: s, 28046 width: s,
28047 viewBox: `0 0 ${_} ${_}`, 28048 ref: t, 28049 role: "img" 28050 }, v), 28051 !!d && /* @__PURE__ */ Jt.createElement("title", null, d), 28052 /* @__PURE__ */ Jt.createElement( 28053 "path", 28054 { 28055 fill: l, 28056 d: `M0,0 h${_}v${_}H0z`, 28057 shapeRendering: "crispEdges" 28058 } 28059 ), 28060 /* @__PURE__ */ Jt.createElement("path", { fill: o, d: T, shapeRendering: "crispEdges" }), 28061 R 28062 ); 28063 } 28064); 28065eh.displayName = "QRCodeSVG"; 28066const HE = "/_components/v2/dfec6a6cec67b2de1eeda21cfe393b8c825ff76a/bayu-syaits-7yqsC3uDlV0-unsplash__1_.91b5b1cf.jpg", GE = "/_components/v2/dfec6a6cec67b2de1eeda21cfe393b8c825ff76a/valeriia-bilousova-U-wrVctNx6k-unsplash__1_.682e7d38.jpg", VE = "/_components/v2/dfec6a6cec67b2de1eeda21cfe393b8c825ff76a/krisztina-papp-ND5zJAxKRqo-unsplash__1_.8b9ac2ec.jpg", WE = "/_components/v2/dfec6a6cec67b2de1eeda21cfe393b8c825ff76a/fabrizio-conti-3TPDdXG0FwM-unsplash__1_.28638384.jpg", $E = "/_components/v2/dfec6a6cec67b2de1eeda21cfe393b8c825ff76a/altumcode-Vr-7axBnmjE-unsplash__1_.5685925c.jpg", jE = "/_components/v2/dfec6a6cec67b2de1eeda21cfe393b8c825ff76a/val-vesa-dV1ShxBfX5s-unsplash__1_.c55c0620.jpg", XE = "/_components/v2/dfec6a6cec67b2de1eeda21cfe393b8c825ff76a/illia-panasenko-DlZ3swPF4UI-unsplash__1_.5fcf5c62.jpg", qE = "/_components/v2/dfec6a6cec67b2de1eeda21cfe393b8c825ff76a/nathan-dumlao-3w_hlbOAibU-unsplash__1_.9381b89d.jpg", _i = (n) => `https://images.unsplash.com/${n}?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&q=80&w=320`, YE = _i("photo-1464295440335-ee082a75ccca"), KE = _i("photo-1697946979172-fbeb94bf57b0"), JE = _i("photo-1641570599342-36953beede98"), ZE = _i("photo-1527840330704-143cde6c566e"), QE = _i("photo-1623067607218-196e4f76aa4b"), eM = _i("photo-1721369780881-74bab5181261"), tM = _i("photo-1601784529732-557f84f923f2"), nM = _i("photo-1591184508248-1a02b97197c6"), iM = _i("photo-1561297489-bbf7a3871769"), rM = _i("photo-1691315039493-0d627a38a7c4"), sM = [ 28067 { 28068 radiusFactor: 0.78, 28069 tiltDeg: 14, 28070 yawDeg: -6, 28071 periodSec: 56, 28072 direction: 1, 28073 photos: [ 28074 { img: HE, card: 10, scaleMul: 0.78, brightness: 1.02 }, 28075 { img: GE, card: -14, scaleMul: 0.62, brightness: 0.96 }, 28076 { img: VE, card: 6, scaleMul: 0.84, brightness: 1 }, 28077 { img: WE, card: -10, scaleMul: 0.68, brightness: 1.05 }, 28078 { img: $E, card: 16, scaleMul: 0.74, brightness: 0.98 }, 28079 { img: jE, card: -12, scaleMul: 0.58, brightness: 1.03 } 28080 ] 28081 }, 28082 { 28083 radiusFactor: 1.06, 28084 tiltDeg: 34, 28085 yawDeg: 12, 28086 periodSec: 78, 28087 direction: -1, 28088 photos: [ 28089 { img: XE, card: -6, scaleMul: 0.92, brightness: 1 }, 28090 { img: qE, card: 14, scaleMul: 0.7, brightness: 0.97 }, 28091 { img: YE, card: -9, scaleMul: 0.88, brightness: 1.04 }, 28092 { img: KE, card: 18, scaleMul: 0.66, brightness: 1 }, 28093 { img: JE, card: -4, scaleMul: 0.8, brightness: 0.95 }, 28094 { img: ZE, card: 12, scaleMul: 0.74, brightness: 1.06 } 28095 ] 28096 }, 28097 { 28098 radiusFactor: 1.34, 28099 tiltDeg: 6, 28100 yawDeg: -18, 28101 periodSec: 96, 28102 direction: 1, 28103 photos: [ 28104 { img: QE, card: -16, scaleMul: 1, brightness: 1 }, 28105 { img: eM, card: 8, scaleMul: 0.86, brightness: 0.98 }, 28106 { img: tM, card: -10, scaleMul: 0.94, brightness: 1.03 }, 28107 { img: nM, card: 14, scaleMul: 0.82, brightness: 0.96 }, 28108 { img: iM, card: -6, scaleMul: 0.9, brightness: 1.01 }, 28109 { img: rM, card: 12, scaleMul: 0.78, brightness: 1 } 28110 ] 28111 } 28112], aM = 60, oM = 76, lM = 0.5, $l = sM.flatMap((n) => { 28113 const e = n.tiltDeg * Math.PI / 180, t = n.yawDeg * Math.PI / 180, i = Math.cos(e), r = Math.sin(e), s = Math.cos(t), a = Math.sin(t); 28114 return n.photos.map((l, o) => ({ 28115 ring: n, 28116 photo: l, 28117 phase: o / n.photos.length, 28118 tiltRad: e, 28119 yawRad: t, 28120 cosTilt: i, 28121 sinTilt: r, 28122 cosYaw: s, 28123 sinYaw: a, 28124 bobSeed: o * 1.7 + n.tiltDeg * 0.13 28125 })); 28126}); 28127function cM(n) { 28128 return Math.max(0, Math.min(1, n)); 28129} 28130function uM() { 28131 const n = mt([]); 28132 return bt(() => { 28133 const e = performance.now(); 28134 let t = 0, i = Math.min(window.innerWidth, window.innerHeight) * 0.42; 28135 const r = () => { 28136 i = Math.min(window.innerWidth, window.innerHeight) * 0.42; 28137 }; 28138 window.addEventListener("resize", r, { passive: !0 }); 28139 function s(a) { 28140 const l = (a - e) / 1e3; 28141 for (let o = 0; o < $l.length; o++) { 28142 const c = n.current[o]; 28143 if (!c) continue; 28144 const u = $l[o], { ring: h, photo: d } = u, f = (l / h.periodSec * h.direction + u.phase) % 1, p = (f < 0 ? f + 1 : f) * Math.PI * 2, v = i * h.radiusFactor, m = Math.
28144cos(p) * v, g = Math.sin(p) * v, _ = Math.sin(l * 0.35 + u.bobSeed) * i * 0.025, x = _ * u.cosTilt - g * u.sinTilt, E = _ * u.sinTilt + g * u.cosTilt, R = m, T = R * u.cosYaw - E * u.sinYaw, w = R * u.sinYaw + E * u.cosYaw, y = x, M = cM(w / v * 0.5 + 0.5), L = (0.62 + 0.5 * M) * d.scaleMul, C = 0.42 + 0.58 * M, U = Math.hypot(T, y), F = w < 0 && U < i * lM ? 0 : C, I = h.direction * (-(p * 180) / Math.PI + 90), k = h.tiltDeg, H = d.card + Math.sin(l * 0.22 + u.bobSeed) * 1.4; 28145 c.style.transform = `translate3d(${T.toFixed(2)}px, ${y.toFixed(2)}px, 0) translate(-50%, -50%) rotateY(${I.toFixed(2)}deg) rotateX(${k.toFixed(2)}deg) rotateZ(${H.toFixed(2)}deg) scale(${L.toFixed(4)})`, c.style.opacity = F.toFixed(3), c.style.zIndex = String(Math.round(M * 100)), c.style.filter = `brightness(${(d.brightness * (0.78 + 0.22 * M)).toFixed(3)})`; 28146 } 28147 t = requestAnimationFrame(s); 28148 } 28149 return t = requestAnimationFrame(s), () => { 28150 cancelAnimationFrame(t), window.removeEventListener("resize", r); 28151 }; 28152 }
28152, []), /* @__PURE__ */ P( 28153 "div", 28154 { 28155 className: "absolute inset-0 pointer-events-none", 28156 style: { 28157 zIndex: 5, 28158 perspective: "1400px", 28159 perspectiveOrigin: "50% 50%" 28160 }, 28161 children: /* @__PURE__ */ P( 28162 "div", 28163 { 28164 className: "absolute", 28165 style: { left: "50%", top: "50%", transformStyle: "preserve-3d" }, 28166 children: $l.map((e, t) => /* @__PURE__ */ P( 28167 "div", 28168 { 28169 ref: (i) => { 28170 n.current[t] = i; 28171 }, 28172 className: "absolute", 28173 style: { 28174 left: 0, 28175 top: 0, 28176 willChange: "transform, opacity", 28177 transformStyle: "preserve-3d", 28178 backfaceVisibility: "hidden" 28179 }, 28180 children: /* @__PURE__ */ P( 28181 "div", 28182 { 28183 style: { 28184 background: "white", 28185 padding: "6px 6px 18px 6px", 28186 boxShadow: "0 1px 0 rgba(255,255,255,0.6) inset, 0 10px 24px rgba(0,0,0,0.45), 0 2px 6px rgba(0,0,0,0.35)" 28187 }, 28188 children: /* @__PURE__ */ P( 28189 "div", 28190 { 28191 style: { 28192 width: `${aM}px`, 28193 height: `${oM}px`, 28194 backgroundImage: `url(${e.photo.img})`, 28195 backgroundSize: "cover", 28196 backgroundPosition: "center", 28197 backgroundRepeat: "no-repeat", 28198 boxShadow: "inset 0 0 0 1px rgba(0,0,0,0.06)" 28199 } 28200 } 28201 ) 28202 } 28203 ) 28204 }, 28205 t 28206 )) 28207 } 28208 ) 28209 } 28210 ); 28211} 28212function Qo(n, e) { 28213 var t = {}; 28214 for (var i in n) Object.prototype.hasOwnProperty.call(n, i) && e.indexOf(i) < 0 && (t[i] = n[i]); 28215 if (n != null && typeof Object.getOwnPropertySymbols == "function") 28216 for (var r = 0, i = Object.getOwnPropertySymbols(n); r < i.length; r++) 28217 e.indexOf(i[r]) < 0 && Object.prototype.propertyIsEnumerable.call(n, i[r]) && (t[i[r]] = n[i[r]]); 28218 return t; 28219} 28220function hM(n, e, t, i) { 28221 function r(s) { 28222 return s instanceof t ? s : new t(function(a) { 28223 a(s); 28224 }); 28225 } 28226 return new (t || (t = Promise))(function(s, a) { 28227 function l(u) { 28228 try { 28229 c(i.next(u)); 28230 } catch (h) { 28231 a(h); 28232 } 28233 } 28234 function o(u) { 28235 try { 28236 c(i.throw(u)); 28237 } catch (h) { 28238 a(h); 28239 } 28240 } 28241 function c(u) { 28242 u.done ? s(u.value) : r(u.value).then(l, o); 28243 } 28244 c((i = i.apply(n, e || [])).next()); 28245 }); 28246} 28247const dM = (n) => n ? (...e) => n(...e) : (...e) => fetch(...e);
28248class th extends Error { 28249 constructor(e, t = "FunctionsError", i) { 28250 super(e), this.name = t, this.context = i; 28251 } 28252 toJSON() { 28253 return { 28254 name: this.name, 28255 message: this.message, 28256 context: this.context 28257 }; 28258 } 28259} 28260class fM extends th { 28261 constructor(e) { 28262 super("Failed to send a request to the Edge Function", "FunctionsFetchError", e); 28263 } 28264} 28265class Jd extends th { 28266 constructor(e) { 28267 super("Relay Error invoking the Edge Function", "FunctionsRelayError", e); 28268 } 28269} 28270class Zd extends th { 28271 constructor(e) { 28272 super("Edge Function returned a non-2xx status code", "FunctionsHttpError", e); 28273 } 28274} 28275var au; 28276(function(n) { 28277 n.Any = "any", n.ApNortheast1 = "ap-northeast-1", n.ApNortheast2 = "ap-northeast-2", n.ApSouth1 = "ap-south-1", n.ApSoutheast1 = "ap-southeast-1", n.ApSoutheast2 = "ap-southeast-2", n.CaCentral1 = "ca-central-1", n.EuCentral1 = "eu-central-1", n.EuWest1 = "eu-west-1", n.EuWest2 = "eu-west-2", n.EuWest3 = "eu-west-3", n.SaEast1 = "sa-east-1", n.UsEast1 = "us-east-1", n.UsWest1 = "us-west-1", n.UsWest2 = "us-west-2"; 28278})(au || (au = {})); 28279class pM { 28280 /** 28281 * Creates a new Functions client bound to an Edge Functions URL. 28282 * 28283 * @example Using supabase-js (recommended) 28284 * ```ts 28285 * import { createClient } from '@supabase/supabase-js' 28286 * 28287 * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key') 28288 * const { data, error } = await supabase.functions.invoke('hello-world') 28289 * ``` 28290 * 28291 * @category Edge Functions 28292 * 28293 * @example Standalone import for bundle-sensitive environments 28294 * ```ts 28295 * import { FunctionsClient, FunctionRegion } from '@supabase/functions-js' 28296 * 28297 * const functions = new FunctionsClient('https://xyzcompany.supabase.co/functions/v1', { 28298 * headers: { apikey: 'your-publishable-key' }, 28299 * region: FunctionRegion.UsEast1, 28300 * }) 28301 * ``` 28302 */ 28303 constructor(e, { headers: t = {}, customFetch: i, region: r = au.Any } = {}) { 28304 this.url = e, this.headers = t, this.region = r, this.fetch = dM(i); 28305 } 28306 /** 28307 * Updates the authorization header 28308 * @param token - the new jwt token sent in the authorisation header 28309 * 28310 * @category Edge Functions 28311 * 28312 * @example Setting the authorization header 28313 * ```ts 28314 * functions.setAuth(session.access_token) 28315 * ``` 28316 */ 28317 setAuth(e) { 28318 this.headers.Authorization = `Bearer ${e}`; 28319 } 28320 /** 28321 * Invokes a function 28322 * @param functionName - The name of the Function to invoke. 28323 * @param options - Options for invoking the Function. 28324 * @example 28325 * ```ts 28326 * const { data, error } = await functions.invoke('hello-world', { 28327 * body: { name: 'Ada' }, 28328 * }) 28329 * ``` 28330 * 28331 * @category Edge Functions 28332 * 28333 * @remarks 28334 * - Requires an Authorization header. 28335 * - Invoke params generally match the [Fetch API](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) spec. 28336 * - When you pass in a body to your function, we automatically attach the Content-Type header for `Blob`, `ArrayBuffer`, `File`, `FormData` and `String`. If it doesn't match any of these types we assume the payload is `json`, serialize it and attach the `Content-Type` header as `application/json`. You can override this behavior by passing in a `Content-Type` header of your own. 28337 * - Responses are automatically parsed as `json`, `blob` and `form-data` depending on the `Content-Type` header sent by your function. Responses are parsed as `text` by default. 28338 * 28339 * @example Basic invocation 28340 * ```js 28341 * const { data, error } = await supabase.functions.invoke('hello', { 28342 * body: { foo: 'bar' } 28343 * }) 28344 * ``` 28345 * 28346 * @exampleDescription Error handling 28347 * A `FunctionsHttpError` error is returned if your function throws an error, `FunctionsRelayError` if the Supabase Relay has an error processing your function and `FunctionsFetchError` if there is a network error in calling your function. Log the full error object so fields like `name`, `context`, and any structured body aren't hidden. 28348 * 28349 * @example Error handling 28350 * ```js 28351 * import { FunctionsHttpError, FunctionsRelayError, FunctionsFetchError } from "@supabase/supabase-js"; 28352 * 28353 * const { data, error } = await supabase.functions.invoke('hello', { 28354 * headers: { 28355 * "my-custom-header": 'my-custom-header-value' 28356 * }, 28357 * body: { foo: 'bar' } 28358 * }) 28359 * 28360 * if (error instanceof FunctionsHttpError) { 28361 * const errorMessage = await error.context.json() 28362 * console.error('Function returned an error', errorMessage) 28363 * } else if (error instanceof FunctionsRelayError) { 28364 * console.error('Relay error:', error) 28365 * } else if (error instanceof FunctionsFetchError) { 28366 * console.error('Fetch error:', error) 28367 * } 28368 * ``` 28369 * 28370 * @exampleDescription Passing custom headers 28371 * You can pass custom headers to your function. Note: supabase-js automatically passes the `Authorization` header with the signed in user's JWT. 28372 * 28373 * @example Passing custom headers 28374 * ```js 28375 * const { data, error } = await supabase.functions.invoke('hello', { 28376 * headers: { 28377 * "my-custom-header": 'my-custom-header-value' 28378 * }, 28379 * body: { foo: 'bar' } 28380 * }) 28381 * ``` 28382 * 28383 * @exampleDescription Calling with DELETE HTTP verb 28384 * You can also set the HTTP verb to `DELETE` when calling your Edge Function. 28385 * 28386 * @example Calling with DELETE HTTP verb 28387 * ```js 28388 * const { data, error } = await supabase.functions.invoke('hello', { 28389 * headers: { 28390 * "my-custom-header": 'my-custom-header-value' 28391 * }, 28392 * body: { foo: 'bar' }, 28393 * method: 'DELETE' 28394 * }) 28395 * ``` 28396 * 28397 * @exampleDescription Invoking a Function in the UsEast1 region 28398 * Here are the available regions: 28399 * - `FunctionRegion.Any` 28400 * - `FunctionRegion.ApNortheast1` 28401 * - `FunctionRegion.ApNortheast2` 28402 * - `FunctionRegion.ApSouth1` 28403 * - `FunctionRegion.ApSoutheast1` 28404 * - `FunctionRegion.ApSoutheast2` 28405 * - `FunctionRegion.CaCentral1` 28406 * - `FunctionRegion.EuCentral1` 28407 * - `FunctionRegion.EuWest1` 28408 * - `FunctionRegion.EuWest2` 28409 * - `FunctionRegion.EuWest3` 28410 * - `FunctionRegion.SaEast1` 28411 * - `FunctionRegion.UsEast1` 28412 * - `FunctionRegion.UsWest1` 28413 * - `FunctionRegion.UsWest2` 28414 * 28415 * @example Invoking a Function in the UsEast1 region 28416 * ```js 28417 * import { createClient, FunctionRegion } from '@supabase/supabase-js' 28418 * 28419 * const { data, error } = await supabase.functions.invoke('hello', { 28420 * body: { foo: 'bar' }, 28421 * region: FunctionRegion.UsEast1 28422 * }) 28423 * ``` 28424 * 28425 * @exampleDescription Calling with GET HTTP verb 28426 * You can also set the HTTP verb to `GET` when calling your Edge Function. 28427 * 28428 * @example Calling with GET HTTP verb 28429 * ```js 28430 * const { data, error } = await supabase.functions.invoke('hello', { 28431 * headers: { 28432 * "my-custom-header": 'my-custom-header-value' 28433 * }, 28434 * method: 'GET' 28435 * }) 28436 * ``` 28437 * 28438 * @example Standalone client invoke 28439 * ```ts 28440 * const { data, error } = await functions.invoke('hello-world', { 28441 * body: { name: 'Ada' }, 28442 * }) 28443 * ``` 28444 */ 28445 invoke(e) { 28446 return hM(this, arguments, void 0, function* (t, i = {}) { 28447 var r; 28448 let s, a;
28449 try { 28450 const { headers: l, method: o, body: c, signal: u, timeout: h } = i; 28451 let d = {}, { region: f } = i; 28452 f || (f = this.region); 28453 const p = new URL(`${this.url}/${t}`); 28454 f && f !== "any" && (d["x-region"] = f, p.searchParams.set("forceFunctionRegion", f)); 28455 let v; 28456 c && (l && !Object.prototype.hasOwnProperty.call(l, "Content-Type") || !l) ? typeof Blob < "u" && c instanceof Blob || c instanceof ArrayBuffer ? (d["Content-Type"] = "application/octet-stream", v = c) : typeof c == "string" ? (d["Content-Type"] = "text/plain", v = c) : typeof FormData < "u" && c instanceof FormData ? v = c : (d["Content-Type"] = "application/json", v = JSON.stringify(c)) : c && typeof c != "string" && !(typeof Blob < "u" && c instanceof Blob) && !(c instanceof ArrayBuffer) && !(typeof FormData < "u" && c instanceof FormData) ? v = JSON.stringify(c) : v = c; 28457 let m = u; 28458 h && (a = new AbortController(), s = setTimeout(() => a.abort(), h), u ? (m = a.signal, u.addEventListener("abort", () => a.abort())) : m = a.signal); 28459 const g = yield this.fetch(p.toString(), { 28460 method: o || "POST", 28461 // headers priority is (high to low): 28462 // 1. invoke-level headers 28463 // 2. client-level headers 28464 // 3. default Content-Type header 28465 headers: Object.assign(Object.assign(Object.assign({}, d), this.headers), l), 28466 body: v, 28467 signal: m 28468 }).catch((R) => { 28469 throw new fM(R); 28470 }), _ = g.headers.get("x-relay-error"); 28471 if (_ && _ === "true") 28472 throw new Jd(g); 28473 if (!g.ok) 28474 throw new Zd(g); 28475 let x = ((r = g.headers.get("Content-Type")) !== null && r !== void 0 ? r : "text/plain").split(";")[0].trim(), E; 28476 return x === "application/json" ? E = yield g.json() : x === "application/octet-stream" || x === "application/pdf" ? E = yield g.blob() : x === "text/event-stream" ? E = g : x === "multipart/form-data" ? E = yield g.formData() : E = yield g.text(), { data: E, error: null, response: g }; 28477 } catch (l) { 28478 return { 28479 data: null, 28480 error: l, 28481 response: l instanceof Zd || l instanceof Jd ? l.context : void 0 28482 }; 28483 } finally { 28484 s && clearTimeout(s); 28485 } 28486 }); 28487 } 28488} 28489const ym = 3, Qd = (n) => Math.min(1e3 * 2 ** n, 3e4), mM = [520, 503], xm = [ 28490 "GET", 28491 "HEAD", 28492 "OPTIONS" 28493]; 28494var ef = class extends Error { 28495 /** 28496 * @example 28497 * ```ts 28498 * import PostgrestError from '@supabase/postgrest-js' 28499 * 28500 * throw new PostgrestError({ 28501 * message: 'Row level security prevented the request', 28502 * details: 'RLS denied the insert', 28503 * hint: 'Check your policies', 28504 * code: 'PGRST301', 28505 * }) 28506 * ``` 28507 */ 28508 constructor(n) { 28509 super(n.message), this.name = "PostgrestError", this.details = n.details, this.hint = n.hint, this.code = n.code; 28510 } 28511 toJSON() { 28512 return { 28513 name: this.name, 28514 message: this.message, 28515 details: this.details, 28516 hint: this.hint, 28517 code: this.code 28518 }; 28519 } 28520}; 28521function tf(n, e) { 28522 return new Promise((t) => { 28523 if (e?.aborted) { 28524 t(); 28525 return; 28526 } 28527 const i = setTimeout(() => { 28528 e?.removeEventListener("abort", r), t(); 28529 }, n); 28530 function r() { 28531 clearTimeout(i), t(); 28532 } 28533 e?.addEventListener("abort", r); 28534 }); 28535} 28536function gM(n, e, t, i) { 28537 return !(!i || t >= ym || !xm.includes(n) || !mM.includes(e)); 28538} 28539var vM = class { 28540 /** 28541 * Creates a builder configured for a specific PostgREST request. 28542 * 28543 * @example Using supabase-js (recommended) 28544 * ```ts 28545 * import { createClient } from '@supabase/supabase-js' 28546 * 28547 * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key') 28548 * const { data, error } = await supabase.from('users').select('*') 28549 * ``` 28550 * 28551 * @category Database 28552 * 28553 * @example Standalone import for bundle-sensitive environments 28554 * ```ts 28555 * import { PostgrestQueryBuilder } from '@supabase/postgrest-js' 28556 * 28557 * const builder = new PostgrestQueryBuilder( 28558 * new URL('https://xyzcompany.supabase.co/rest/v1/users'), 28559 * { headers: new Headers({ apikey: 'your-publishable-key' }) } 28560 * ) 28561 * ``` 28562 */ 28563 constructor(n) { 28564 var e, t, i, r, s; 28565 this.shouldThrowOnError = !1, this.retryEnabled = !0, this.method = n.method, this.url = n.url, this.headers = new Headers(n.headers), this.schema = n.schema, this.body = n.body, this.shouldThrowOnError = (e = n.shouldThrowOnError) !== null && e !== void 0 ? e : !1, this.signal = n.signal, this.isMaybeSingle = (t = n.isMaybeSingle) !== null && t !== void 0 ? t : !1, this.shouldStripNulls = (i = n.shouldStripNulls) !== null && i !== void 0 ? i : !1, this.urlLengthLimit = (r = n.urlLengthLimit) !== null && r !== void 0 ? r : 8e3, this.retryEnabled = (s = n.retry) !== null && s !== void 0 ? s : !0, n.fetch ? this.fetch = n.fetch : this.fetch = fetch; 28566 } 28567 /** 28568 * If there's an error with the query, throwOnError will reject the promise by 28569 * throwing the error instead of returning it as part of a successful response. 28570 * 28571 * {@link https://github.com/supabase/supabase-js/issues/92} 28572 * 28573 * @category Database 28574 * @subcategory Using modifiers 28575 */ 28576 throwOnError() { 28577 return this.shouldThrowOnError = !0, this; 28578 } 28579 /** 28580 * Strip null values from the response data. Properties with `null` values 28581 * will be omitted from the returned JSON objects. 28582 * 28583 * Requires PostgREST 11.2.0+. 28584 * 28585 * {@link https://docs.postgrest.org/en/stable/references/api/resource_representation.html#stripped-nulls} 28586 * 28587 * @category Database 28588 * @subcategory Using modifiers 28589 * 28590 * @example With `select()` 28591 * ```ts 28592 * const { data, error } = await supabase 28593 * .from('characters') 28594 * .select() 28595 * .stripNulls() 28596 * ``` 28597 * 28598 * @exampleSql With `select()` 28599 * ```sql 28600 * create table 28601 * characters (id int8 primary key, name text, bio text); 28602 * 28603 * insert into 28604 * characters (id, name, bio) 28605 * values 28606 * (1, 'Luke', null), 28607 * (2, 'Leia', 'Princess of Alderaan'); 28608 * ``` 28609 * 28610 * @exampleResponse With `select()` 28611 * ```json 28612 * { 28613 * "data": [ 28614 * { 28615 * "id": 1, 28616 * "name": "Luke" 28617 * }, 28618 * { 28619 * "id": 2, 28620 * "name": "Leia", 28621 * "bio": "Princess of Alderaan" 28622 * } 28623 * ], 28624 * "status": 200, 28625 * "statusText": "OK" 28626 * } 28627 * ``` 28628 */ 28629 stripNulls() { 28630 if (this.headers.get("Accept") === "text/csv") throw new Error("stripNulls() cannot be used with csv()"); 28631 return this.shouldStripNulls = !0, this; 28632 } 28633 /** 28634 * Set an HTTP header on this single PostgREST request, overriding any header 28635 * with the same name set on the client. 28636 * 28637 * This is an advanced escape hatch for one-off needs (passing a custom 28638 * `Authorization` for a single query, attaching a tracing header, etc.). 28639 * Most callers do not need it: configure client-wide headers via the 28640 * `headers` option when constructing the client, and authentication via 28641 * Supabase Auth. 28642 * 28643 * @param name - HTTP header name 28644 * @param value - HTTP header value 28645 * 28646 * @category Database 28647 * @subcategory Using modifiers 28648 */ 28649 setHeader(n, e) { 28650 return this.headers = new Headers(this.headers), this.headers.set(n, e), this; 28651 } 28652 /** 28653 * @category Database 28654 * @subcategory Using modifiers 28655 * 28656 * Configure retry behavior for this request. 28657 * 28658 * By default, retries are enabled for idempotent requests (GET, HEAD, OPTIONS) 28659 * that fail with network errors or specific HTTP status codes (503, 520). 28660 * Retries use exponential backoff (1s, 2s, 4s) with a maximum of 3 attempts. 28661 * 28662 * @param enabled - Whether to enable retries for this request 28663 * 28664 * @example 28665 * ```ts 28666 * // Disable retries for a specific query 28667 * const { data, error } = await supabase 28668 * .from('users') 28669 * .select() 28670 * .retry(false) 28671 * ``` 28672 */ 28673 retry(n) { 28674 return this.retryEnabled = n, this; 28675 } 28676 then(n, e) { 28677 var t = this; 28678 if (this.schema === void 0 || (["GET", "HEAD"].includes(this.method) ? this.headers.set("Accept-Profile", this.schema) : this.headers.set("Content-Profile", this.schema)), this.method !== "GET" && this.method !== "HEAD" && this.headers.set("Content-Type", "application/json"), this.shouldStripNulls) { 28679 const a = this.headers.get("Accept"); 28680 a === "application/vnd.pgrst.object+json" ? this.headers.set("Accept", "application/vnd.pgrst.object+json;nulls=stripped") : (!a || a === "application/json") && this.headers.set("Accept", "application/vnd.pgrst.array+json;nulls=stripped"); 28681 } 28682 const i = this.fetch; 28683 let s = (async () => { 28684 let a = 0; 28685 for (; ; ) { 28686 const c = {};
28687 t.headers.forEach((h, d) => { 28688 c[d] = h; 28689 }), a > 0 && (c["X-Retry-Count"] = String(a)); 28690 let u; 28691 try { 28692 u = await i(t.url.toString(), { 28693 method: t.method, 28694 headers: c, 28695 body: JSON.stringify(t.body, (h, d) => typeof d == "bigint" ? d.toString() : d), 28696 signal: t.signal 28697 }); 28698 } catch (h) { 28699 if (h?.name === "AbortError" || h?.code === "ABORT_ERR" || !xm.includes(t.method)) throw h; 28700 if (t.retryEnabled && a < ym) { 28701 const d = Qd(a); 28702 a++, await tf(d, t.signal); 28703 continue; 28704 } 28705 throw h; 28706 } 28707 if (gM(t.method, u.status, a, t.retryEnabled)) { 28708 var l, o; 28709 const h = (l = (o = u.headers) === null || o === void 0 ? void 0 : o.get("Retry-After")) !== null && l !== void 0 ? l : null, d = h !== null ? Math.max(0, parseInt(h, 10) || 0) * 1e3 : Qd(a); 28710 await u.text(), a++, await tf(d, t.signal); 28711 continue; 28712 } 28713 return await t.processResponse(u); 28714 } 28715 })(); 28716 return this.shouldThrowOnError || (s = s.catch((a) => { 28717 var l; 28718 let o = "", c = "", u = ""; 28719 const h = a?.cause; 28720 if (h) { 28721 var d, f, p, v; 28722 const _ = (d = h?.message) !== null && d !== void 0 ? d : "", x = (f = h?.code) !== null && f !== void 0 ? f : ""; 28723 o = `${(p = a?.name) !== null && p !== void 0 ? p : "FetchError"}: ${a?.message}`, o += ` 28724 28725Caused by: ${(v = h?.name) !== null && v !== void 0 ? v : "Error"}: ${_}`, x && (o += ` (${x})`), h?.stack && (o += ` 28726${h.stack}`); 28727 } else { 28728 var m; 28729 o = (m = a?.stack) !== null && m !== void 0 ? m : ""; 28730 } 28731 const g = this.url.toString().length; 28732 return a?.name === "AbortError" || a?.code === "ABORT_ERR" ? (u = "", c = "Request was aborted (timeout or manual cancellation)", g > this.urlLengthLimit && (c += `. Note: Your request URL is ${g} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)) : (h?.name === "HeadersOverflowError" || h?.code === "UND_ERR_HEADERS_OVERFLOW") && (u = "", c = "HTTP headers exceeded server limits (typically 16KB)", g > this.urlLengthLimit && (c += `. Your request URL is ${g} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)), { 28733 success: !1, 28734 error: { 28735 message: `${(l = a?.name) !== null && l !== void 0 ? l : "FetchError"}: ${a?.message}`, 28736 details: o, 28737 hint: c, 28738 code: u 28739 }, 28740 data: null, 28741 count: null, 28742 status: 0, 28743 statusText: "" 28744 }; 28745 })), s.then(n, e); 28746 } 28747 /** 28748 * Process a fetch response and return the standardized postgrest response. 28749 */ 28750 async processResponse(n) { 28751 var e = this; 28752 let t = null, i = null, r = null, s = n.status, a = n.statusText; 28753 if (n.ok) { 28754 var l, o; 28755 if (e.method !== "HEAD") { 28756 var c; 28757 const d = await n.text(); 28758 if (d !== "") if (e.headers.get("Accept") === "text/csv") i = d; 28759 else if (e.headers.get("Accept") && (!((c = e.headers.get("Accept")) === null || c === void 0) && c.includes("application/vnd.pgrst.plan+text"))) i = d; 28760 else try { 28761 i = JSON.parse(d); 28762 } catch { 28763 if (t = { message: d }, i = null, e.shouldThrowOnError) throw new ef({ 28764 message: d, 28765 details: "", 28766 hint: "", 28767 code: "" 28768 }); 28769 } 28770 } 28771 const u = (l = e.headers.get("Prefer")) === null || l === void 0 ? void 0 : l.match(/count=(exact|planned|estimated)/), h = (o = n.headers.get("content-range")) === null || o === void 0 ? void 0 : o.split("/"); 28772 u && h && h.length > 1 && (r = parseInt(h[1])), e.isMaybeSingle && Array.isArray(i) && (i.length > 1 ? (t = { 28773 code: "PGRST116", 28774 details: `Results contain ${i.length} rows, application/vnd.pgrst.object+json requires 1 row`, 28775 hint: null, 28776 message: "JSON object requested, multiple (or no) rows returned" 28777 }, i = null, r = null, s = 406, a = "Not Acceptable") : i.length === 1 ? i = i[0] : i = null); 28778 } else { 28779 const u = await n.text();
28780 try { 28781 t = JSON.parse(u), Array.isArray(t) && n.status === 404 && (i = [], t = null, s = 200, a = "OK"); 28782 } catch { 28783 n.status === 404 && u === "" ? (s = 204, a = "No Content") : t = { message: u }; 28784 } 28785 if (t && e.shouldThrowOnError) throw new ef(t); 28786 } 28787 return { 28788 success: t === null, 28789 error: t, 28790 data: i, 28791 count: r, 28792 status: s, 28793 statusText: a 28794 }; 28795 } 28796 /** 28797 * Override the type of the returned `data`. 28798 * 28799 * @typeParam NewResult - The new result type to override with 28800 * @deprecated Use overrideTypes<yourType, { merge: false }>() method at the end of your call chain instead 28801 * 28802 * @category Database 28803 * @subcategory Using modifiers 28804 */ 28805 returns() { 28806 return this; 28807 } 28808 /** 28809 * Override the type of the returned `data` field in the response. 28810 * 28811 * @typeParam NewResult - The new type to cast the response data to 28812 * @typeParam Options - Optional type configuration (defaults to { merge: true }) 28813 * @typeParam Options.merge - When true, merges the new type with existing return type. When false, replaces the existing types entirely (defaults to true) 28814 * @example 28815 * ```typescript 28816 * // Merge with existing types (default behavior) 28817 * const query = supabase 28818 * .from('users') 28819 * .select() 28820 * .overrideTypes<{ custom_field: string }>() 28821 * 28822 * // Replace existing types completely 28823 * const replaceQuery = supabase 28824 * .from('users') 28825 * .select() 28826 * .overrideTypes<{ id: number; name: string }, { merge: false }>() 28827 * ``` 28828 * @returns A PostgrestBuilder instance with the new type 28829 * 28830 * @category Database 28831 * @subcategory Using modifiers 28832 * 28833 * @example Complete Override type of successful response 28834 * ```ts 28835 * const { data } = await supabase 28836 * .from('countries') 28837 * .select() 28838 * .overrideTypes<Array<MyType>, { merge: false }>() 28839 * ``` 28840 * 28841 * @exampleResponse Complete Override type of successful response 28842 * ```ts 28843 * let x: typeof data // MyType[] 28844 * ``` 28845 * 28846 * @example Complete Override type of object response 28847 * ```ts 28848 * const { data } = await supabase 28849 * .from('countries') 28850 * .select() 28851 * .maybeSingle() 28852 * .overrideTypes<MyType, { merge: false }>() 28853 * ``` 28854 * 28855 * @exampleResponse Complete Override type of object response 28856 * ```ts 28857 * let x: typeof data // MyType | null 28858 * ``` 28859 * 28860 * @example Partial Override type of successful response 28861 * ```ts 28862 * const { data } = await supabase 28863 * .from('countries') 28864 * .select() 28865 * .overrideTypes<Array<{ status: "A" | "B" }>>() 28866 * ``` 28867 * 28868 * @exampleResponse Partial Override type of successful response 28869 * ```ts 28870 * let x: typeof data // Array<CountryRowProperties & { status: "A" | "B" }> 28871 * ``` 28872 * 28873 * @example Partial Override type of object response 28874 * ```ts 28875 * const { data } = await supabase 28876 * .from('countries') 28877 * .select() 28878 * .maybeSingle() 28879 * .overrideTypes<{ status: "A" | "B" }>() 28880 * ``` 28881 * 28882 * @exampleResponse Partial Override type of object response 28883 * ```ts 28884 * let x: typeof data // CountryRowProperties & { status: "A" | "B" } | null 28885 * ``` 28886 * 28887 * @example Merge vs replace existing types 28888 * ```typescript 28889 * // Merge with existing types (default behavior) 28890 * const query = supabase 28891 * .from('users') 28892 * .select() 28893 * .overrideTypes<{ custom_field: string }>() 28894 * 28895 * // Replace existing types completely 28896 * const replaceQuery = supabase 28897 * .from('users') 28898 * .select() 28899 * .overrideTypes<{ id: number; name: string }, { merge: false }>() 28900 * ``` 28901 */ 28902 overrideTypes() { 28903 return this; 28904 } 28905}, _M = class extends vM { 28906 throwOnError() { 28907 return super.throwOnError(); 28908 } 28909 /** 28910 * Perform a SELECT on the query result. 28911 * 28912 * By default, `.insert()`, `.update()`, `.upsert()`, and `.delete()` do not 28913 * return modified rows. By calling this method, modified rows are returned in 28914 * `data`. 28915 * 28916 * @param columns - The columns to retrieve, separated by commas 28917 * 28918 * @category Database 28919 * @subcategory Using modifiers 28920 * 28921 * @example With `upsert()` 28922 * ```ts 28923 * const { data, error } = await supabase 28924 * .from('characters')
28925 * .upsert({ id: 1, name: 'Han Solo' }) 28926 * .select() 28927 * ``` 28928 * 28929 * @exampleSql With `upsert()` 28930 * ```sql 28931 * create table 28932 * characters (id int8 primary key, name text); 28933 * 28934 * insert into 28935 * characters (id, name) 28936 * values 28937 * (1, 'Han'); 28938 * ``` 28939 * 28940 * @exampleResponse With `upsert()` 28941 * ```json 28942 * { 28943 * "data": [ 28944 * { 28945 * "id": 1, 28946 * "name": "Han Solo" 28947 * } 28948 * ], 28949 * "status": 201, 28950 * "statusText": "Created" 28951 * } 28952 * ``` 28953 */ 28954 select(n) { 28955 let e = !1; 28956 const t = (n ?? "*").split("").map((i) => /\s/.test(i) && !e ? "" : (i === '"' && (e = !e), i)).join(""); 28957 return this.url.searchParams.set("select", t), this.headers.append("Prefer", "return=representation"), this; 28958 } 28959 /** 28960 * Order the query result by `column`. 28961 * 28962 * You can call this method multiple times to order by multiple columns. 28963 * 28964 * You can order referenced tables, but it only affects the ordering of the 28965 * parent table if you use `!inner` in the query. 28966 * 28967 * @param column - The column to order by 28968 * @param options - Named parameters 28969 * @param options.ascending - If `true`, the result will be in ascending order 28970 * @param options.nullsFirst - If `true`, `null`s appear first. If `false`, 28971 * `null`s appear last. 28972 * @param options.referencedTable - Set this to order a referenced table by 28973 * its columns 28974 * @param options.foreignTable - Deprecated, use `options.referencedTable` 28975 * instead 28976 * 28977 * @category Database 28978 * @subcategory Using modifiers 28979 * 28980 * @example With `select()` 28981 * ```ts 28982 * const { data, error } = await supabase 28983 * .from('characters') 28984 * .select('id, name') 28985 * .order('id', { ascending: false }) 28986 * ``` 28987 * 28988 * @exampleSql With `select()` 28989 * ```sql 28990 * create table 28991 * characters (id int8 primary key, name text); 28992 * 28993 * insert into 28994 * characters (id, name) 28995 * values 28996 * (1, 'Luke'), 28997 * (2, 'Leia'), 28998 * (3, 'Han'); 28999 * ``` 29000 * 29001 * @exampleResponse With `select()` 29002 * ```json 29003 * { 29004 * "data": [ 29005 * { 29006 * "id": 3, 29007 * "name": "Han" 29008 * }, 29009 * { 29010 * "id": 2, 29011 * "name": "Leia" 29012 * }, 29013 * { 29014 * "id": 1, 29015 * "name": "Luke" 29016 * } 29017 * ], 29018 * "status": 200, 29019 * "statusText": "OK" 29020 * } 29021 * ``` 29022 * 29023 * @exampleDescription On a referenced table 29024 * Ordering with `referencedTable` doesn't affect the ordering of the 29025 * parent table. 29026 * 29027 * @example On a referenced table 29028 * ```ts 29029 * const { data, error } = await supabase 29030 * .from('orchestral_sections') 29031 * .select(` 29032 * name, 29033 * instruments ( 29034 * name 29035 * ) 29036 * `) 29037 * .order('name', { referencedTable: 'instruments', ascending: false }) 29038 * 29039 * ``` 29040 * 29041 * @exampleSql On a referenced table 29042 * ```sql 29043 * create table 29044 * orchestral_sections (id int8 primary key, name text); 29045 * create table 29046 * instruments ( 29047 * id int8 primary key, 29048 * section_id int8 not null references orchestral_sections, 29049 * name text 29050 * ); 29051 * 29052 * insert into 29053 * orchestral_sections (id, name) 29054 * values 29055 * (1, 'strings'), 29056 * (2, 'woodwinds'); 29057 * insert into 29058 * instruments (id, section_id, name) 29059 * values 29060 * (1, 1, 'harp'),
29061 * (2, 1, 'violin'); 29062 * ``` 29063 * 29064 * @exampleResponse On a referenced table 29065 * ```json 29066 * { 29067 * "data": [ 29068 * { 29069 * "name": "strings", 29070 * "instruments": [ 29071 * { 29072 * "name": "violin" 29073 * }, 29074 * { 29075 * "name": "harp" 29076 * } 29077 * ] 29078 * }, 29079 * { 29080 * "name": "woodwinds", 29081 * "instruments": [] 29082 * } 29083 * ], 29084 * "status": 200, 29085 * "statusText": "OK" 29086 * } 29087 * ``` 29088 * 29089 * @exampleDescription Order parent table by a referenced table 29090 * Ordering with `referenced_table(col)` affects the ordering of the 29091 * parent table. 29092 * 29093 * @example Order parent table by a referenced table 29094 * ```ts 29095 * const { data, error } = await supabase 29096 * .from('instruments') 29097 * .select(` 29098 * name, 29099 * section:orchestral_sections ( 29100 * name 29101 * ) 29102 * `) 29103 * .order('section(name)', { ascending: true }) 29104 * 29105 * ``` 29106 * 29107 * @exampleSql Order parent table by a referenced table 29108 * ```sql 29109 * create table 29110 * orchestral_sections (id int8 primary key, name text); 29111 * create table 29112 * instruments ( 29113 * id int8 primary key, 29114 * section_id int8 not null references orchestral_sections, 29115 * name text 29116 * ); 29117 * 29118 * insert into 29119 * orchestral_sections (id, name) 29120 * values 29121 * (1, 'strings'), 29122 * (2, 'woodwinds'); 29123 * insert into 29124 * instruments (id, section_id, name) 29125 * values 29126 * (1, 2, 'flute'), 29127 * (2, 1, 'violin'); 29128 * ``` 29129 * 29130 * @exampleResponse Order parent table by a referenced table 29131 * ```json 29132 * { 29133 * "data": [ 29134 * { 29135 * "name": "violin", 29136 * "orchestral_sections": {"name": "strings"} 29137 * }, 29138 * { 29139 * "name": "flute", 29140 * "orchestral_sections": {"name": "woodwinds"} 29141 * } 29142 * ], 29143 * "status": 200, 29144 * "statusText": "OK" 29145 * } 29146 * ``` 29147 */ 29148 order(n, { ascending: e = !0, nullsFirst: t, foreignTable: i, referencedTable: r = i } = {}) { 29149 const s = r ? `${r}.order` : "order", a = this.url.searchParams.get(s); 29150 return this.url.searchParams.set(s, `${a ? `${a},` : ""}${n}.${e ? "asc" : "desc"}${t === void 0 ? "" : t ? ".nullsfirst" : ".nullslast"}`), this; 29151 } 29152 /** 29153 * Limit the query result by `rows`. 29154 * 29155 * @param rows - The maximum number of rows to return 29156 * @param options - Named parameters 29157 * @param options.referencedTable - Set this to limit rows of referenced 29158 * tables instead of the parent table 29159 * @param options.foreignTable - Deprecated, use `options.referencedTable` 29160 * instead 29161 * 29162 * @category Database 29163 * @subcategory Using modifiers 29164 * 29165 * @example With `select()` 29166 * ```ts 29167 * const { data, error } = await supabase 29168 * .from('characters') 29169 * .select('name') 29170 * .limit(1) 29171 * ``` 29172 * 29173 * @exampleSql With `select()` 29174 * ```sql 29175 * create table 29176 * characters (id int8 primary key, name text); 29177 * 29178 * insert into 29179 * characters (id, name) 29180 * values 29181 * (1, 'Luke'), 29182 * (2, 'Leia'), 29183 * (3, 'Han'); 29184 * ``` 29185 * 29186 * @exampleResponse With `select()` 29187 * ```json 29188 * { 29189 * "data": [ 29190 * { 29191 * "name": "Luke" 29192 * } 29193 * ], 29194 * "status": 200, 29195 * "statusText": "OK" 29196 * } 29197 * ``` 29198 * 29199 * @example On a referenced table 29200 * ```ts 29201 * const { data, error } = await supabase 29202 * .from('orchestral_sections') 29203 * .select(` 29204 * name, 29205 * instruments ( 29206 * name 29207 * ) 29208 * `) 29209 * .limit(1, { referencedTable: 'instruments' }) 29210 * ``` 29211 * 29212 * @exampleSql On a referenced table 29213 * ```sql 29214 * create table 29215 * orchestral_sections (id int8 primary key, name text); 29216 * create table 29217 * instruments ( 29218 * id int8 primary key, 29219 * section_id int8 not null references orchestral_sections, 29220 * name text 29221 * ); 29222 * 29223 * insert into 29224 * orchestral_sections (id, name) 29225 * values 29226 * (1, 'strings'); 29227 * insert into 29228 * instruments (id, section_id, name) 29229 * values 29230 * (1, 1, 'harp'),
29231 * (2, 1, 'violin'); 29232 * ``` 29233 * 29234 * @exampleResponse On a referenced table 29235 * ```json 29236 * { 29237 * "data": [ 29238 * { 29239 * "name": "strings", 29240 * "instruments": [ 29241 * { 29242 * "name": "violin" 29243 * } 29244 * ] 29245 * } 29246 * ], 29247 * "status": 200, 29248 * "statusText": "OK" 29249 * } 29250 * ``` 29251 */ 29252 limit(n, { foreignTable: e, referencedTable: t = e } = {}) { 29253 const i = typeof t > "u" ? "limit" : `${t}.limit`; 29254 return this.url.searchParams.set(i, `${n}`), this; 29255 } 29256 /** 29257 * Limit the query result by starting at an offset `from` and ending at the offset `to`. 29258 * Only records within this range are returned. 29259 * This respects the query order and if there is no order clause the range could behave unexpectedly. 29260 * The `from` and `to` values are 0-based and inclusive: `range(1, 3)` will include the second, third 29261 * and fourth rows of the query. 29262 * 29263 * @param from - The starting index from which to limit the result 29264 * @param to - The last index to which to limit the result 29265 * @param options - Named parameters 29266 * @param options.referencedTable - Set this to limit rows of referenced 29267 * tables instead of the parent table 29268 * @param options.foreignTable - Deprecated, use `options.referencedTable` 29269 * instead 29270 * 29271 * @category Database 29272 * @subcategory Using modifiers 29273 * 29274 * @example With `select()` 29275 * ```ts 29276 * const { data, error } = await supabase 29277 * .from('characters') 29278 * .select('name') 29279 * .range(0, 1) 29280 * ``` 29281 * 29282 * @exampleSql With `select()` 29283 * ```sql 29284 * create table 29285 * characters (id int8 primary key, name text); 29286 * 29287 * insert into 29288 * characters (id, name) 29289 * values 29290 * (1, 'Luke'), 29291 * (2, 'Leia'), 29292 * (3, 'Han'); 29293 * ``` 29294 * 29295 * @exampleResponse With `select()` 29296 * ```json 29297 * { 29298 * "data": [ 29299 * { 29300 * "name": "Luke" 29301 * }, 29302 * { 29303 * "name": "Leia" 29304 * } 29305 * ], 29306 * "status": 200, 29307 * "statusText": "OK" 29308 * } 29309 * ``` 29310 */ 29311 range(n, e, { foreignTable: t, referencedTable: i = t } = {}) { 29312 const r = typeof i > "u" ? "offset" : `${i}.offset`, s = typeof i > "u" ? "limit" : `${i}.limit`; 29313 return this.url.searchParams.set(r, `${n}`), this.url.searchParams.set(s, `${e - n + 1}`), this; 29314 } 29315 /** 29316 * Set the AbortSignal for the fetch request. 29317 * 29318 * @param signal - The AbortSignal to use for the fetch request 29319 * 29320 * @category Database 29321 * @subcategory Using modifiers 29322 * 29323 * @remarks 29324 * You can use this to set a timeout for the request. 29325 * 29326 * @exampleDescription Aborting requests in-flight 29327 * You can use an [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController) to abort requests. 29328 * Note that `status` and `statusText` don't mean anything for aborted requests as the request wasn't fulfilled. 29329 * 29330 * @example Aborting requests in-flight 29331 * ```ts 29332 * const ac = new AbortController() 29333 * 29334 * const { data, error } = await supabase 29335 * .from('very_big_table') 29336 * .select() 29337 * .abortSignal(ac.signal) 29338 * 29339 * // Abort the request after 100 ms 29340 * setTimeout(() => ac.abort(), 100) 29341 * ``` 29342 * 29343 * @exampleResponse Aborting requests in-flight 29344 * ```json 29345 * { 29346 * "error": { 29347 * "message": "AbortError: The user aborted a request.", 29348 * "details": "", 29349 * "hint": "The request was aborted locally via the provided AbortSignal.", 29350 * "code": "" 29351 * }, 29352 * "status": 0, 29353 * "statusText": "" 29354 * } 29355 * 29356 * ``` 29357 * 29358 * @example Set a timeout 29359 * ```ts 29360 * const { data, error } = await supabase 29361 * .from('very_big_table') 29362 * .select() 29363 * .abortSignal(AbortSignal.timeout(1000 /* ms *\/)) 29364 * ``` 29365 * 29366 * @exampleResponse Set a timeout 29367 * ```json 29368 * { 29369 * "error": { 29370 * "message": "FetchError: The user aborted a request.", 29371 * "details": "", 29372 * "hint": "", 29373 * "code": "" 29374 * }, 29375 * "status": 400, 29376 * "statusText": "Bad Request" 29377 * } 29378 * 29379 * ``` 29380 */ 29381 abortSignal(n) { 29382 return this.signal = n, this; 29383 } 29384 /** 29385 * Return `data` as a single object instead of an array of objects. 29386 * 29387 * Query result must be one row (e.g. using `.limit(1)`), otherwise this 29388 * returns an error. 29389 * 29390 * @category Database 29391 * @subcategory Using modifiers 29392 * 29393 * @example With `select()` 29394 * ```ts 29395 * const { data, error } = await supabase 29396 * .from('characters') 29397 * .select('name') 29398 * .limit(1) 29399 * .single() 29400 * ``` 29401 * 29402 * @exampleSql With `select()` 29403 * ```sql 29404 * create table 29405 * characters (id int8 primary key, name text); 29406 * 29407 * insert into 29408 * characters (id, name) 29409 * values 29410 * (1, 'Luke'), 29411 * (2, 'Leia'), 29412 * (3, 'Han'); 29413 * ``` 29414 * 29415 * @exampleResponse With `select()` 29416 * ```json 29417 * { 29418 * "data": { 29419 * "name": "Luke" 29420 * }, 29421 * "status": 200, 29422 * "statusText": "OK" 29423 * } 29424 * ``` 29425 */ 29426 single() { 29427 return this.headers.set("Accept", "application/vnd.pgrst.object+json"), this; 29428 } 29429 /** 29430 * Return `data` as a single object instead of an array of objects. 29431 * 29432 * Query result must be zero or one row (e.g. using `.limit(1)`), otherwise 29433 * this returns an error. 29434 * 29435 * @category Database 29436 * @subcategory Using modifiers 29437 * 29438 * @example With `select()` 29439 * ```ts 29440 * const { data, error } = await supabase 29441 * .from('characters') 29442 * .select() 29443 * .eq('name', 'Katniss') 29444 * .maybeSingle() 29445 * ``` 29446 * 29447 * @exampleSql With `select()` 29448 * ```sql 29449 * create table 29450 * characters (id int8 primary key, name text); 29451 * 29452 * insert into 29453 * characters (id, name) 29454 * values 29455 * (1, 'Luke'), 29456 * (2, 'Leia'), 29457 * (3, 'Han'); 29458 * ``` 29459 * 29460 * @exampleResponse With `select()` 29461 * ```json 29462 * { 29463 * "status": 200, 29464 * "statusText": "OK" 29465 * } 29466 * ``` 29467 */ 29468 maybeSingle() { 29469 return this.isMaybeSingle = !0, this; 29470 } 29471 /** 29472 * Return `data` as a string in CSV format. 29473 * 29474 * @category Database 29475 * @subcategory Using modifiers 29476 * 29477 * @exampleDescription Return data as CSV 29478 * By default, the data is returned in JSON format, but can also be returned as Comma Separated Values. 29479 * 29480 * @example Return data as CSV 29481 * ```ts 29482 * const { data, error } = await supabase 29483 * .from('characters') 29484 * .select() 29485 * .csv() 29486 * ``` 29487 * 29488 * @exampleSql Return data as CSV 29489 * ```sql 29490 * create table 29491 * characters (id int8 primary key, name text); 29492 * 29493 * insert into 29494 * characters (id, name) 29495 * values 29496 * (1, 'Luke'), 29497 * (2, 'Leia'), 29498 * (3, 'Han'); 29499 * ``` 29500 * 29501 * @exampleResponse Return data as CSV 29502 * ```json 29503 * { 29504 * "data": "id,name\n1,Luke\n2,Leia\n3,Han", 29505 * "status": 200, 29506 * "statusText": "OK" 29507 * } 29508 * ``` 29509 */ 29510 csv() { 29511 return this.headers.set("Accept", "text/csv"), this; 29512 } 29513 /** 29514 * Return `data` as an object in [GeoJSON](https://geojson.org) format. 29515 * 29516 * @category Database 29517 * @subcategory Using modifiers 29518 */ 29519 geojson() { 29520 return this.headers.set("Accept", "application/geo+json"), this; 29521 } 29522 /** 29523 * Return `data` as the EXPLAIN plan for the query. 29524 * 29525 * You need to enable the 29526 * [db_plan_enabled](https://supabase.com/docs/guides/database/debugging-performance#enabling-explain) 29527 * setting before using this method. 29528 *
29529 * @param options - Named parameters 29530 * 29531 * @param options.analyze - If `true`, the query will be executed and the 29532 * actual run time will be returned 29533 * 29534 * @param options.verbose - If `true`, the query identifier will be returned 29535 * and `data` will include the output columns of the query 29536 * 29537 * @param options.settings - If `true`, include information on configuration 29538 * parameters that affect query planning 29539 * 29540 * @param options.buffers - If `true`, include information on buffer usage 29541 * 29542 * @param options.wal - If `true`, include information on WAL record generation 29543 * 29544 * @param options.format - The format of the output, can be `"text"` (default) 29545 * or `"json"` 29546 * 29547 * @category Database 29548 * @subcategory Using modifiers 29549 * 29550 * @exampleDescription Get the execution plan 29551 * By default, the data is returned in TEXT format, but can also be returned as JSON by using the `format` parameter. 29552 * 29553 * @example Get the execution plan 29554 * ```ts 29555 * const { data, error } = await supabase 29556 * .from('characters') 29557 * .select() 29558 * .explain() 29559 * ``` 29560 * 29561 * @exampleSql Get the execution plan 29562 * ```sql 29563 * create table 29564 * characters (id int8 primary key, name text); 29565 * 29566 * insert into 29567 * characters (id, name) 29568 * values 29569 * (1, 'Luke'), 29570 * (2, 'Leia'), 29571 * (3, 'Han'); 29572 * ``` 29573 * 29574 * @exampleResponse Get the execution plan 29575 * ```js 29576 * Aggregate (cost=33.34..33.36 rows=1 width=112) 29577 * -> Limit (cost=0.00..18.33 rows=1000 width=40) 29578 * -> Seq Scan on characters (cost=0.00..22.00 rows=1200 width=40) 29579 * ``` 29580 * 29581 * @exampleDescription Get the execution plan with analyze and verbose 29582 * By default, the data is returned in TEXT format, but can also be returned as JSON by using the `format` parameter. 29583 * 29584 * @example Get the execution plan with analyze and verbose 29585 * ```ts 29586 * const { data, error } = await supabase 29587 * .from('characters') 29588 * .select() 29589 * .explain({analyze:true,verbose:true}) 29590 * ``` 29591 * 29592 * @exampleSql Get the execution plan with analyze and verbose 29593 * ```sql 29594 * create table 29595 * characters (id int8 primary key, name text); 29596 * 29597 * insert into 29598 * characters (id, name) 29599 * values 29600 * (1, 'Luke'), 29601 * (2, 'Leia'), 29602 * (3, 'Han'); 29603 * ``` 29604 * 29605 * @exampleResponse Get the execution plan with analyze and verbose 29606 * ```js 29607 * Aggregate (cost=33.34..33.36 rows=1 width=112) (actual time=0.041..0.041 rows=1 loops=1) 29608 * Output: NULL::bigint, count(ROW(characters.id, characters.name)), COALESCE(json_agg(ROW(characters.id, characters.name)), '[]'::json), NULLIF(current_setting('response.headers'::text, true), ''::text), NULLIF(current_setting('response.status'::text, true), ''::text) 29609 * -> Limit (cost=0.00..18.33 rows=1000 width=40) (actual time=0.005..0.006 rows=3 loops=1) 29610 * Output: characters.id, characters.name 29611 * -> Seq Scan on public.characters (cost=0.00..22.00 rows=1200 width=40) (actual time=0.004..0.005 rows=3 loops=1) 29612 * Output: characters.id, characters.name 29613 * Query Identifier: -4730654291623321173 29614 * Planning Time: 0.407 ms 29615 * Execution Time: 0.119 ms 29616 * ``` 29617 */ 29618 explain({ analyze: n = !1, verbose: e = !1, settings: t = !1, buffers: i = !1, wal: r = !1, format: s = "text" } = {}) { 29619 var a; 29620 const l = [ 29621 n ? "analyze" : null, 29622 e ? "verbose" : null, 29623 t ? "settings" : null, 29624 i ? "buffers" : null, 29625 r ? "wal" : null 29626 ].filter(Boolean).join("|"), o = (a = this.headers.get("Accept")) !== null && a !== void 0 ? a : "application/json"; 29627 return this.headers.set("Accept", `application/vnd.pgrst.plan+${s}; for="${o}"; options=${l};
29627`), s === "json" ? this : this; 29628 } 29629 /** 29630 * Dry-run this request: execute the query but discard the changes. 29631 * 29632 * Server-side, PostgREST runs the query inside a transaction and rolls it back 29633 * instead of committing. The response still contains the data that *would* have 29634 * been returned â `RETURNING` clauses execute and RLS, triggers, and constraints 29635 * are all evaluated â but no row is actually inserted, updated, or deleted. 29636 * 29637 * This affects only the single request it is chained to. The JS caller has no 29638 * handle on the transaction: supabase-js does not group multiple queries into 29639 * one transaction. For multi-statement transactional logic, use a database 29640 * function (`supabase.rpc(...)`). 29641 * 29642 * Sets the `Prefer: tx=rollback` header. See PostgREST's docs on transaction 29643 * preferences for the underlying mechanism. 29644 * 29645 * @category Database 29646 * @subcategory Using modifiers 29647 * 29648 * @example Validate an insert without persisting 29649 * ```ts 29650 * const { data, error } = await supabase 29651 * .from('countries') 29652 * .insert({ name: 'France' }) 29653 * .select() 29654 * .rollback() 29655 * // `data` shows what would have been inserted; nothing is saved. 29656 * ``` 29657 */ 29658 rollback() { 29659 return this.headers.append("Prefer", "tx=rollback"), this; 29660 } 29661 /** 29662 * Override the type of the returned `data`. 29663 * 29664 * @typeParam NewResult - The new result type to override with 29665 * @deprecated Use overrideTypes<yourType, { merge: false }>() method at the end of your call chain instead 29666 * 29667 * @category Database 29668 * @subcategory Using modifiers 29669 * 29670 * @remarks 29671 * - Deprecated: use overrideTypes method instead 29672 * 29673 * @example Override type of successful response 29674 * ```ts 29675 * const { data } = await supabase 29676 * .from('countries') 29677 * .select() 29678 * .returns<Array<MyType>>() 29679 * ``` 29680 * 29681 * @exampleResponse Override type of successful response 29682 * ```js 29683 * let x: typeof data // MyType[] 29684 * ``` 29685 * 29686 * @example Override type of object response 29687 * ```ts 29688 * const { data } = await supabase 29689 * .from('countries') 29690 * .select() 29691 * .maybeSingle() 29692 * .returns<MyType>() 29693 * ``` 29694 * 29695 * @exampleResponse Override type of object response 29696 * ```js 29697 * let x: typeof data // MyType | null 29698 * ``` 29699 */ 29700 returns() { 29701 return this; 29702 } 29703 /** 29704 * Set the maximum number of rows that can be affected by the query. 29705 * Only available in PostgREST v13+ and only works with PATCH and DELETE methods. 29706 * 29707 * @param rows - The maximum number of rows that can be affected 29708 * 29709 * @category Database 29710 * @subcategory Using modifiers 29711 */ 29712 maxAffected(n) { 29713 return this.headers.append("Prefer", "handling=strict"), this.headers.append("Prefer", `max-affected=${n}`), this; 29714 } 29715}; 29716const nf = /* @__PURE__ */ new RegExp("[,()]"); 29717var rs = class extends _M { 29718 throwOnError() { 29719 return super.throwOnError(); 29720 } 29721 /** 29722 * Match only rows where `column` is equal to `value`. 29723 * 29724 * To check if the value of `column` is NULL, you should use `.is()` instead. 29725 * 29726 * @param column - The column to filter on 29727 * @param value - The value to filter with 29728 * 29729 * @category Database 29730 * @subcategory Using filters 29731 * 29732 * @example With `select()` 29733 * ```ts 29734 * const { data, error } = await supabase 29735 * .from('characters') 29736 * .select() 29737 * .eq('name', 'Leia') 29738 * ``` 29739 * 29740 * @exampleSql With `select()` 29741 * ```sql 29742 * create table 29743 * characters (id int8 primary key, name text); 29744 * 29745 * insert into 29746 * characters (id, name) 29747 * values 29748 * (1, 'Luke'), 29749 * (2, 'Leia'), 29750 * (3, 'Han'); 29751 * ``` 29752 * 29753 * @exampleResponse With `select()` 29754 * ```json 29755 * { 29756 * "data": [ 29757 * { 29758 * "id": 2, 29759 * "name": "Leia" 29760 * } 29761 * ], 29762 * "status": 200, 29763 * "statusText": "OK" 29764 * } 29765 * ``` 29766 */ 29767 eq(n, e) { 29768 return this.url.searchParams.append(n, `eq.${e}`), this; 29769 } 29770 /** 29771 * Match only rows where `column` is not equal to `value`. 29772 * 29773 * This filter does not include rows where `column` is `NULL`. To match null 29774 * values, use `.is(column, null)` instead. 29775 * 29776 * @param column - The column to filter on 29777 * @param value - The value to filter with 29778 * 29779 * @category Database 29780 * @subcategory Using filters 29781 * 29782 * @example With `select()` 29783 * ```ts 29784 * const { data, error } = await supabase 29785 * .from('characters') 29786 * .select() 29787 * .neq('name', 'Leia') 29788 * ``` 29789 * 29790 * @exampleSql With `select()` 29791 * ```sql 29792 * create table 29793 * characters (id int8 primary key, name text); 29794 * 29795 * insert into 29796 * characters (id, name) 29797 * values 29798 * (1, 'Luke'), 29799 * (2, 'Leia'), 29800 * (3, 'Han'); 29801 * ``` 29802 * 29803 * @exampleResponse With `select()` 29804 * ```json 29805 * { 29806 * "data": [ 29807 * { 29808 * "id": 1, 29809 * "name": "Luke" 29810 * }, 29811 * { 29812 * "id": 3, 29813 * "name": "Han" 29814 * } 29815 * ], 29816 * "status": 200, 29817 * "statusText": "OK" 29818 * } 29819 * ``` 29820 */ 29821 neq(n, e) { 29822 return this.url.searchParams.append(n, `neq.${e}`), this; 29823 } 29824 /** 29825 * Match only rows where `column` is greater than `value`. 29826 * 29827 * @param column - The column to filter on 29828 * @param value - The value to filter with 29829 * 29830 * @category Database 29831 * @subcategory Using filters 29832 * 29833 * @exampleDescription With `select()` 29834 * When using [reserved words](https://www.postgresql.org/docs/current/sql-keywords-appendix.html) for column names you need 29835 * to add double quotes e.g. `.gt('"order"', 2)` 29836 * 29837 * @example With `select()` 29838 * ```ts 29839 * const { data, error } = await supabase 29840 * .from('characters') 29841 * .select() 29842 * .gt('id', 2) 29843 * ``` 29844 * 29845 * @exampleSql With `select()` 29846 * ```sql 29847 * create table 29848 * characters (id int8 primary key, name text); 29849 * 29850 * insert into 29851 * characters (id, name) 29852 * values 29853 * (1, 'Luke'), 29854 * (2, 'Leia'), 29855 * (3, 'Han'); 29856 * ``` 29857 * 29858 * @exampleResponse With `select()` 29859 * ```json 29860 * { 29861 * "data": [ 29862 * { 29863 * "id": 3, 29864 * "name": "Han" 29865 * } 29866 * ], 29867 * "status": 200, 29868 * "statusText": "OK" 29869 * } 29870 * ``` 29871 */ 29872 gt(n, e) { 29873 return this.url.searchParams.append(n, `gt.${e}`), this; 29874 } 29875 /** 29876 * Match only rows where `column` is greater than or equal to `value`. 29877 * 29878 * @param column - The column to filter on 29879 * @param value - The value to filter with 29880 * 29881 * @category Database 29882 * @subcategory Using filters 29883 * 29884 * @example With `select()` 29885 * ```ts 29886 * const { data, error } = await supabase 29887 * .from('characters') 29888 * .select() 29889 * .gte('id', 2) 29890 * ``` 29891 * 29892 * @exampleSql With `select()` 29893 * ```sql 29894 * create table 29895 * characters (id int8 primary key, name text); 29896 * 29897 * insert into 29898 * characters (id, name) 29899 * values 29900 * (1, 'Luke'), 29901 * (2, 'Leia'), 29902 * (3, 'Han'); 29903 * ``` 29904 * 29905 * @exampleResponse With `select()` 29906 * ```json 29907 * { 29908 * "data": [ 29909 * { 29910 * "id": 2, 29911 * "name": "Leia" 29912 * }, 29913 * { 29914 * "id": 3, 29915 * "name": "Han" 29916 * } 29917 * ], 29918 * "status": 200, 29919 * "statusText": "OK" 29920 * } 29921 * ``` 29922 */ 29923 gte(n, e) { 29924 return this.url.searchParams.append(n, `gte.${e}`), this; 29925 } 29926 /** 29927 * Match only rows where `column` is less than `value`. 29928 * 29929 * @param column - The column to filter on 29930 * @param value - The value to filter with 29931 * 29932 * @category Database 29933 * @subcategory Using filters 29934 * 29935 * @example With `select()` 29936 * ```ts 29937 * const { data, error } = await supabase 29938 * .from('characters') 29939 * .select() 29940 * .lt('id', 2) 29941 * ``` 29942 * 29943 * @exampleSql With `select()` 29944 * ```sql 29945 * create table 29946 * characters (id int8 primary key, name text); 29947 * 29948 * insert into 29949 * characters (id, name) 29950 * values 29951 * (1, 'Luke'), 29952 * (2, 'Leia'), 29953 * (3, 'Han'); 29954 * ``` 29955 * 29956 * @exampleResponse With `select()` 29957 * ```json 29958 * { 29959 * "data": [ 29960 * { 29961 * "id": 1, 29962 * "name": "Luke" 29963 * } 29964 * ], 29965 * "status": 200, 29966 * "statusText": "OK" 29967 * } 29968 * ``` 29969 */ 29970 lt(n, e) { 29971 return this.url.searchParams.append(n, `lt.${e}`), this; 29972 } 29973 /** 29974 * Match only rows where `column` is less than or equal to `value`. 29975 * 29976 * @param column - The column to filter on 29977 * @param value - The value to filter with 29978 * 29979 * @category Database 29980 * @subcategory Using filters 29981 * 29982 * @example With `select()` 29983 * ```ts 29984 * const { data, error } = await supabase 29985 * .from('characters') 29986 * .select() 29987 * .lte('id', 2) 29988 * ``` 29989 * 29990 * @exampleSql With `select()` 29991 * ```sql 29992 * create table 29993 * characters (id int8 primary key, name text); 29994 * 29995 * insert into 29996 * characters (id, name) 29997 * values 29998 * (1, 'Luke'), 29999 * (2, 'Leia'), 30000 * (3, 'Han'); 30001 * ``` 30002 * 30003 * @exampleResponse With `select()` 30004 * ```json 30005 * { 30006 * "data": [ 30007 * { 30008 * "id": 1, 30009 * "name": "Luke" 30010 * }, 30011 * { 30012 * "id": 2, 30013 * "name": "Leia" 30014 * } 30015 * ], 30016 * "status": 200, 30017 * "statusText": "OK" 30018 * } 30019 * ``` 30020 */ 30021 lte(n, e) { 30022 return this.url.searchParams.append(n, `lte.${e}`), this; 30023 } 30024 /** 30025 * Match only rows where `column` matches `pattern` case-sensitively. 30026 * 30027 * @param column - The column to filter on 30028 * @param pattern - The pattern to match with 30029 * 30030 * @category Database 30031 * @subcategory Using filters 30032 * 30033 * @example With `select()` 30034 * ```ts 30035 * const { data, error } = await supabase 30036 * .from('characters') 30037 * .select() 30038 * .like('name', '%Lu%') 30039 * ``` 30040 * 30041 * @exampleSql With `select()` 30042 * ```sql 30043 * create table 30044 * characters (id int8 primary key, name text); 30045 * 30046 * insert into 30047 * characters (id, name) 30048 * values 30049 * (1, 'Luke'), 30050 * (2, 'Leia'), 30051 * (3, 'Han'); 30052 * ``` 30053 * 30054 * @exampleResponse With `select()` 30055 * ```json 30056 * { 30057 * "data": [ 30058 * { 30059 * "id": 1, 30060 * "name": "Luke" 30061 * } 30062 * ], 30063 * "status": 200, 30064 * "statusText": "OK" 30065 * } 30066 * ``` 30067 */ 30068 like(n, e) { 30069 return this.url.searchParams.append(n, `like.${e}`), this; 30070 } 30071 /** 30072 * Match only rows where `column` matches all of `patterns` case-sensitively. 30073 * 30074 * @param column - The column to filter on 30075 * @param patterns - The patterns to match with 30076 * 30077 * @category Database 30078 * @subcategory Using filters 30079 */ 30080 likeAllOf(n, e) { 30081 return this.url.searchParams.append(n, `like(all).{${e.join(",")}}`), this; 30082 } 30083 /** 30084 * Match only rows where `column` matches any of `patterns` case-sensitively. 30085 * 30086 * @param column - The column to filter on 30087 * @param patterns - The patterns to match with 30088 * 30089 * @category Database 30090 * @subcategory Using filters 30091 */ 30092 likeAnyOf(n, e) { 30093 return this.url.searchParams.append(n, `like(any).{${e.join(",")}}`), this; 30094 } 30095 /** 30096 * Match only rows where `column` matches `pattern` case-insensitively. 30097 * 30098 * @param column - The column to filter on 30099 * @param pattern - The pattern to match with 30100 * 30101 * @category Database 30102 * @subcategory Using filters 30103 * 30104 * @example With `select()` 30105 * ```ts 30106 * const { data, error } = await supabase 30107 * .from('characters') 30108 * .select() 30109 * .ilike('name', '%lu%') 30110 * ``` 30111 * 30112 * @exampleSql With `select()` 30113 * ```sql 30114 * create table 30115 * characters (id int8 primary key, name text); 30116 * 30117 * insert into 30118 * characters (id, name) 30119 * values 30120 * (1, 'Luke'), 30121 * (2, 'Leia'), 30122 * (3, 'Han'); 30123 * ``` 30124 * 30125 * @exampleResponse With `select()` 30126 * ```json 30127 * { 30128 * "data": [ 30129 * { 30130 * "id": 1, 30131 * "name": "Luke" 30132 * } 30133 * ], 30134 * "status": 200, 30135 * "statusText": "OK" 30136 * } 30137 * ``` 30138 */ 30139 ilike(n, e) { 30140 return this.url.searchParams.append(n, `ilike.${e}`), this; 30141 } 30142 /** 30143 * Match only rows where `column` matches all of `patterns` case-insensitively. 30144 * 30145 * @param column - The column to filter on 30146 * @param patterns - The patterns to match with 30147 * 30148 * @category Database 30149 * @subcategory Using filters 30150 */ 30151 ilikeAllOf(n, e) { 30152 return this.url.searchParams.append(n, `ilike(all).{${e.join(",")}}`), this; 30153 } 30154 /** 30155 * Match only rows where `column` matches any of `patterns` case-insensitively. 30156 * 30157 * @param column - The column to filter on 30158 * @param patterns - The patterns to match with 30159 * 30160 * @category Database 30161 * @subcategory Using filters 30162 */ 30163 ilikeAnyOf(n, e) { 30164 return this.url.searchParams.append(n, `ilike(any).{${e.join(",")}}`), this; 30165 } 30166 /** 30167 * Match only rows where `column` matches the PostgreSQL regex `pattern` 30168 * case-sensitively (using the `~` operator). 30169 * 30170 * @param column - The column to filter on 30171 * @param pattern - The PostgreSQL regular expression pattern to match with 30172 */ 30173 regexMatch(n, e) { 30174 return this.url.searchParams.append(n, `match.${e}`), this; 30175 } 30176 /** 30177 * Match only rows where `column` matches the PostgreSQL regex `pattern` 30178 * case-insensitively (using the `~*` operator). 30179 * 30180 * @param column - The column to filter on 30181 * @param pattern - The PostgreSQL regular expression pattern to match with 30182 */ 30183 regexIMatch(n, e) { 30184 return this.url.searchParams.append(n, `imatch.${e}`), this; 30185 } 30186 /** 30187 * Match only rows where `column` IS `value`. 30188 * 30189 * For non-boolean columns, this is only relevant for checking if the value of 30190 * `column` is NULL by setting `value` to `null`. 30191 * 30192 * For boolean columns, you can also set `value` to `true` or `false` and it 30193 * will behave the same way as `.eq()`. 30194 * 30195 * @param column - The column to filter on 30196 * @param value - The value to filter with 30197 * 30198 * @category Database 30199 * @subcategory Using filters 30200 * 30201 * @exampleDescription Checking for nullness, true or false 30202 * Using the `eq()` filter doesn't work when filtering for `null`. 30203 * 30204 * Instead, you need to use `is()`. 30205 * 30206 * @example Checking for nullness, true or false 30207 * ```ts 30208 * const { data, error } = await supabase 30209 * .from('countries') 30210 * .select() 30211 * .is('name', null) 30212 * ``` 30213 * 30214 * @exampleSql Checking for nullness, true or false 30215 * ```sql 30216 * create table 30217 * countries (id int8 primary key, name text); 30218 * 30219 * insert into
30220 * countries (id, name) 30221 * values 30222 * (1, 'null'), 30223 * (2, null); 30224 * ``` 30225 * 30226 * @exampleResponse Checking for nullness, true or false 30227 * ```json 30228 * { 30229 * "data": [ 30230 * { 30231 * "id": 2, 30232 * "name": "null" 30233 * } 30234 * ], 30235 * "status": 200, 30236 * "statusText": "OK" 30237 * } 30238 * ``` 30239 */ 30240 is(n, e) { 30241 return this.url.searchParams.append(n, `is.${e}`), this; 30242 } 30243 /** 30244 * Match only rows where `column` IS DISTINCT FROM `value`. 30245 * 30246 * Unlike `.neq()`, this treats `NULL` as a comparable value. Two `NULL` values 30247 * are considered equal (not distinct), and comparing `NULL` with any non-NULL 30248 * value returns true (distinct). 30249 * 30250 * @param column - The column to filter on 30251 * @param value - The value to filter with 30252 */ 30253 isDistinct(n, e) { 30254 return this.url.searchParams.append(n, `isdistinct.${e}`), this; 30255 } 30256 /** 30257 * Match only rows where `column` is included in the `values` array. 30258 * 30259 * @param column - The column to filter on 30260 * @param values - The values array to filter with 30261 * 30262 * @category Database 30263 * @subcategory Using filters 30264 * 30265 * @example With `select()` 30266 * ```ts 30267 * const { data, error } = await supabase 30268 * .from('characters') 30269 * .select() 30270 * .in('name', ['Leia', 'Han']) 30271 * ``` 30272 * 30273 * @exampleSql With `select()` 30274 * ```sql 30275 * create table 30276 * characters (id int8 primary key, name text); 30277 * 30278 * insert into 30279 * characters (id, name) 30280 * values 30281 * (1, 'Luke'), 30282 * (2, 'Leia'), 30283 * (3, 'Han'); 30284 * ``` 30285 * 30286 * @exampleResponse With `select()` 30287 * ```json 30288 * { 30289 * "data": [ 30290 * { 30291 * "id": 2, 30292 * "name": "Leia" 30293 * }, 30294 * { 30295 * "id": 3, 30296 * "name": "Han" 30297 * } 30298 * ], 30299 * "status": 200, 30300 * "statusText": "OK" 30301 * } 30302 * ``` 30303 */ 30304 in(n, e) { 30305 const t = Array.from(new Set(e)).map((i) => typeof i == "string" && nf.test(i) ? `"${i}"` : `${i}`).join(","); 30306 return this.url.searchParams.append(n, `in.(${t})`), this; 30307 } 30308 /** 30309 * Match only rows where `column` is NOT included in the `values` array. 30310 * 30311 * @param column - The column to filter on 30312 * @param values - The values array to filter with 30313 */ 30314 notIn(n, e) { 30315 const t = Array.from(new Set(e)).map((i) => typeof i == "string" && nf.test(i) ? `"${i}"` : `${i}`).join(","); 30316 return this.url.searchParams.append(n, `not.in.(${t})`), this; 30317 } 30318 /** 30319 * Only relevant for jsonb, array, and range columns. Match only rows where 30320 * `column` contains every element appearing in `value`. 30321 * 30322 * @param column - The jsonb, array, or range column to filter on 30323 * @param value - The jsonb, array, or range value to filter with 30324 * 30325 * @category Database 30326 * @subcategory Using filters 30327 * 30328 * @example On array columns 30329 * ```ts 30330 * const { data, error } = await supabase 30331 * .from('issues') 30332 * .select() 30333 * .contains('tags', ['is:open', 'priority:low']) 30334 * ``` 30335 * 30336 * @exampleSql On array columns 30337 * ```sql 30338 * create table 30339 * issues ( 30340 * id int8 primary key, 30341 * title text, 30342 * tags text[] 30343 * ); 30344 * 30345 * insert into 30346 * issues (id, title, tags) 30347 * values 30348 * (1, 'Cache invalidation is not working', array['is:open', 'severity:high', 'priority:low']), 30349 * (2, 'Use better names', array['is:open', 'severity:low', 'priority:medium']); 30350 * ``` 30351 * 30352 * @exampleResponse On array columns 30353 * ```json 30354 * { 30355 * "data": [ 30356 * { 30357 * "title": "Cache invalidation is not working" 30358 * } 30359 * ], 30360 * "status": 200, 30361 * "statusText": "OK" 30362 * } 30363 * ``` 30364 * 30365 * @exampleDescription On range columns 30366 * Postgres supports a number of [range 30367 * types](https://www.postgresql.org/docs/current/rangetypes.html). You 30368 * can filter on range columns using the string representation of range 30369 * values. 30370 * 30371 * @example On range columns 30372 * ```ts 30373 * const { data, error } = await supabase 30374 * .from('reservations') 30375 * .select() 30376 * .contains('during', '[2000-01-01 13:00, 2000-01-01 13:30)') 30377 * ``` 30378 * 30379 * @exampleSql On range columns 30380 * ```sql 30381 * create table 30382 * reservations ( 30383 * id int8 primary key, 30384 * room_name text, 30385 * during tsrange 30386 * ); 30387 * 30388 * insert into 30389 * reservations (id, room_name, during) 30390 * values 30391 * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),
30392 * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)'); 30393 * ``` 30394 * 30395 * @exampleResponse On range columns 30396 * ```json 30397 * { 30398 * "data": [ 30399 * { 30400 * "id": 1, 30401 * "room_name": "Emerald", 30402 * "during": "[\"2000-01-01 13:00:00\",\"2000-01-01 15:00:00\")" 30403 * } 30404 * ], 30405 * "status": 200, 30406 * "statusText": "OK" 30407 * } 30408 * ``` 30409 * 30410 * @example On `jsonb` columns 30411 * ```ts 30412 * const { data, error } = await supabase 30413 * .from('users') 30414 * .select('name') 30415 * .contains('address', { postcode: 90210 }) 30416 * ``` 30417 * 30418 * @exampleSql On `jsonb` columns 30419 * ```sql 30420 * create table 30421 * users ( 30422 * id int8 primary key, 30423 * name text, 30424 * address jsonb 30425 * ); 30426 * 30427 * insert into 30428 * users (id, name, address) 30429 * values 30430 * (1, 'Michael', '{ "postcode": 90210, "street": "Melrose Place" }'), 30431 * (2, 'Jane', '{}'); 30432 * ``` 30433 * 30434 * @exampleResponse On `jsonb` columns 30435 * ```json 30436 * { 30437 * "data": [ 30438 * { 30439 * "name": "Michael" 30440 * } 30441 * ], 30442 * "status": 200, 30443 * "statusText": "OK" 30444 * } 30445 * ``` 30446 */ 30447 contains(n, e) { 30448 return typeof e == "string" ? this.url.searchParams.append(n, `cs.${e}`) : Array.isArray(e) ? this.url.searchParams.append(n, `cs.{${e.join(",")}}`) : this.url.searchParams.append(n, `cs.${JSON.stringify(e)}`), this; 30449 } 30450 /** 30451 * Only relevant for jsonb, array, and range columns. Match only rows where 30452 * every element appearing in `column` is contained by `value`. 30453 * 30454 * @param column - The jsonb, array, or range column to filter on 30455 * @param value - The jsonb, array, or range value to filter with 30456 * 30457 * @category Database 30458 * @subcategory Using filters 30459 * 30460 * @example On array columns 30461 * ```ts 30462 * const { data, error } = await supabase 30463 * .from('classes') 30464 * .select('name') 30465 * .containedBy('days', ['monday', 'tuesday', 'wednesday', 'friday']) 30466 * ``` 30467 * 30468 * @exampleSql On array columns 30469 * ```sql 30470 * create table 30471 * classes ( 30472 * id int8 primary key, 30473 * name text, 30474 * days text[] 30475 * ); 30476 * 30477 * insert into 30478 * classes (id, name, days) 30479 * values 30480 * (1, 'Chemistry', array['monday', 'friday']), 30481 * (2, 'History', array['monday', 'wednesday', 'thursday']); 30482 * ``` 30483 * 30484 * @exampleResponse On array columns 30485 * ```json 30486 * { 30487 * "data": [ 30488 * { 30489 * "name": "Chemistry" 30490 * } 30491 * ], 30492 * "status": 200, 30493 * "statusText": "OK" 30494 * } 30495 * ``` 30496 * 30497 * @exampleDescription On range columns 30498 * Postgres supports a number of [range 30499 * types](https://www.postgresql.org/docs/current/rangetypes.html). You 30500 * can filter on range columns using the string representation of range 30501 * values. 30502 * 30503 * @example On range columns 30504 * ```ts 30505 * const { data, error } = await supabase 30506 * .from('reservations') 30507 * .select() 30508 * .containedBy('during', '[2000-01-01 00:00, 2000-01-01 23:59)') 30509 * ``` 30510 * 30511 * @exampleSql On range columns 30512 * ```sql 30513 * create table 30514 * reservations ( 30515 * id int8 primary key, 30516 * room_name text, 30517 * during tsrange 30518 * ); 30519 * 30520 * insert into 30521 * reservations (id, room_name, during) 30522 * values 30523 * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'), 30524 * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)'); 30525 * ``` 30526 * 30527 * @exampleResponse On range columns 30528 * ```json 30529 * { 30530 * "data": [ 30531 * { 30532 * "id": 1, 30533 * "room_name": "Emerald", 30534 * "during": "[\"2000-01-01 13:00:00\",\"2000-01-01 15:00:00\")" 30535 * } 30536 * ], 30537 * "status": 200, 30538 * "statusText": "OK" 30539 * } 30540 * ``` 30541 * 30542 * @example On `jsonb` columns 30543 * ```ts 30544 * const { data, error } = await supabase 30545 * .from('users') 30546 * .select('name') 30547 * .containedBy('address', {}) 30548 * ``` 30549 * 30550 * @exampleSql On `jsonb` columns 30551 * ```sql 30552 * create table 30553 * users ( 30554 * id int8 primary key, 30555 * name text, 30556 * address jsonb 30557 * ); 30558 * 30559 * insert into 30560 * users (id, name, address) 30561 * values 30562 * (1, 'Michael', '{ "postcode": 90210, "street": "Melrose Place" }'), 30563 * (2, 'Jane', '{}'); 30564 * ``` 30565 * 30566 * @exampleResponse On `jsonb` columns 30567 * ```json 30568 * { 30569 * "data": [ 30570 * { 30571 * "name": "Jane" 30572 * } 30573 * ], 30574 * "status": 200, 30575 * "statusText": "OK" 30576 * } 30577 * 30578 * ``` 30579 */ 30580 containedBy(n, e) { 30581 return typeof e == "string" ? this.url.searchParams.append(n, `cd.${e}`) : Array.isArray(e) ? this.url.searchParams.append(n, `cd.{${e.join(",")}}`) : this.url.searchParams.append(n, `cd.${JSON.stringify(e)}`), this; 30582 } 30583 /** 30584 * Only relevant for range columns. Match only rows where every element in 30585 * `column` is greater than any element in `range`. 30586 * 30587 * @param column - The range column to filter on 30588 * @param range - The range to filter with 30589 * 30590 * @category Database 30591 * @subcategory Using filters 30592 * 30593 * @exampleDescription With `select()` 30594 * Postgres supports a number of [range 30595 * types](https://www.postgresql.org/docs/current/rangetypes.html). You 30596 * can filter on range columns using the string representation of range 30597 * values. 30598 * 30599 * @example With `select()` 30600 * ```ts 30601 * const { data, error } = await supabase 30602 * .from('reservations') 30603 * .select() 30604 * .rangeGt('during', '[2000-01-02 08:00, 2000-01-02 09:00)') 30605 * ``` 30606 * 30607 * @exampleSql With `select()` 30608 * ```sql 30609 * create table 30610 * reservations ( 30611 * id int8 primary key, 30612 * room_name text, 30613 * during tsrange 30614 * ); 30615 * 30616 * insert into 30617 * reservations (id, room_name, during) 30618 * values 30619 * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),
30620 * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)'); 30621 * ``` 30622 * 30623 * @exampleResponse With `select()` 30624 * ```json 30625 * { 30626 * "data": [ 30627 * { 30628 * "id": 2, 30629 * "room_name": "Topaz", 30630 * "during": "[\"2000-01-02 09:00:00\",\"2000-01-02 10:00:00\")" 30631 * } 30632 * ], 30633 * "status": 200, 30634 * "statusText": "OK" 30635 * } 30636 * 30637 * ``` 30638 */ 30639 rangeGt(n, e) { 30640 return this.url.searchParams.append(n, `sr.${e}`), this; 30641 } 30642 /** 30643 * Only relevant for range columns. Match only rows where every element in 30644 * `column` is either contained in `range` or greater than any element in 30645 * `range`. 30646 * 30647 * @param column - The range column to filter on 30648 * @param range - The range to filter with 30649 * 30650 * @category Database 30651 * @subcategory Using filters 30652 * 30653 * @exampleDescription With `select()` 30654 * Postgres supports a number of [range 30655 * types](https://www.postgresql.org/docs/current/rangetypes.html). You 30656 * can filter on range columns using the string representation of range 30657 * values. 30658 * 30659 * @example With `select()` 30660 * ```ts 30661 * const { data, error } = await supabase 30662 * .from('reservations') 30663 * .select() 30664 * .rangeGte('during', '[2000-01-02 08:30, 2000-01-02 09:30)') 30665 * ``` 30666 * 30667 * @exampleSql With `select()` 30668 * ```sql 30669 * create table 30670 * reservations ( 30671 * id int8 primary key, 30672 * room_name text, 30673 * during tsrange 30674 * ); 30675 * 30676 * insert into 30677 * reservations (id, room_name, during) 30678 * values 30679 * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'), 30680 * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)'); 30681 * ``` 30682 * 30683 * @exampleResponse With `select()` 30684 * ```json 30685 * { 30686 * "data": [ 30687 * { 30688 * "id": 2, 30689 * "room_name": "Topaz", 30690 * "during": "[\"2000-01-02 09:00:00\",\"2000-01-02 10:00:00\")" 30691 * } 30692 * ], 30693 * "status": 200, 30694 * "statusText": "OK" 30695 * } 30696 * 30697 * ``` 30698 */ 30699 rangeGte(n, e) { 30700 return this.url.searchParams.append(n, `nxl.${e}`), this; 30701 } 30702 /** 30703 * Only relevant for range columns. Match only rows where every element in 30704 * `column` is less than any element in `range`. 30705 * 30706 * @param column - The range column to filter on 30707 * @param range - The range to filter with 30708 * 30709 * @category Database 30710 * @subcategory Using filters 30711 * 30712 * @exampleDescription With `select()` 30713 * Postgres supports a number of [range 30714 * types](https://www.postgresql.org/docs/current/rangetypes.html). You 30715 * can filter on range columns using the string representation of range 30716 * values. 30717 * 30718 * @example With `select()` 30719 * ```ts 30720 * const { data, error } = await supabase 30721 * .from('reservations') 30722 * .select() 30723 * .rangeLt('during', '[2000-01-01 15:00, 2000-01-01 16:00)') 30724 * ``` 30725 * 30726 * @exampleSql With `select()` 30727 * ```sql 30728 * create table 30729 * reservations ( 30730 * id int8 primary key, 30731 * room_name text, 30732 * during tsrange 30733 * ); 30734 * 30735 * insert into 30736 * reservations (id, room_name, during) 30737 * values 30738 * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'), 30739 * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)'); 30740 * ``` 30741 * 30742 * @exampleResponse With `select()` 30743 * ```json 30744 * { 30745 * "data": [ 30746 * { 30747 * "id": 1, 30748 * "room_name": "Emerald", 30749 * "during": "[\"2000-01-01 13:00:00\",\"2000-01-01 15:00:00\")" 30750 * } 30751 * ], 30752 * "status": 200, 30753 * "statusText": "OK" 30754 * } 30755 * ``` 30756 */ 30757 rangeLt(n, e) { 30758 return this.url.searchParams.append(n, `sl.${e}`), this; 30759 } 30760 /** 30761 * Only relevant for range columns. Match only rows where every element in 30762 * `column` is either contained in `range` or less than any element in 30763 * `range`. 30764 * 30765 * @param column - The range column to filter on 30766 * @param range - The range to filter with 30767 * 30768 * @category Database 30769 * @subcategory Using filters 30770 * 30771 * @exampleDescription With `select()` 30772 * Postgres supports a number of [range 30773 * types](https://www.postgresql.org/docs/current/rangetypes.html). You 30774 * can filter on range columns using the string representation of range 30775 * values. 30776 * 30777 * @example With `select()` 30778 * ```ts 30779 * const { data, error } = await supabase 30780 * .from('reservations') 30781 * .select() 30782 * .rangeLte('during', '[2000-01-01 14:00, 2000-01-01 16:00)') 30783 * ``` 30784 * 30785 * @exampleSql With `select()` 30786 * ```sql 30787 * create table 30788 * reservations ( 30789 * id int8 primary key, 30790 * room_name text, 30791 * during tsrange 30792 * ); 30793 * 30794 * insert into 30795 * reservations (id, room_name, during) 30796 * values 30797 * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'),
30798 * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)'); 30799 * ``` 30800 * 30801 * @exampleResponse With `select()` 30802 * ```json 30803 * { 30804 * "data": [ 30805 * { 30806 * "id": 1, 30807 * "room_name": "Emerald", 30808 * "during": "[\"2000-01-01 13:00:00\",\"2000-01-01 15:00:00\")" 30809 * } 30810 * ], 30811 * "status": 200, 30812 * "statusText": "OK" 30813 * } 30814 * 30815 * ``` 30816 */ 30817 rangeLte(n, e) { 30818 return this.url.searchParams.append(n, `nxr.${e}`), this; 30819 } 30820 /** 30821 * Only relevant for range columns. Match only rows where `column` is 30822 * mutually exclusive to `range` and there can be no element between the two 30823 * ranges. 30824 * 30825 * @param column - The range column to filter on 30826 * @param range - The range to filter with 30827 * 30828 * @category Database 30829 * @subcategory Using filters 30830 * 30831 * @exampleDescription With `select()` 30832 * Postgres supports a number of [range 30833 * types](https://www.postgresql.org/docs/current/rangetypes.html). You 30834 * can filter on range columns using the string representation of range 30835 * values. 30836 * 30837 * @example With `select()` 30838 * ```ts 30839 * const { data, error } = await supabase 30840 * .from('reservations') 30841 * .select() 30842 * .rangeAdjacent('during', '[2000-01-01 12:00, 2000-01-01 13:00)') 30843 * ``` 30844 * 30845 * @exampleSql With `select()` 30846 * ```sql 30847 * create table 30848 * reservations ( 30849 * id int8 primary key, 30850 * room_name text, 30851 * during tsrange 30852 * ); 30853 * 30854 * insert into 30855 * reservations (id, room_name, during) 30856 * values 30857 * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'), 30858 * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)'); 30859 * ``` 30860 * 30861 * @exampleResponse With `select()` 30862 * ```json 30863 * { 30864 * "data": [ 30865 * { 30866 * "id": 1, 30867 * "room_name": "Emerald", 30868 * "during": "[\"2000-01-01 13:00:00\",\"2000-01-01 15:00:00\")" 30869 * } 30870 * ], 30871 * "status": 200, 30872 * "statusText": "OK" 30873 * } 30874 * ``` 30875 */ 30876 rangeAdjacent(n, e) { 30877 return this.url.searchParams.append(n, `adj.${e}`), this; 30878 } 30879 /** 30880 * Only relevant for array and range columns. Match only rows where 30881 * `column` and `value` have an element in common. 30882 * 30883 * @param column - The array or range column to filter on 30884 * @param value - The array or range value to filter with 30885 * 30886 * @category Database 30887 * @subcategory Using filters 30888 * 30889 * @example On array columns 30890 * ```ts 30891 * const { data, error } = await supabase 30892 * .from('issues') 30893 * .select('title') 30894 * .overlaps('tags', ['is:closed', 'severity:high']) 30895 * ``` 30896 * 30897 * @exampleSql On array columns 30898 * ```sql 30899 * create table 30900 * issues ( 30901 * id int8 primary key, 30902 * title text, 30903 * tags text[] 30904 * ); 30905 * 30906 * insert into 30907 * issues (id, title, tags) 30908 * values 30909 * (1, 'Cache invalidation is not working', array['is:open', 'severity:high', 'priority:low']), 30910 * (2, 'Use better names', array['is:open', 'severity:low', 'priority:medium']); 30911 * ``` 30912 * 30913 * @exampleResponse On array columns 30914 * ```json 30915 * { 30916 * "data": [ 30917 * { 30918 * "title": "Cache invalidation is not working" 30919 * } 30920 * ], 30921 * "status": 200, 30922 * "statusText": "OK" 30923 * } 30924 * ``` 30925 * 30926 * @exampleDescription On range columns 30927 * Postgres supports a number of [range 30928 * types](https://www.postgresql.org/docs/current/rangetypes.html). You 30929 * can filter on range columns using the string representation of range 30930 * values. 30931 * 30932 * @example On range columns 30933 * ```ts 30934 * const { data, error } = await supabase 30935 * .from('reservations') 30936 * .select() 30937 * .overlaps('during', '[2000-01-01 12:45, 2000-01-01 13:15)') 30938 * ``` 30939 * 30940 * @exampleSql On range columns 30941 * ```sql 30942 * create table 30943 * reservations ( 30944 * id int8 primary key, 30945 * room_name text, 30946 * during tsrange 30947 * ); 30948 * 30949 * insert into 30950 * reservations (id, room_name, during) 30951 * values 30952 * (1, 'Emerald', '[2000-01-01 13:00, 2000-01-01 15:00)'), 30953 * (2, 'Topaz', '[2000-01-02 09:00, 2000-01-02 10:00)'); 30954 * ``` 30955 * 30956 * @exampleResponse On range columns 30957 * ```json 30958 * { 30959 * "data": [ 30960 * { 30961 * "id": 1, 30962 * "room_name": "Emerald", 30963 * "during": "[\"2000-01-01 13:00:00\",\"2000-01-01 15:00:00\")" 30964 * } 30965 * ], 30966 * "status": 200, 30967 * "statusText": "OK" 30968 * } 30969 * ``` 30970 */ 30971 overlaps(n, e) { 30972 return typeof e == "string" ? this.url.searchParams.append(n, `ov.${e}`) : this.url.searchParams.append(n, `ov.{${e.join(",")}}`), this; 30973 } 30974 /** 30975 * Only relevant for text and tsvector columns. Match only rows where 30976 * `column` matches the query string in `query`. 30977 * 30978 * @param column - The text or tsvector column to filter on 30979 * @param query - The query text to match with
30980 * @param options - Named parameters 30981 * @param options.config - The text search configuration to use 30982 * @param options.type - Change how the `query` text is interpreted 30983 * 30984 * @category Database 30985 * @subcategory Using filters 30986 * 30987 * @remarks 30988 * - For more information, see [Postgres full text search](/docs/guides/database/full-text-search). 30989 * 30990 * @example Text search 30991 * ```ts 30992 * const result = await supabase 30993 * .from("texts") 30994 * .select("content") 30995 * .textSearch("content", `'eggs' & 'ham'`, { 30996 * config: "english", 30997 * }); 30998 * ``` 30999 * 31000 * @exampleSql Text search 31001 * ```sql 31002 * create table texts ( 31003 * id bigint 31004 * primary key 31005 * generated always as identity, 31006 * content text 31007 * ); 31008 * 31009 * insert into texts (content) values 31010 * ('Four score and seven years ago'), 31011 * ('The road goes ever on and on'), 31012 * ('Green eggs and ham') 31013 * ; 31014 * ``` 31015 * 31016 * @exampleResponse Text search 31017 * ```json 31018 * { 31019 * "data": [ 31020 * { 31021 * "content": "Green eggs and ham" 31022 * } 31023 * ], 31024 * "status": 200, 31025 * "statusText": "OK" 31026 * } 31027 * ``` 31028 * 31029 * @exampleDescription Basic normalization 31030 * Uses PostgreSQL's `plainto_tsquery` function. 31031 * 31032 * @example Basic normalization 31033 * ```ts 31034 * const { data, error } = await supabase 31035 * .from('quotes') 31036 * .select('catchphrase') 31037 * .textSearch('catchphrase', `'fat' & 'cat'`, { 31038 * type: 'plain', 31039 * config: 'english' 31040 * }) 31041 * ``` 31042 * 31043 * @exampleDescription Full normalization 31044 * Uses PostgreSQL's `phraseto_tsquery` function. 31045 * 31046 * @example Full normalization 31047 * ```ts 31048 * const { data, error } = await supabase 31049 * .from('quotes') 31050 * .select('catchphrase') 31051 * .textSearch('catchphrase', `'fat' & 'cat'`, { 31052 * type: 'phrase', 31053 * config: 'english' 31054 * }) 31055 * ``` 31056 * 31057 * @exampleDescription Websearch 31058 * Uses PostgreSQL's `websearch_to_tsquery` function. 31059 * This function will never raise syntax errors, which makes it possible to use raw user-supplied input for search, and can be used 31060 * with advanced operators. 31061 * 31062 * - `unquoted text`: text not inside quote marks will be converted to terms separated by & operators, as if processed by plainto_tsquery. 31063 * - `"quoted text"`: text inside quote marks will be converted to terms separated by `<->` operators, as if processed by phraseto_tsquery. 31064 * - `OR`: the word âorâ will be converted to the | operator. 31065 * - `-`: a dash will be converted to the ! operator. 31066 * 31067 * @example Websearch 31068 * ```ts 31069 * const { data, error } = await supabase 31070 * .from('quotes') 31071 * .select('catchphrase') 31072 * .textSearch('catchphrase', `'fat or cat'`, { 31073 * type: 'websearch', 31074 * config: 'english' 31075 * }) 31076 * ``` 31077 */ 31078 textSearch(n, e, { config: t, type: i } = {}) { 31079 let r = ""; 31080 i === "plain" ? r = "pl" : i === "phrase" ? r = "ph" : i === "websearch" && (r = "w"); 31081 const s = t === void 0 ? "" : `(${t})`; 31082 return this.url.searchParams.append(n, `${r}fts${s}.${e}`), this; 31083 } 31084 /** 31085 * Match only rows where each column in `query` keys is equal to its 31086 * associated value. Shorthand for multiple `.eq()`s. 31087 * 31088 * @param query - The object to filter with, with column names as keys mapped 31089 * to their filter values 31090 * 31091 * @category Database 31092 * @subcategory Using filters 31093 * 31094 * @example With `select()` 31095 * ```ts 31096 * const { data, error } = await supabase 31097 * .from('characters') 31098 * .select('name') 31099 * .match({ id: 2, name: 'Leia' }) 31100 * ``` 31101 * 31102 * @exampleSql With `select()` 31103 * ```sql 31104 * create table 31105 * characters (id int8 primary key, name text); 31106 * 31107 * insert into 31108 * characters (id, name) 31109 * values 31110 * (1, 'Luke'), 31111 * (2, 'Leia'), 31112 * (3, 'Han'); 31113 * ``` 31114 * 31115 * @exampleResponse With `select()` 31116 * ```json 31117 * { 31118 * "data": [ 31119 * { 31120 * "name": "Leia" 31121 * } 31122 * ], 31123 * "status": 200, 31124 * "statusText": "OK" 31125 * } 31126 * ``` 31127 */ 31128 match(n) { 31129 return Object.entries(n).filter(([e, t]) => t !== void 0).forEach(([e, t]) => { 31130 this.url.searchParams.append(e, `eq.${t}`); 31131 }), this; 31132 } 31133 /** 31134 * Match only rows which doesn't satisfy the filter. 31135 * 31136 * Unlike most filters, `opearator` and `value` are used as-is and need to 31137 * follow [PostgREST 31138 * syntax](https://postgrest.org/en/stable/api.html#operators). You also need 31139 * to make sure they are properly sanitized. 31140 * 31141 * @param column - The column to filter on 31142 * @param operator - The operator to be negated to filter with, following 31143 * PostgREST syntax 31144 * @param value - The value to filter with, following PostgREST syntax 31145 * 31146 * @category Database 31147 * @subcategory Using filters 31148 * 31149 * @remarks 31150 * not() expects you to use the raw PostgREST syntax for the filter values. 31151 * 31152 * ```ts 31153 * .not('id', 'in', '(5,6,7)') // Use `()` for `in` filter 31154 * .not('arraycol', 'cs', '{"a","b"}') // Use `cs` for `contains()`, `{}` for array values 31155 * ``` 31156 * 31157 * @example With `select()` 31158 * ```ts 31159 * const { data, error } = await supabase 31160 * .from('countries') 31161 * .select() 31162 * .not('name', 'is', null) 31163 * ``` 31164 * 31165 * @exampleSql With `select()` 31166 * ```sql 31167 * create table 31168 * countries (id int8 primary key, name text); 31169 * 31170 * insert into
31171 * countries (id, name) 31172 * values 31173 * (1, 'null'), 31174 * (2, null); 31175 * ``` 31176 * 31177 * @exampleResponse With `select()` 31178 * ```json 31179 * { 31180 * "data": [ 31181 * { 31182 * "id": 1, 31183 * "name": "null" 31184 * } 31185 * ], 31186 * "status": 200, 31187 * "statusText": "OK" 31188 * } 31189 * 31190 * ``` 31191 */ 31192 not(n, e, t) { 31193 return this.url.searchParams.append(n, `not.${e}.${t}`), this; 31194 } 31195 /** 31196 * Match only rows which satisfy at least one of the filters. 31197 * 31198 * Unlike most filters, `filters` is used as-is and needs to follow [PostgREST 31199 * syntax](https://postgrest.org/en/stable/api.html#operators). You also need 31200 * to make sure it's properly sanitized. 31201 * 31202 * It's currently not possible to do an `.or()` filter across multiple tables. 31203 * 31204 * @param filters - The filters to use, following PostgREST syntax 31205 * @param options - Named parameters 31206 * @param options.referencedTable - Set this to filter on referenced tables 31207 * instead of the parent table 31208 * @param options.foreignTable - Deprecated, use `referencedTable` instead 31209 * 31210 * @category Database 31211 * @subcategory Using filters 31212 * 31213 * @remarks 31214 * or() expects you to use the raw PostgREST syntax for the filter names and values. 31215 * 31216 * ```ts 31217 * .or('id.in.(5,6,7), arraycol.cs.{"a","b"}') // Use `()` for `in` filter, `{}` for array values and `cs` for `contains()`. 31218 * .or('id.in.(5,6,7), arraycol.cd.{"a","b"}') // Use `cd` for `containedBy()` 31219 * ``` 31220 * 31221 * @example With `select()` 31222 * ```ts 31223 * const { data, error } = await supabase 31224 * .from('characters') 31225 * .select('name') 31226 * .or('id.eq.2,name.eq.Han') 31227 * ``` 31228 * 31229 * @exampleSql With `select()` 31230 * ```sql 31231 * create table 31232 * characters (id int8 primary key, name text); 31233 * 31234 * insert into 31235 * characters (id, name) 31236 * values 31237 * (1, 'Luke'), 31238 * (2, 'Leia'), 31239 * (3, 'Han'); 31240 * ``` 31241 * 31242 * @exampleResponse With `select()` 31243 * ```json 31244 * { 31245 * "data": [ 31246 * { 31247 * "name": "Leia" 31248 * }, 31249 * { 31250 * "name": "Han" 31251 * } 31252 * ], 31253 * "status": 200, 31254 * "statusText": "OK" 31255 * } 31256 * ``` 31257 * 31258 * @example Use `or` with `and` 31259 * ```ts 31260 * const { data, error } = await supabase 31261 * .from('characters') 31262 * .select('name') 31263 * .or('id.gt.3,and(id.eq.1,name.eq.Luke)') 31264 * ``` 31265 * 31266 * @exampleSql Use `or` with `and` 31267 * ```sql 31268 * create table 31269 * characters (id int8 primary key, name text); 31270 * 31271 * insert into 31272 * characters (id, name) 31273 * values 31274 * (1, 'Luke'), 31275 * (2, 'Leia'), 31276 * (3, 'Han'); 31277 * ``` 31278 * 31279 * @exampleResponse Use `or` with `and` 31280 * ```json 31281 * { 31282 * "data": [ 31283 * { 31284 * "name": "Luke" 31285 * } 31286 * ], 31287 * "status": 200, 31288 * "statusText": "OK" 31289 * } 31290 * ``` 31291 * 31292 * @example Use `or` on referenced tables 31293 * ```ts 31294 * const { data, error } = await supabase 31295 * .from('orchestral_sections') 31296 * .select(` 31297 * name, 31298 * instruments!inner ( 31299 * name 31300 * ) 31301 * `) 31302 * .or('section_id.eq.1,name.eq.guzheng', { referencedTable: 'instruments' }) 31303 * ``` 31304 * 31305 * @exampleSql Use `or` on referenced tables 31306 * ```sql 31307 * create table 31308 * orchestral_sections (id int8 primary key, name text); 31309 * create table 31310 * instruments ( 31311 * id int8 primary key, 31312 * section_id int8 not null references orchestral_sections, 31313 * name text 31314 * ); 31315 * 31316 * insert into 31317 * orchestral_sections (id, name) 31318 * values 31319 * (1, 'strings'), 31320 * (2, 'woodwinds'); 31321 * insert into 31322 * instruments (id, section_id, name) 31323 * values 31324 * (1, 2, 'flute'), 31325 * (2, 1, 'violin'); 31326 * ``` 31327 * 31328 * @exampleResponse Use `or` on referenced tables 31329 * ```json 31330 * { 31331 * "data": [ 31332 * { 31333 * "name": "strings", 31334 * "instruments": [ 31335 * { 31336 * "name": "violin" 31337 * } 31338 * ] 31339 * } 31340 * ], 31341 * "status": 200, 31342 * "statusText": "OK" 31343 * } 31344 * ``` 31345 */ 31346 or(n, { foreignTable: e, referencedTable: t = e } = {}) { 31347 const i = t ? `${t}.or` : "or"; 31348 return this.url.searchParams.append(i, `(${n})`), this; 31349 } 31350 /** 31351 * Match only rows which satisfy the filter. This is an escape hatch - you 31352 * should use the specific filter methods wherever possible. 31353 * 31354 * Unlike most filters, `opearator` and `value` are used as-is and need to 31355 * follow [PostgREST 31356 * syntax](https://postgrest.org/en/stable/api.html#operators). You also need 31357 * to make sure they are properly sanitized. 31358 * 31359 * @param column - The column to filter on 31360 * @param operator - The operator to filter with, following PostgREST syntax 31361 * @param value - The value to filter with, following PostgREST syntax 31362 * 31363 * @category Database 31364 * @subcategory Using filters 31365 * 31366 * @remarks 31367 * filter() expects you to use the raw PostgREST syntax for the filter values. 31368 * 31369 * ```ts 31370 * .filter('id', 'in', '(5,6,7)') // Use `()` for `in` filter 31371 * .filter('arraycol', 'cs', '{"a","b"}') // Use `cs` for `contains()`, `{}` for array values 31372 * ``` 31373 * 31374 * @example With `select()` 31375 * ```ts 31376 * const { data, error } = await supabase 31377 * .from('characters') 31378 * .select() 31379 * .filter('name', 'in', '("Han","Yoda")') 31380 * ``` 31381 * 31382 * @exampleSql With `select()` 31383 * ```sql 31384 * create table 31385 * characters (id int8 primary key, name text); 31386 * 31387 * insert into 31388 * characters (id, name) 31389 * values 31390 * (1, 'Luke'), 31391 * (2, 'Leia'), 31392 * (3, 'Han'); 31393 * ``` 31394 * 31395 * @exampleResponse With `select()` 31396 * ```json 31397 * { 31398 * "data": [ 31399 * { 31400 * "id": 3, 31401 * "name": "Han" 31402 * } 31403 * ], 31404 * "status": 200, 31405 * "statusText": "OK" 31406 * } 31407 * ``` 31408 * 31409 * @example On a referenced table 31410 * ```ts 31411 * const { data, error } = await supabase 31412 * .from('orchestral_sections') 31413 * .select(` 31414 * name, 31415 * instruments!inner ( 31416 * name 31417 * ) 31418 * `) 31419 * .filter('instruments.name', 'eq', 'flute') 31420 * ``` 31421 * 31422 * @exampleSql On a referenced table 31423 * ```sql 31424 * create table 31425 * orchestral_sections (id int8 primary key, name text); 31426 * create table 31427 * instruments ( 31428 * id int8 primary key, 31429 * section_id int8 not null references orchestral_sections, 31430 * name text 31431 * ); 31432 * 31433 * insert into 31434 * orchestral_sections (id, name) 31435 * values 31436 * (1, 'strings'), 31437 * (2, 'woodwinds'); 31438 * insert into 31439 * instruments (id, section_id, name) 31440 * values 31441 * (1, 2, 'flute'), 31442 * (2, 1, 'violin'); 31443 * ``` 31444 * 31445 * @exampleResponse On a referenced table 31446 * ```json 31447 * { 31448 * "data": [ 31449 * { 31450 * "name": "woodwinds", 31451 * "instruments": [ 31452 * { 31453 * "name": "flute" 31454 * } 31455 * ] 31456 * } 31457 * ], 31458 * "status": 200, 31459 * "statusText": "OK" 31460 * } 31461 * ``` 31462 */ 31463 filter(n, e, t) { 31464 return this.url.searchParams.append(n, `${e}.${t}`), this; 31465 } 31466}, yM = class { 31467 /** 31468 * Creates a query builder scoped to a Postgres table or view. 31469 * 31470 * @category Database 31471 * 31472 * @param url - The URL for the query
31473 * @param options - Named parameters 31474 * @param options.headers - Custom headers 31475 * @param options.schema - Postgres schema to use 31476 * @param options.fetch - Custom fetch implementation 31477 * @param options.urlLengthLimit - Maximum URL length before warning 31478 * @param options.retry - Enable automatic retries for transient errors (default: true) 31479 * 31480 * @example Using supabase-js (recommended) 31481 * ```ts 31482 * import { createClient } from '@supabase/supabase-js' 31483 * 31484 * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key') 31485 * const { data, error } = await supabase.from('users').select('*') 31486 * ``` 31487 * 31488 * @example Standalone import for bundle-sensitive environments 31489 * ```ts 31490 * import { PostgrestQueryBuilder } from '@supabase/postgrest-js' 31491 * 31492 * const query = new PostgrestQueryBuilder( 31493 * new URL('https://xyzcompany.supabase.co/rest/v1/users'), 31494 * { headers: { apikey: 'your-publishable-key' }, retry: true } 31495 * ) 31496 * ``` 31497 */ 31498 constructor(n, { headers: e = {}, schema: t, fetch: i, urlLengthLimit: r = 8e3, retry: s }) { 31499 this.url = n, this.headers = new Headers(e), this.schema = t, this.fetch = i, this.urlLengthLimit = r, this.retry = s; 31500 } 31501 /** 31502 * Clone URL and headers to prevent shared state between operations. 31503 */ 31504 cloneRequestState() { 31505 return { 31506 url: new URL(this.url.toString()), 31507 headers: new Headers(this.headers) 31508 }; 31509 } 31510 /** 31511 * Perform a SELECT query on the table or view. 31512 * 31513 * @param columns - The columns to retrieve, separated by commas. Columns can be renamed when returned with `customName:columnName` 31514 * 31515 * @param options - Named parameters 31516 * 31517 * @param options.head - When set to `true`, `data` will not be returned. 31518 * Useful if you only need the count. 31519 * 31520 * @param options.count - Count algorithm to use to count rows in the table or view. 31521 * 31522 * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the 31523 * hood. 31524 * 31525 * `"planned"`: Approximated but fast count algorithm. Uses the Postgres 31526 * statistics under the hood. 31527 * 31528 * `"estimated"`: Uses exact count for low numbers and planned count for high 31529 * numbers. 31530 * 31531 * @remarks 31532 * When using `count` with `.range()` or `.limit()`, the returned `count` is the total number of rows 31533 * that match your filters, not the number of rows in the current page. Use this to build pagination UI. 31534 31535 * - By default, Supabase projects return a maximum of 1,000 rows. This setting can be changed in your project's [API settings](/dashboard/project/_/settings/api). It's recommended that you keep it low to limit the payload size of accidental or malicious requests. You can use `range()` queries to paginate through your data. 31536 * - `select()` can be combined with [Filters](/docs/reference/javascript/using-filters) 31537 * - `select()` can be combined with [Modifiers](/docs/reference/javascript/using-modifiers) 31538 * - `apikey` is a reserved keyword if you're using the [Supabase Platform](/docs/guides/platform) and [should be avoided as a column name](https://github.com/supabase/supabase/issues/5465). * 31539 * @category Database 31540 * 31541 * @example Getting your data 31542 * ```js 31543 * const { data, error } = await supabase 31544 * .from('characters') 31545 * .select() 31546 * ``` 31547 * 31548 * @exampleSql Getting your data 31549 * ```sql 31550 * create table 31551 * characters (id int8 primary key, name text); 31552 * 31553 * insert into 31554 * characters (id, name) 31555 * values 31556 * (1, 'Harry'), 31557 * (2, 'Frodo'), 31558 * (3, 'Katniss'); 31559 * ``` 31560 * 31561 * @exampleResponse Getting your data 31562 * ```json 31563 * { 31564 * "data": [ 31565 * { 31566 * "id": 1, 31567 * "name": "Harry" 31568 * }, 31569 * { 31570 * "id": 2, 31571 * "name": "Frodo" 31572 * }, 31573 * { 31574 * "id": 3, 31575 * "name": "Katniss" 31576 * } 31577 * ], 31578 * "status": 200, 31579 * "statusText": "OK" 31580 * } 31581 * ``` 31582 * 31583 * @exampleDescription Handling errors 31584 * The most useful field on a Postgres error is usually `hint` â when the database knows the fix, it puts the literal SQL there. For example, a permission-denied error (`code: '42501'`) arrives with a `hint` like `"Grant the required privileges to the current role with: GRANT SELECT ON public.characters TO anon;"`. Log the full `error` object so the hint isn't hidden behind `error.message`. 31585 * 31586 * @example Handling errors 31587 * ```js 31588 * const { data, error } = await supabase.from('characters').select() 31589 * if (error) { 31590 * // Logs the full error: message, code, details, and hint. 31591 * console.error(error) 31592 * return 31593 * } 31594 * ``` 31595 * 31596 * @exampleResponse Handling errors 31597 * ```json 31598 * { 31599 * "error": { 31600 * "code": "42501", 31601 * "details": null, 31602 * "hint": "Grant the required privileges to the current role with: GRANT SELECT ON public.characters TO anon;", 31603 * "message": "permission denied for table characters" 31604 * }, 31605 * "status": 401, 31606 * "statusText": "Unauthorized" 31607 * } 31608 * ``` 31609 * 31610 * @example Selecting specific columns 31611 * ```js 31612 * const { data, error } = await supabase 31613 * .from('characters') 31614 * .select('name') 31615 * ``` 31616 * 31617 * @exampleSql Selecting specific columns 31618 * ```sql 31619 * create table 31620 * characters (id int8 primary key, name text); 31621 * 31622 * insert into 31623 * characters (id, name) 31624 * values 31625 * (1, 'Frodo'), 31626 * (2, 'Harry'), 31627 * (3, 'Katniss'); 31628 * ``` 31629 * 31630 * @exampleResponse Selecting specific columns 31631 * ```json 31632 * { 31633 * "data": [ 31634 * { 31635 * "name": "Frodo" 31636 * }, 31637 * { 31638 * "name": "Harry" 31639 * }, 31640 * { 31641 * "name": "Katniss" 31642 * } 31643 * ], 31644 * "status": 200, 31645 * "statusText": "OK" 31646 * } 31647 * ``` 31648 * 31649 * @exampleDescription Query referenced tables 31650 * If your database has foreign key relationships, you can query related tables too. 31651 * 31652 * @example Query referenced tables 31653 * ```js 31654 * const { data, error } = await supabase 31655 * .from('orchestral_sections') 31656 * .select(` 31657 * name, 31658 * instruments ( 31659 * name 31660 * ) 31661 * `) 31662 * ``` 31663 * 31664 * @exampleSql Query referenced tables 31665 * ```sql 31666 * create table 31667 * orchestral_sections (id int8 primary key, name text); 31668 * create table 31669 * instruments ( 31670 * id int8 primary key, 31671 * section_id int8 not null references orchestral_sections, 31672 * name text 31673 * ); 31674 * 31675 * insert into 31676 * orchestral_sections (id, name) 31677 * values 31678 * (1, 'strings'), 31679 * (2, 'woodwinds'); 31680 * insert into 31681 * instruments (id, section_id, name) 31682 * values 31683 * (1, 2, 'flute'), 31684 * (2, 1, 'violin'); 31685 * ``` 31686 * 31687 * @exampleResponse Query referenced tables 31688 * ```json 31689 * { 31690 * "data": [ 31691 * { 31692 * "name": "strings", 31693 * "instruments": [ 31694 * { 31695 * "name": "violin" 31696 * } 31697 * ] 31698 * }, 31699 * { 31700 * "name": "woodwinds", 31701 * "instruments": [ 31702 * { 31703 * "name": "flute" 31704 * } 31705 * ] 31706 * } 31707 * ], 31708 * "status": 200, 31709 * "statusText": "OK" 31710 * } 31711 * ``` 31712 * 31713 * @exampleDescription Query referenced tables with spaces in their names 31714 * If your table name contains spaces, you must use double quotes in the `select` statement to reference the table. 31715 * 31716 * @example Query referenced tables with spaces in their names 31717 * ```js 31718 * const { data, error } = await supabase 31719 * .from('orchestral sections') 31720 * .select(` 31721 * name, 31722 * "musical instruments" ( 31723 * name 31724 * ) 31725 * `) 31726 * ``` 31727 * 31728 * @exampleSql Query referenced tables with spaces in their names 31729 * ```sql 31730 * create table 31731 * "orchestral sections" (id int8 primary key, name text); 31732 * create table 31733 * "musical instruments" ( 31734 * id int8 primary key, 31735 * section_id int8 not null references "orchestral sections", 31736 * name text 31737 * ); 31738 * 31739 * insert into 31740 * "orchestral sections" (id, name) 31741 * values 31742 * (1, 'strings'), 31743 * (2, 'woodwinds'); 31744 * insert into 31745 * "musical instruments" (id, section_id, name) 31746 * values 31747 * (1, 2, 'flute'), 31748 * (2, 1, 'violin'); 31749 * ``` 31750 * 31751 * @exampleResponse Query referenced tables with spaces in their names 31752 * ```json 31753 * { 31754 * "data": [ 31755 * { 31756 * "name": "strings", 31757 * "musical instruments": [ 31758 * { 31759 * "name": "violin" 31760 * } 31761 * ] 31762 * }, 31763 * { 31764 * "name": "woodwinds", 31765 * "musical instruments": [ 31766 * { 31767 * "name": "flute" 31768 * } 31769 * ] 31770 * } 31771 * ], 31772 * "status": 200, 31773 * "statusText": "OK" 31774 * } 31775 * ``` 31776 * 31777 * @exampleDescription Query referenced tables through a join table 31778 * If you're in a situation where your tables are **NOT** directly 31779 * related, but instead are joined by a _join table_, you can still use 31780 * the `select()` method to query the related data. The join table needs 31781 * to have the foreign keys as part of its composite primary key. 31782 * 31783 * @example Query referenced tables through a join table 31784 * ```ts 31785 * const { data, error } = await supabase 31786 * .from('users') 31787 * .select(` 31788 * name, 31789 * teams ( 31790 * name 31791 * ) 31792 * `) 31793 * 31794 * ``` 31795 * 31796 * @exampleSql Query referenced tables through a join table 31797 * ```sql 31798 * create table 31799 * users ( 31800 * id int8 primary key, 31801 * name text 31802 * ); 31803 * create table 31804 * teams ( 31805 * id int8 primary key, 31806 * name text 31807 * ); 31808 * -- join table 31809 * create table 31810 * users_teams ( 31811 * user_id int8 not null references users, 31812 * team_id int8 not null references teams, 31813 * -- both foreign keys must be part of a composite primary key 31814 * primary key (user_id, team_id) 31815 * ); 31816 * 31817 * insert into 31818 * users (id, name) 31819 * values 31820 * (1, 'Kiran'), 31821 * (2, 'Evan'); 31822 * insert into 31823 * teams (id, name) 31824 * values 31825 * (1, 'Green'), 31826 * (2, 'Blue'); 31827 * insert into 31828 * users_teams (user_id, team_id) 31829 * values 31830 * (1, 1), 31831 * (1, 2), 31832 * (2, 2); 31833 * ``` 31834 * 31835 * @exampleResponse Query referenced tables through a join table 31836 * ```json 31837 * { 31838 * "data": [ 31839 * { 31840 * "name": "Kiran",
31841 * "teams": [ 31842 * { 31843 * "name": "Green" 31844 * }, 31845 * { 31846 * "name": "Blue" 31847 * } 31848 * ] 31849 * }, 31850 * { 31851 * "name": "Evan", 31852 * "teams": [ 31853 * { 31854 * "name": "Blue" 31855 * } 31856 * ] 31857 * } 31858 * ], 31859 * "status": 200, 31860 * "statusText": "OK" 31861 * } 31862 * 31863 * ``` 31864 * 31865 * @exampleDescription Query the same referenced table multiple times 31866 * If you need to query the same referenced table twice, use the name of the 31867 * joined column to identify which join to use. You can also give each 31868 * column an alias. 31869 * 31870 * @example Query the same referenced table multiple times 31871 * ```ts 31872 * const { data, error } = await supabase 31873 * .from('messages') 31874 * .select(` 31875 * content, 31876 * from:sender_id(name), 31877 * to:receiver_id(name) 31878 * `) 31879 * 31880 * // To infer types, use the name of the table (in this case `users`) and 31881 * // the name of the foreign key constraint. 31882 * const { data, error } = await supabase 31883 * .from('messages') 31884 * .select(` 31885 * content, 31886 * from:users!messages_sender_id_fkey(name), 31887 * to:users!messages_receiver_id_fkey(name) 31888 * `) 31889 * ``` 31890 * 31891 * @exampleSql Query the same referenced table multiple times 31892 * ```sql 31893 * create table 31894 * users (id int8 primary key, name text); 31895 * 31896 * create table 31897 * messages ( 31898 * sender_id int8 not null references users, 31899 * receiver_id int8 not null references users, 31900 * content text 31901 * ); 31902 * 31903 * insert into 31904 * users (id, name) 31905 * values 31906 * (1, 'Kiran'), 31907 * (2, 'Evan'); 31908 * 31909 * insert into 31910 * messages (sender_id, receiver_id, content) 31911 * values 31912 * (1, 2, 'ð'); 31913 * ``` 31914 * ``` 31915 * 31916 * @exampleResponse Query the same referenced table multiple times 31917 * ```json 31918 * { 31919 * "data": [ 31920 * { 31921 * "content": "ð", 31922 * "from": { 31923 * "name": "Kiran" 31924 * }, 31925 * "to": { 31926 * "name": "Evan" 31927 * } 31928 * } 31929 * ], 31930 * "status": 200, 31931 * "statusText": "OK" 31932 * } 31933 * ``` 31934 * 31935 * @exampleDescription Query nested foreign tables through a join table 31936 * You can use the result of a joined table to gather data in 31937 * another foreign table. With multiple references to the same foreign 31938 * table you must specify the column on which to conduct the join. 31939 * 31940 * @example Query nested foreign tables through a join table 31941 * ```ts 31942 * const { data, error } = await supabase 31943 * .from('games') 31944 * .select(` 31945 * game_id:id, 31946 * away_team:teams!games_away_team_fkey ( 31947 * users ( 31948 * id, 31949 * name 31950 * ) 31951 * ) 31952 * `) 31953 * 31954 * ``` 31955 * 31956 * @exampleSql Query nested foreign tables through a join table 31957 * ```sql 31958 * ```sql 31959 * create table 31960 * users ( 31961 * id int8 primary key, 31962 * name text 31963 * ); 31964 * create table 31965 * teams ( 31966 * id int8 primary key, 31967 * name text 31968 * ); 31969 * -- join table 31970 * create table 31971 * users_teams ( 31972 * user_id int8 not null references users, 31973 * team_id int8 not null references teams, 31974 * 31975 * primary key (user_id, team_id) 31976 * ); 31977 * create table 31978 * games ( 31979 * id int8 primary key, 31980 * home_team int8 not null references teams, 31981 * away_team int8 not null references teams, 31982 * name text 31983 * ); 31984 * 31985 * insert into users (id, name) 31986 * values 31987 * (1, 'Kiran'), 31988 * (2, 'Evan'); 31989 * insert into 31990 * teams (id, name) 31991 * values 31992 * (1, 'Green'), 31993 * (2, 'Blue'); 31994 * insert into 31995 * users_teams (user_id, team_id) 31996 * values 31997 * (1, 1), 31998 * (1, 2), 31999 * (2, 2); 32000 * insert into 32001 * games (id, home_team, away_team, name) 32002 * values 32003 * (1, 1, 2, 'Green vs Blue'), 32004 * (2, 2, 1, 'Blue vs Green'); 32005 * ``` 32006 * 32007 * @exampleResponse Query nested foreign tables through a join table 32008 * ```json 32009 * { 32010 * "data": [ 32011 * { 32012 * "game_id": 1, 32013 * "away_team": { 32014 * "users": [ 32015 * { 32016 * "id": 1, 32017 * "name": "Kiran" 32018 * }, 32019 * { 32020 * "id": 2, 32021 * "name": "Evan" 32022 * } 32023 * ] 32024 * } 32025 * }, 32026 * { 32027 * "game_id": 2, 32028 * "away_team": { 32029 * "users": [ 32030 * { 32031 * "id": 1, 32032 * "name": "Kiran" 32033 * } 32034 * ] 32035 * } 32036 * } 32037 * ], 32038 * "status": 200, 32039 * "statusText": "OK" 32040 * } 32041 * 32042 * ``` 32043 * 32044 * @exampleDescription Filtering through referenced tables 32045 * If the filter on a referenced table's column is not satisfied, the referenced 32046 * table returns `[]` or `null` but the parent table is not filtered out. 32047 * If you want to filter out the parent table rows, use the `!inner` hint 32048 * 32049 * @example Filtering through referenced tables 32050 * ```ts 32051 * const { data, error } = await supabase 32052 * .from('instruments') 32053 * .select('name, orchestral_sections(*)') 32054 * .eq('orchestral_sections.name', 'percussion') 32055 * ``` 32056 * 32057 * @exampleSql Filtering through referenced tables 32058 * ```sql 32059 * create table 32060 * orchestral_sections (id int8 primary key, name text); 32061 * create table 32062 * instruments ( 32063 * id int8 primary key, 32064 * section_id int8 not null references orchestral_sections, 32065 * name text 32066 * ); 32067 * 32068 * insert into 32069 * orchestral_sections (id, name) 32070 * values 32071 * (1, 'strings'), 32072 * (2, 'woodwinds'); 32073 * insert into 32074 * instruments (id, section_id, name) 32075 * values 32076 * (1, 2, 'flute'), 32077 * (2, 1, 'violin'); 32078 * ``` 32079 * 32080 * @exampleResponse Filtering through referenced tables 32081 * ```json 32082 * { 32083 * "data": [ 32084 * { 32085 * "name": "flute", 32086 * "orchestral_sections": null 32087 * }, 32088 * { 32089 * "name": "violin", 32090 * "orchestral_sections": null 32091 * } 32092 * ], 32093 * "status": 200, 32094 * "statusText": "OK" 32095 * } 32096 * ``` 32097 * 32098 * @exampleDescription Querying referenced table with count 32099 * You can get the number of rows in a related table by using the 32100 * **count** property. 32101 * 32102 * @example Querying referenced table with count 32103 * ```ts 32104 * const { data, error } = await supabase 32105 * .from('orchestral_sections') 32106 * .select(`*, instruments(count)`) 32107 * ``` 32108 * 32109 * @exampleSql Querying referenced table with count 32110 * ```sql 32111 * create table orchestral_sections ( 32112 * "id" "uuid" primary key default "extensions"."uuid_generate_v4"() not null, 32113 * "name" text 32114 * ); 32115 * 32116 * create table characters ( 32117 * "id" "uuid" primary key default "extensions"."uuid_generate_v4"() not null, 32118 * "name" text, 32119 * "section_id" "uuid" references public.orchestral_sections on delete cascade 32120 * ); 32121 * 32122 * with section as ( 32123 * insert into orchestral_sections (name) 32124 * values ('strings') returning id 32125 * ) 32126 * insert into instruments (name, section_id) values 32127 * ('violin', (select id from section)), 32128 * ('viola', (select id from section)), 32129 * ('cello', (select id from section)), 32130 * ('double bass', (select id from section)); 32131 * ``` 32132 * 32133 * @exampleResponse Querying referenced table with count 32134 * ```json 32135 * [ 32136 * { 32137 * "id": "693694e7-d993-4360-a6d7-6294e325d9b6", 32138 * "name": "strings", 32139 * "instruments": [ 32140 * { 32141 * "count": 4 32142 * } 32143 * ] 32144 * } 32145 * ] 32146 * ``` 32147 * 32148 * @exampleDescription Querying with count option 32149 * You can get the number of rows by using the 32150 * [count](/docs/reference/javascript/select#parameters) option. 32151 * 32152 * @example Querying with count option 32153 * ```ts 32154 * const { count, error } = await supabase 32155 * .from('characters') 32156 * .select('*', { count: 'exact', head: true }) 32157 * ``` 32158 * 32159 * @exampleSql Querying with count option 32160 * ```sql 32161 * create table 32162 * characters (id int8 primary key, name text); 32163 * 32164 * insert into 32165 * characters (id, name) 32166 * values 32167 * (1, 'Luke'), 32168 * (2, 'Leia'), 32169 * (3, 'Han'); 32170 * ``` 32171 * 32172 * @exampleResponse Querying with count option 32173 * ```json 32174 * { 32175 * "count": 3, 32176 * "status": 200, 32177 * "statusText": "OK" 32178 * } 32179 * ``` 32180 * 32181 * @exampleDescription Querying JSON data 32182 * You can select and filter data inside of
32183 * [JSON](/docs/guides/database/json) columns. Postgres offers some 32184 * [operators](/docs/guides/database/json#query-the-jsonb-data) for 32185 * querying JSON data. 32186 * 32187 * @example Querying JSON data 32188 * ```ts 32189 * const { data, error } = await supabase 32190 * .from('users') 32191 * .select(` 32192 * id, name, 32193 * address->city 32194 * `) 32195 * ``` 32196 * 32197 * @exampleSql Querying JSON data 32198 * ```sql 32199 * create table 32200 * users ( 32201 * id int8 primary key, 32202 * name text, 32203 * address jsonb 32204 * ); 32205 * 32206 * insert into 32207 * users (id, name, address) 32208 * values 32209 * (1, 'Frodo', '{"city":"Hobbiton"}'); 32210 * ``` 32211 * 32212 * @exampleResponse Querying JSON data 32213 * ```json 32214 * { 32215 * "data": [ 32216 * { 32217 * "id": 1, 32218 * "name": "Frodo", 32219 * "city": "Hobbiton" 32220 * } 32221 * ], 32222 * "status": 200, 32223 * "statusText": "OK" 32224 * } 32225 * ``` 32226 * 32227 * @exampleDescription Querying referenced table with inner join 32228 * If you don't want to return the referenced table contents, you can leave the parenthesis empty. 32229 * Like `.select('name, orchestral_sections!inner()')`. 32230 * 32231 * @example Querying referenced table with inner join 32232 * ```ts 32233 * const { data, error } = await supabase 32234 * .from('instruments') 32235 * .select('name, orchestral_sections!inner(name)') 32236 * .eq('orchestral_sections.name', 'woodwinds') 32237 * .limit(1) 32238 * ``` 32239 * 32240 * @exampleSql Querying referenced table with inner join 32241 * ```sql 32242 * create table orchestral_sections ( 32243 * "id" "uuid" primary key default "extensions"."uuid_generate_v4"() not null, 32244 * "name" text 32245 * ); 32246 * 32247 * create table instruments ( 32248 * "id" "uuid" primary key default "extensions"."uuid_generate_v4"() not null, 32249 * "name" text, 32250 * "section_id" "uuid" references public.orchestral_sections on delete cascade 32251 * ); 32252 * 32253 * with section as ( 32254 * insert into orchestral_sections (name) 32255 * values ('woodwinds') returning id 32256 * ) 32257 * insert into instruments (name, section_id) values 32258 * ('flute', (select id from section)), 32259 * ('clarinet', (select id from section)), 32260 * ('bassoon', (select id from section)), 32261 * ('piccolo', (select id from section)); 32262 * ``` 32263 * 32264 * @exampleResponse Querying referenced table with inner join 32265 * ```json 32266 * { 32267 * "data": [ 32268 * { 32269 * "name": "flute", 32270 * "orchestral_sections": {"name": "woodwinds"} 32271 * } 32272 * ], 32273 * "status": 200, 32274 * "statusText": "OK" 32275 * } 32276 * ``` 32277 * 32278 * @exampleDescription Switching schemas per query 32279 * In addition to setting the schema during initialization, you can also switch schemas on a per-query basis. 32280 * Make sure you've set up your [database privileges and API settings](/docs/guides/api/using-custom-schemas). 32281 * 32282 * @example Switching schemas per query 32283 * ```ts 32284 * const { data, error } = await supabase 32285 * .schema('myschema') 32286 * .from('mytable') 32287 * .select() 32288 * ``` 32289 * 32290 * @exampleSql Switching schemas per query 32291 * ```sql 32292 * create schema myschema; 32293 * 32294 * create table myschema.mytable ( 32295 * id uuid primary key default gen_random_uuid(), 32296 * data text 32297 * ); 32298 * 32299 * insert into myschema.mytable (data) values ('mydata'); 32300 * ``` 32301 * 32302 * @exampleResponse Switching schemas per query 32303 * ```json 32304 * { 32305 * "data": [ 32306 * { 32307 * "id": "4162e008-27b0-4c0f-82dc-ccaeee9a624d", 32308 * "data": "mydata" 32309 * } 32310 * ], 32311 * "status": 200, 32312 * "statusText": "OK" 32313 * } 32314 * ``` 32315 */ 32316 select(n, e) { 32317 const { head: t = !1, count: i } = e ?? {}, r = t ? "HEAD" : "GET"; 32318 let s = !1; 32319 const a = (n ?? "*").split("").map((c) => /\s/.test(c) && !s ? "" : (c === '"' && (s = !s), c)).join(""), { url: l, headers: o } = this.cloneRequestState(); 32320 return l.searchParams.set("select", a), i && o.append("Prefer", `count=${i}`), new rs({ 32321 method: r, 32322 url: l, 32323 headers: o, 32324 schema: this.schema, 32325 fetch: this.fetch, 32326 urlLengthLimit: this.urlLengthLimit, 32327 retry: this.retry 32328 }); 32329 } 32330 /** 32331 * Perform an INSERT into the table or view. 32332 * 32333 * By default, inserted rows are not returned. To return it, chain the call
32334 * with `.select()`. 32335 * 32336 * @param values - The values to insert. Pass an object to insert a single row 32337 * or an array to insert multiple rows. 32338 * 32339 * @param options - Named parameters 32340 * 32341 * @param options.count - Count algorithm to use to count inserted rows. 32342 * 32343 * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the 32344 * hood. 32345 * 32346 * `"planned"`: Approximated but fast count algorithm. Uses the Postgres 32347 * statistics under the hood. 32348 * 32349 * `"estimated"`: Uses exact count for low numbers and planned count for high 32350 * numbers. 32351 * 32352 * @param options.defaultToNull - Make missing fields default to `null`. 32353 * Otherwise, use the default value for the column. Only applies for bulk 32354 * inserts. 32355 * 32356 * @category Database 32357 * 32358 * @example Create a record 32359 * ```ts 32360 * const { error } = await supabase 32361 * .from('countries') 32362 * .insert({ id: 1, name: 'Mordor' }) 32363 * ``` 32364 * 32365 * @exampleSql Create a record 32366 * ```sql 32367 * create table 32368 * countries (id int8 primary key, name text); 32369 * ``` 32370 * 32371 * @exampleResponse Create a record 32372 * ```json 32373 * { 32374 * "status": 201, 32375 * "statusText": "Created" 32376 * } 32377 * ``` 32378 * 32379 * @exampleDescription Handling errors 32380 * `error.hint` from Postgres often contains the actionable fix (e.g. `"Grant the required privileges to the current role with: GRANT INSERT ON public.countries TO anon;"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`. 32381 * 32382 * @example Handling errors 32383 * ```js 32384 * const { error } = await supabase.from('countries').insert({ id: 1, name: 'Mordor' }) 32385 * if (error) console.error(error) 32386 * ``` 32387 * 32388 * @example Create a record and return it 32389 * ```ts 32390 * const { data, error } = await supabase 32391 * .from('countries') 32392 * .insert({ id: 1, name: 'Mordor' }) 32393 * .select() 32394 * ``` 32395 * 32396 * @exampleSql Create a record and return it 32397 * ```sql 32398 * create table 32399 * countries (id int8 primary key, name text); 32400 * ``` 32401 * 32402 * @exampleResponse Create a record and return it 32403 * ```json 32404 * { 32405 * "data": [ 32406 * { 32407 * "id": 1, 32408 * "name": "Mordor" 32409 * } 32410 * ], 32411 * "status": 201, 32412 * "statusText": "Created" 32413 * } 32414 * ``` 32415 * 32416 * @exampleDescription Bulk create 32417 * A bulk create operation is handled in a single transaction. 32418 * If any of the inserts fail, none of the rows are inserted. 32419 * 32420 * @example Bulk create 32421 * ```ts 32422 * const { error } = await supabase 32423 * .from('countries') 32424 * .insert([ 32425 * { id: 1, name: 'Mordor' }, 32426 * { id: 1, name: 'The Shire' }, 32427 * ]) 32428 * ``` 32429 * 32430 * @exampleSql Bulk create 32431 * ```sql 32432 * create table 32433 * countries (id int8 primary key, name text); 32434 * ``` 32435 * 32436 * @exampleResponse Bulk create 32437 * ```json 32438 * { 32439 * "error": { 32440 * "code": "23505", 32441 * "details": "Key (id)=(1) already exists.", 32442 * "hint": null, 32443 * "message": "duplicate key value violates unique constraint \"countries_pkey\"" 32444 * }, 32445 * "status": 409, 32446 * "statusText": "Conflict" 32447 * } 32448 * ``` 32449 */ 32450 insert(n, { count: e, defaultToNull: t = !0 } = {}) { 32451 var i; 32452 const r = "POST", { url: s, headers: a } = this.cloneRequestState(); 32453 if (e && a.append("Prefer", `count=${e}`), t || a.append("Prefer", "missing=default"), Array.isArray(n)) { 32454 const l = n.reduce((o, c) => o.concat(Object.keys(c)), []); 32455 if (l.length > 0) { 32456 const o = [...new Set(l)].map((c) => `"${c}"`); 32457 s.searchParams.set("columns", o.join(",")); 32458 } 32459 } 32460 return new rs({ 32461 method: r, 32462 url: s, 32463 headers: a, 32464 schema: this.schema, 32465 body: n, 32466 fetch: (i = this.fetch) !== null && i !== void 0 ? i : fetch, 32467 urlLengthLimit: this.urlLengthLimit, 32468 retry: this.retry 32469 }); 32470 } 32471 /** 32472 * Perform an UPSERT on the table or view. Depending on the column(s) passed 32473 * to `onConflict`, `.upsert()` allows you to perform the equivalent of 32474 * `.insert()` if a row with the corresponding `onConflict` columns doesn't 32475 * exist, or if it does exist, perform an alternative action depending on 32476 * `ignoreDuplicates`. 32477 * 32478 * By default, upserted rows are not returned. To return it, chain the call
32479 * with `.select()`. 32480 * 32481 * @param values - The values to upsert with. Pass an object to upsert a 32482 * single row or an array to upsert multiple rows. 32483 * 32484 * @param options - Named parameters 32485 * 32486 * @param options.onConflict - Comma-separated UNIQUE column(s) to specify how 32487 * duplicate rows are determined. Two rows are duplicates if all the 32488 * `onConflict` columns are equal. 32489 * 32490 * @param options.ignoreDuplicates - If `true`, duplicate rows are ignored. If 32491 * `false`, duplicate rows are merged with existing rows. 32492 * 32493 * @param options.count - Count algorithm to use to count upserted rows. 32494 * 32495 * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the 32496 * hood. 32497 * 32498 * `"planned"`: Approximated but fast count algorithm. Uses the Postgres 32499 * statistics under the hood. 32500 * 32501 * `"estimated"`: Uses exact count for low numbers and planned count for high 32502 * numbers. 32503 * 32504 * @param options.defaultToNull - Make missing fields default to `null`. 32505 * Otherwise, use the default value for the column. This only applies when 32506 * inserting new rows, not when merging with existing rows under 32507 * `ignoreDuplicates: false`. This also only applies when doing bulk upserts. 32508 * 32509 * @example Upsert a single row using a unique key 32510 * ```ts 32511 * // Upserting a single row, overwriting based on the 'username' unique column 32512 * const { data, error } = await supabase 32513 * .from('users') 32514 * .upsert({ username: 'supabot' }, { onConflict: 'username' }) 32515 * 32516 * // Example response: 32517 * // { 32518 * // data: [ 32519 * // { id: 4, message: 'bar', username: 'supabot' } 32520 * // ], 32521 * // error: null 32522 * // } 32523 * ``` 32524 * 32525 * @example Upsert with conflict resolution and exact row counting 32526 * ```ts 32527 * // Upserting and returning exact count 32528 * const { data, error, count } = await supabase 32529 * .from('users') 32530 * .upsert( 32531 * { 32532 * id: 3, 32533 * message: 'foo', 32534 * username: 'supabot' 32535 * }, 32536 * { 32537 * onConflict: 'username', 32538 * count: 'exact' 32539 * } 32540 * ) 32541 * 32542 * // Example response: 32543 * // { 32544 * // data: [ 32545 * // { 32546 * // id: 42, 32547 * // handle: "saoirse", 32548 * // display_name: "Saoirse" 32549 * // } 32550 * // ], 32551 * // count: 1, 32552 * // error: null 32553 * // } 32554 * ``` 32555 * 32556 * @category Database 32557 * 32558 * @remarks 32559 * - Primary keys must be included in `values` to use upsert. 32560 * 32561 * @example Upsert your data 32562 * ```ts 32563 * const { data, error } = await supabase 32564 * .from('instruments') 32565 * .upsert({ id: 1, name: 'piano' }) 32566 * .select() 32567 * ``` 32568 * 32569 * @exampleSql Upsert your data 32570 * ```sql 32571 * create table 32572 * instruments (id int8 primary key, name text); 32573 * 32574 * insert into 32575 * instruments (id, name) 32576 * values 32577 * (1, 'harpsichord'); 32578 * ``` 32579 * 32580 * @exampleResponse Upsert your data 32581 * ```json 32582 * { 32583 * "data": [ 32584 * { 32585 * "id": 1, 32586 * "name": "piano" 32587 * } 32588 * ], 32589 * "status": 201, 32590 * "statusText": "Created" 32591 * } 32592 * ``` 32593 * 32594 * @exampleDescription Handling errors 32595 * `error.hint` from Postgres often contains the actionable fix (e.g. `"Grant the required privileges to the current role with: GRANT INSERT, UPDATE ON public.instruments TO anon;"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`. 32596 * 32597 * @example Handling errors 32598 * ```js 32599 * const { data, error } = await supabase.from('instruments').upsert({ id: 1, name: 'piano' }).select() 32600 * if (error) console.error(error) 32601 * ``` 32602 * 32603 * @example Bulk Upsert your data 32604 * ```ts 32605 * const { data, error } = await supabase 32606 * .from('instruments') 32607 * .upsert([ 32608 * { id: 1, name: 'piano' }, 32609 * { id: 2, name: 'harp' }, 32610 * ]) 32611 * .select() 32612 * ``` 32613 * 32614 * @exampleSql Bulk Upsert your data 32615 * ```sql 32616 * create table 32617 * instruments (id int8 primary key, name text); 32618 * 32619 * insert into 32620 * instruments (id, name) 32621 * values 32622 * (1, 'harpsichord'); 32623 * ``` 32624 * 32625 * @exampleResponse Bulk Upsert your data 32626 * ```json 32627 * { 32628 * "data": [ 32629 * { 32630 * "id": 1, 32631 * "name": "piano" 32632 * }, 32633 * { 32634 * "id": 2, 32635 * "name": "harp" 32636 * } 32637 * ], 32638 * "status": 201, 32639 * "statusText": "Created" 32640 * } 32641 * ``` 32642 * 32643 * @exampleDescription Upserting into tables with constraints 32644 * In the following query, `upsert()` implicitly uses the `id` 32645 * (primary key) column to determine conflicts. If there is no existing 32646 * row with the same `id`, `upsert()` inserts a new row, which 32647 * will fail in this case as there is already a row with `handle` `"saoirse"`. 32648 * Using the `onConflict` option, you can instruct `upsert()` to use 32649 * another column with a unique constraint to determine conflicts. 32650 * 32651 * @example Upserting into tables with constraints 32652 * ```ts 32653 * const { data, error } = await supabase 32654 * .from('users') 32655 * .upsert({ id: 42, handle: 'saoirse', display_name: 'Saoirse' }) 32656 * .select() 32657 * ``` 32658 * 32659 * @exampleSql Upserting into tables with constraints 32660 * ```sql 32661 * create table 32662 * users ( 32663 * id int8 generated by default as identity primary key, 32664 * handle text not null unique, 32665 * display_name text 32666 * ); 32667 * 32668 * insert into 32669 * users (id, handle, display_name) 32670 * values 32671 * (1, 'saoirse', null); 32672 * ``` 32673 * 32674 * @exampleResponse Upserting into tables with constraints 32675 * ```json 32676 * { 32677 * "error": { 32678 * "code": "23505", 32679 * "details": "Key (handle)=(saoirse) already exists.", 32680 * "hint": null, 32681 * "message": "duplicate key value violates unique constraint \"users_handle_key\"" 32682 * }, 32683 * "status": 409, 32684 * "statusText": "Conflict" 32685 * } 32686 * ``` 32687 */ 32688 upsert(n, { onConflict: e, ignoreDuplicates: t = !1, count: i, defaultToNull: r = !0 } = {}) { 32689 var s; 32690 const a = "POST", { url: l, headers: o } = this.cloneRequestState(); 32691 if (o.append("Prefer", `resolution=${t ? "ignore" : "merge"}-duplicates`), e !== void 0 && l.searchParams.set("on_conflict", e), i && o.append("Prefer", `count=${i}`), r || o.append("Prefer", "missing=default"), Array.isArray(n)) { 32692 const c = n.reduce((u, h) => u.concat(Object.keys(h)), []); 32693 if (c.length > 0) { 32694 const u = [...new Set(c)].map((h) => `"${h}"`); 32695 l.searchParams.set("columns", u.join(",")); 32696 } 32697 } 32698 return new rs({ 32699 method: a, 32700 url: l, 32701 headers: o, 32702 schema: this.schema, 32703 body: n, 32704 fetch: (s = this.fetch) !== null && s !== void 0 ? s : fetch, 32705 urlLengthLimit: this.urlLengthLimit, 32706 retry: this.retry 32707 }); 32708 } 32709 /** 32710 * Perform an UPDATE on the table or view. 32711 * 32712 * By default, updated rows are not returned. To return it, chain the call
32713 * with `.select()` after filters. 32714 * 32715 * @param values - The values to update with 32716 * 32717 * @param options - Named parameters 32718 * 32719 * @param options.count - Count algorithm to use to count updated rows. 32720 * 32721 * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the 32722 * hood. 32723 * 32724 * `"planned"`: Approximated but fast count algorithm. Uses the Postgres 32725 * statistics under the hood. 32726 * 32727 * `"estimated"`: Uses exact count for low numbers and planned count for high 32728 * numbers. 32729 * 32730 * @category Database 32731 * 32732 * @remarks 32733 * - `update()` should always be combined with [Filters](/docs/reference/javascript/using-filters) to target the item(s) you wish to update. 32734 * 32735 * @example Updating your data 32736 * ```ts 32737 * const { error } = await supabase 32738 * .from('instruments') 32739 * .update({ name: 'piano' }) 32740 * .eq('id', 1) 32741 * ``` 32742 * 32743 * @exampleSql Updating your data 32744 * ```sql 32745 * create table 32746 * instruments (id int8 primary key, name text); 32747 * 32748 * insert into 32749 * instruments (id, name) 32750 * values 32751 * (1, 'harpsichord'); 32752 * ``` 32753 * 32754 * @exampleResponse Updating your data 32755 * ```json 32756 * { 32757 * "status": 204, 32758 * "statusText": "No Content" 32759 * } 32760 * ``` 32761 * 32762 * @exampleDescription Handling errors 32763 * `error.hint` from Postgres often contains the actionable fix (e.g. `"Grant the required privileges to the current role with: GRANT UPDATE ON public.instruments TO anon;"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`. 32764 * 32765 * @example Handling errors 32766 * ```js 32767 * const { error } = await supabase.from('instruments').update({ name: 'piano' }).eq('id', 1) 32768 * if (error) console.error(error) 32769 * ``` 32770 * 32771 * @example Update a record and return it 32772 * ```ts 32773 * const { data, error } = await supabase 32774 * .from('instruments') 32775 * .update({ name: 'piano' }) 32776 * .eq('id', 1) 32777 * .select() 32778 * ``` 32779 * 32780 * @exampleSql Update a record and return it 32781 * ```sql 32782 * create table 32783 * instruments (id int8 primary key, name text); 32784 * 32785 * insert into 32786 * instruments (id, name) 32787 * values 32788 * (1, 'harpsichord'); 32789 * ``` 32790 * 32791 * @exampleResponse Update a record and return it 32792 * ```json 32793 * { 32794 * "data": [ 32795 * { 32796 * "id": 1, 32797 * "name": "piano" 32798 * } 32799 * ], 32800 * "status": 200, 32801 * "statusText": "OK" 32802 * } 32803 * ``` 32804 * 32805 * @exampleDescription Updating JSON data 32806 * Postgres offers some 32807 * [operators](/docs/guides/database/json#query-the-jsonb-data) for 32808 * working with JSON data. Currently, it is only possible to update the entire JSON document. 32809 * 32810 * @example Updating JSON data 32811 * ```ts 32812 * const { data, error } = await supabase 32813 * .from('users') 32814 * .update({ 32815 * address: { 32816 * street: 'Melrose Place', 32817 * postcode: 90210 32818 * } 32819 * }) 32820 * .eq('address->postcode', 90210) 32821 * .select() 32822 * ``` 32823 * 32824 * @exampleSql Updating JSON data 32825 * ```sql 32826 * create table 32827 * users ( 32828 * id int8 primary key, 32829 * name text, 32830 * address jsonb 32831 * ); 32832 * 32833 * insert into 32834 * users (id, name, address) 32835 * values 32836 * (1, 'Michael', '{ "postcode": 90210 }'); 32837 * ``` 32838 * 32839 * @exampleResponse Updating JSON data 32840 * ```json 32841 * { 32842 * "data": [ 32843 * { 32844 * "id": 1, 32845 * "name": "Michael", 32846 * "address": { 32847 * "street": "Melrose Place", 32848 * "postcode": 90210 32849 * } 32850 * } 32851 * ], 32852 * "status": 200, 32853 * "statusText": "OK" 32854 * } 32855 * ``` 32856 */ 32857 update(n, { count: e } = {}) { 32858 var t; 32859 const i = "PATCH", { url: r, headers: s } = this.cloneRequestState(); 32860 return e && s.append("Prefer", `count=${e}`), new rs({ 32861 method: i, 32862 url: r, 32863 headers: s, 32864 schema: this.schema, 32865 body: n, 32866 fetch: (t = this.fetch) !== null && t !== void 0 ? t : fetch, 32867 urlLengthLimit: this.urlLengthLimit, 32868 retry: this.retry 32869 }); 32870 } 32871 /** 32872 * Perform a DELETE on the table or view. 32873 * 32874 * By default, deleted rows are not returned. To return it, chain the call
32875 * with `.select()` after filters. 32876 * 32877 * @param options - Named parameters 32878 * 32879 * @param options.count - Count algorithm to use to count deleted rows. 32880 * 32881 * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the 32882 * hood. 32883 * 32884 * `"planned"`: Approximated but fast count algorithm. Uses the Postgres 32885 * statistics under the hood. 32886 * 32887 * `"estimated"`: Uses exact count for low numbers and planned count for high 32888 * numbers. 32889 * 32890 * @category Database 32891 * 32892 * @remarks 32893 * - `delete()` should always be combined with [filters](/docs/reference/javascript/using-filters) to target the item(s) you wish to delete. 32894 * - If you use `delete()` with filters and you have 32895 * [RLS](/docs/learn/auth-deep-dive/auth-row-level-security) enabled, only 32896 * rows visible through `SELECT` policies are deleted. Note that by default 32897 * no rows are visible, so you need at least one `SELECT`/`ALL` policy that 32898 * makes the rows visible. 32899 * - When using `delete().in()`, specify an array of values to target multiple rows with a single query. This is particularly useful for batch deleting entries that share common criteria, such as deleting users by their IDs. Ensure that the array you provide accurately represents all records you intend to delete to avoid unintended data removal. 32900 * 32901 * @example Delete a single record 32902 * ```ts 32903 * const response = await supabase 32904 * .from('countries') 32905 * .delete() 32906 * .eq('id', 1) 32907 * ``` 32908 * 32909 * @exampleSql Delete a single record 32910 * ```sql 32911 * create table 32912 * countries (id int8 primary key, name text); 32913 * 32914 * insert into 32915 * countries (id, name) 32916 * values 32917 * (1, 'Mordor'); 32918 * ``` 32919 * 32920 * @exampleResponse Delete a single record 32921 * ```json 32922 * { 32923 * "status": 204, 32924 * "statusText": "No Content" 32925 * } 32926 * ``` 32927 * 32928 * @exampleDescription Handling errors 32929 * `error.hint` from Postgres often contains the actionable fix (e.g. `"Grant the required privileges to the current role with: GRANT DELETE ON public.countries TO anon;"` for a `42501` permission-denied error). Log the full `error` object so it isn't hidden behind `error.message`. 32930 * 32931 * @example Handling errors 32932 * ```js 32933 * const { error } = await supabase.from('countries').delete().eq('id', 1) 32934 * if (error) console.error(error) 32935 * ``` 32936 * 32937 * @example Delete a record and return it 32938 * ```ts 32939 * const { data, error } = await supabase 32940 * .from('countries') 32941 * .delete() 32942 * .eq('id', 1) 32943 * .select() 32944 * ``` 32945 * 32946 * @exampleSql Delete a record and return it 32947 * ```sql 32948 * create table 32949 * countries (id int8 primary key, name text); 32950 * 32951 * insert into 32952 * countries (id, name) 32953 * values 32954 * (1, 'Mordor'); 32955 * ``` 32956 * 32957 * @exampleResponse Delete a record and return it 32958 * ```json 32959 * { 32960 * "data": [ 32961 * { 32962 * "id": 1, 32963 * "name": "Mordor" 32964 * } 32965 * ], 32966 * "status": 200, 32967 * "statusText": "OK" 32968 * } 32969 * ``` 32970 * 32971 * @example Delete multiple records 32972 * ```ts 32973 * const response = await supabase 32974 * .from('countries') 32975 * .delete() 32976 * .in('id', [1, 2, 3]) 32977 * ``` 32978 * 32979 * @exampleSql Delete multiple records 32980 * ```sql 32981 * create table 32982 * countries (id int8 primary key, name text); 32983 * 32984 * insert into 32985 * countries (id, name) 32986 * values 32987 * (1, 'Rohan'), (2, 'The Shire'), (3, 'Mordor'); 32988 * ``` 32989 * 32990 * @exampleResponse Delete multiple records 32991 * ```json 32992 * { 32993 * "status": 204, 32994 * "statusText": "No Content" 32995 * } 32996 * ``` 32997 */ 32998 delete({ count: n } = {}) { 32999 var e; 33000 const t = "DELETE", { url: i, headers: r } = this.cloneRequestState(); 33001 return n && r.append("Prefer", `count=${n}`), new rs({ 33002 method: t, 33003 url: i, 33004 headers: r, 33005 schema: this.schema, 33006 fetch: (e = this.fetch) !== null && e !== void 0 ? e : fetch, 33007 urlLengthLimit: this.urlLengthLimit, 33008 retry: this.retry 33009 }); 33010 } 33011}; 33012function ua(n) { 33013 "@babel/helpers - typeof"; 33014 return ua = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(e) { 33015 return typeof e; 33016 } : function(e) { 33017 return e && typeof Symbol == "function" && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e; 33018 }, ua(n); 33019} 33020function xM(n, e) { 33021 if (ua(n) != "object" || !n) return n; 33022 var t = n[Symbol.toPrimitive]; 33023 if (t !== void 0) { 33024 var i = t.call(n, e); 33025 if (ua(i) != "object") return i; 33026 throw new TypeError("@@toPrimitive must return a primitive value."); 33027 } 33028 return (e === "string" ? String : Number)(n); 33029} 33030function bM(n) { 33031 var e = xM(n, "string"); 33032 return ua(e) == "symbol" ? e : e + ""; 33033} 33034function wM(n, e, t) { 33035 return (e = bM(e)) in n ? Object.defineProperty(n, e, { 33036 value: t, 33037 enumerable: !0, 33038 configurable: !0, 33039 writable: !0 33040 }) : n[e] = t, n; 33041} 33042function rf(n, e) { 33043 var t = Object.keys(n); 33044 if (Object.getOwnPropertySymbols) { 33045 var i = Object.getOwnPropertySymbols(n); 33046 e && (i = i.filter(function(r) { 33047 return Object.getOwnPropertyDescriptor(n, r).enumerable; 33048 })), t.push.apply(t, i); 33049 } 33050 return t; 33051} 33052function io(n) { 33053 for (var e = 1; e < arguments.length; e++) { 33054 var t = arguments[e] != null ? arguments[e] : {};
33055 e % 2 ? rf(Object(t), !0).forEach(function(i) { 33056 wM(n, i, t[i]); 33057 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(n, Object.getOwnPropertyDescriptors(t)) : rf(Object(t)).forEach(function(i) { 33058 Object.defineProperty(n, i, Object.getOwnPropertyDescriptor(t, i)); 33059 }); 33060 } 33061 return n; 33062} 33063var SM = class bm { 33064 /** 33065 * Creates a PostgREST client. 33066 * 33067 * @param url - URL of the PostgREST endpoint 33068 * @param options - Named parameters 33069 * @param options.headers - Custom headers 33070 * @param options.schema - Postgres schema to switch to 33071 * @param options.fetch - Custom fetch 33072 * @param options.timeout - Optional timeout in milliseconds for all requests. When set, requests will automatically abort after this duration to prevent indefinite hangs. 33073 * @param options.urlLengthLimit - Maximum URL length in characters before warnings/errors are triggered. Defaults to 8000. 33074 * @param options.retry - Enable or disable automatic retries for transient errors. 33075 * When enabled, idempotent requests (GET, HEAD, OPTIONS) that fail with network 33076 * errors or HTTP 503/520 responses will be automatically retried up to 3 times 33077 * with exponential backoff (1s, 2s, 4s). Defaults to `true`. 33078 * @example Using supabase-js (recommended) 33079 * ```ts 33080 * import { createClient } from '@supabase/supabase-js' 33081 * 33082 * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key') 33083 * const { data, error } = await supabase.from('profiles').select('*') 33084 * ``` 33085 * 33086 * @category Database 33087 * 33088 * @remarks 33089 * - A `timeout` option (in milliseconds) can be set to automatically abort requests that take too long. 33090 * - A `urlLengthLimit` option (default: 8000) can be set to control when URL length warnings are included in error messages for aborted requests. 33091 * 33092 * @example Standalone import for bundle-sensitive environments 33093 * ```ts 33094 * import { PostgrestClient } from '@supabase/postgrest-js' 33095 * 33096 * const postgrest = new PostgrestClient('https://xyzcompany.supabase.co/rest/v1', { 33097 * headers: { apikey: 'your-publishable-key' }, 33098 * schema: 'public', 33099 * timeout: 30000, // 30 second timeout 33100 * }) 33101 * ``` 33102 */ 33103 constructor(e, { headers: t = {}, schema: i, fetch: r, timeout: s, urlLengthLimit: a = 8e3, retry: l } = {}) { 33104 this.url = e, this.headers = new Headers(t), this.schemaName = i, this.urlLengthLimit = a; 33105 const o = r ?? globalThis.fetch; 33106 s !== void 0 && s > 0 ? this.fetch = (c, u) => { 33107 const h = new AbortController(), d = setTimeout(() => h.abort(), s), f = u?.signal; 33108 if (f) { 33109 if (f.aborted) 33110 return clearTimeout(d), o(c, u); 33111 const p = () => { 33112 clearTimeout(d), h.abort(); 33113 }; 33114 return f.addEventListener("abort", p, { once: !0 }), o(c, io(io({}, u), {}, { signal: h.signal })).finally(() => { 33115 clearTimeout(d), f.removeEventListener("abort", p); 33116 }); 33117 } 33118 return o(c, io(io({}, u), {}, { signal: h.signal })).finally(() => clearTimeout(d)); 33119 } : this.fetch = o, this.retry = l; 33120 } 33121 /** 33122 * Perform a query on a table or a view. 33123 * 33124 * @param relation - The table or view name to query 33125 * 33126 * @category Database 33127 */ 33128 from(e) { 33129 if (!e || typeof e != "string" || e.trim() === "") throw new Error("Invalid relation name: relation must be a non-empty string."); 33130 return new yM(new URL(`${this.url}/${e}`), { 33131 headers: new Headers(this.headers), 33132 schema: this.schemaName, 33133 fetch: this.fetch, 33134 urlLengthLimit: this.urlLengthLimit, 33135 retry: this.retry 33136 }); 33137 } 33138 /** 33139 * Select a schema to query or perform an function (rpc) call. 33140 * 33141 * The schema needs to be on the list of exposed schemas inside Supabase. 33142 * 33143 * @param schema - The schema to query 33144 * 33145 * @category Database 33146 */ 33147 schema(e) { 33148 return new bm(this.url, { 33149 headers: this.headers, 33150 schema: e, 33151 fetch: this.fetch, 33152 urlLengthLimit: this.urlLengthLimit, 33153 retry: this.retry 33154 }); 33155 } 33156 /** 33157 * Perform a function call. 33158 * 33159 * @param fn - The function name to call 33160 * @param args - The arguments to pass to the function call
33161 * @param options - Named parameters 33162 * @param options.head - When set to `true`, `data` will not be returned. 33163 * Useful if you only need the count. 33164 * @param options.get - When set to `true`, the function will be called with 33165 * read-only access mode. 33166 * @param options.count - Count algorithm to use to count rows returned by the 33167 * function. Only applicable for [set-returning 33168 * functions](https://www.postgresql.org/docs/current/functions-srf.html). 33169 * 33170 * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the 33171 * hood. 33172 * 33173 * `"planned"`: Approximated but fast count algorithm. Uses the Postgres 33174 * statistics under the hood. 33175 * 33176 * `"estimated"`: Uses exact count for low numbers and planned count for high 33177 * numbers. 33178 * 33179 * @example 33180 * ```ts 33181 * // For cross-schema functions where type inference fails, use overrideTypes: 33182 * const { data } = await supabase 33183 * .schema('schema_b') 33184 * .rpc('function_a', {}) 33185 * .overrideTypes<{ id: string; user_id: string }[]>() 33186 * ``` 33187 * 33188 * @category Database 33189 * 33190 * @example Call a Postgres function without arguments 33191 * ```ts 33192 * const { data, error } = await supabase.rpc('hello_world') 33193 * ``` 33194 * 33195 * @exampleSql Call a Postgres function without arguments 33196 * ```sql 33197 * create function hello_world() returns text as $$ 33198 * select 'Hello world'; 33199 * $$ language sql; 33200 * ``` 33201 * 33202 * @exampleResponse Call a Postgres function without arguments 33203 * ```json 33204 * { 33205 * "data": "Hello world", 33206 * "status": 200, 33207 * "statusText": "OK" 33208 * } 33209 * ``` 33210 * 33211 * @example Call a Postgres function with arguments 33212 * ```ts 33213 * const { data, error } = await supabase.rpc('echo', { say: 'ð' }) 33214 * ``` 33215 * 33216 * @exampleSql Call a Postgres function with arguments 33217 * ```sql 33218 * create function echo(say text) returns text as $$ 33219 * select say; 33220 * $$ language sql; 33221 * ``` 33222 * 33223 * @exampleResponse Call a Postgres function with arguments 33224 * ```json 33225 * { 33226 * "data": "ð", 33227 * "status": 200, 33228 * "statusText": "OK" 33229 * } 33230 * 33231 * ``` 33232 * 33233 * @exampleDescription Bulk processing 33234 * You can process large payloads by passing in an array as an argument. 33235 * 33236 * @example Bulk processing 33237 * ```ts 33238 * const { data, error } = await supabase.rpc('add_one_each', { arr: [1, 2, 3] }) 33239 * ``` 33240 * 33241 * @exampleSql Bulk processing 33242 * ```sql 33243 * create function add_one_each(arr int[]) returns int[] as $$ 33244 * select array_agg(n + 1) from unnest(arr) as n; 33245 * $$ language sql; 33246 * ``` 33247 * 33248 * @exampleResponse Bulk processing 33249 * ```json 33250 * { 33251 * "data": [ 33252 * 2, 33253 * 3, 33254 * 4 33255 * ], 33256 * "status": 200, 33257 * "statusText": "OK" 33258 * } 33259 * ``` 33260 * 33261 * @exampleDescription Call a Postgres function with filters
33262 * Postgres functions that return tables can also be combined with [Filters](/docs/reference/javascript/using-filters) and [Modifiers](/docs/reference/javascript/using-modifiers). 33263 * 33264 * @example Call a Postgres function with filters 33265 * ```ts 33266 * const { data, error } = await supabase 33267 * .rpc('list_stored_countries') 33268 * .eq('id', 1) 33269 * .single() 33270 * ``` 33271 * 33272 * @exampleSql Call a Postgres function with filters 33273 * ```sql 33274 * create table 33275 * countries (id int8 primary key, name text); 33276 * 33277 * insert into 33278 * countries (id, name) 33279 * values 33280 * (1, 'Rohan'), 33281 * (2, 'The Shire'); 33282 * 33283 * create function list_stored_countries() returns setof countries as $$ 33284 * select * from countries; 33285 * $$ language sql; 33286 * ``` 33287 * 33288 * @exampleResponse Call a Postgres function with filters 33289 * ```json 33290 * { 33291 * "data": { 33292 * "id": 1, 33293 * "name": "Rohan" 33294 * }, 33295 * "status": 200, 33296 * "statusText": "OK" 33297 * } 33298 * ``` 33299 * 33300 * @example Call a read-only Postgres function 33301 * ```ts 33302 * const { data, error } = await supabase.rpc('hello_world', undefined, { get: true }) 33303 * ``` 33304 * 33305 * @exampleSql Call a read-only Postgres function 33306 * ```sql 33307 * create function hello_world() returns text as $$ 33308 * select 'Hello world'; 33309 * $$ language sql; 33310 * ``` 33311 * 33312 * @exampleResponse Call a read-only Postgres function 33313 * ```json 33314 * { 33315 * "data": "Hello world", 33316 * "status": 200, 33317 * "statusText": "OK" 33318 * } 33319 * ``` 33320 */ 33321 rpc(e, t = {}, { head: i = !1, get: r = !1, count: s } = {}) { 33322 var a; 33323 let l; 33324 const o = new URL(`${this.url}/rpc/${e}`); 33325 let c; 33326 const u = (f) => f !== null && typeof f == "object" && (!Array.isArray(f) || f.some(u)), h = i && Object.values(t).some(u); 33327 h ? (l = "POST", c = t) : i || r ? (l = i ? "HEAD" : "GET", Object.entries(t).filter(([f, p]) => p !== void 0).map(([f, p]) => [f, Array.isArray(p) ? `{${p.join(",")}}` : `${p}`]).forEach(([f, p]) => { 33328 o.searchParams.append(f, p); 33329 })) : (l = "POST", c = t); 33330 const d = new Headers(this.headers); 33331 return h ? d.set("Prefer", s ? `count=${s},return=minimal` : "return=minimal") : s && d.set("Prefer", `count=${s}`), new rs({ 33332 method: l, 33333 url: o, 33334 headers: d, 33335 schema: this.schemaName, 33336 body: c, 33337 fetch: (a = this.fetch) !== null && a !== void 0 ? a : fetch, 33338 urlLengthLimit: this.urlLengthLimit, 33339 retry: this.retry 33340 }); 33341 } 33342}; 33343class EM { 33344 /** 33345 * Static-only utility â prevent instantiation. 33346 */ 33347 constructor() { 33348 } 33349 static detectEnvironment() { 33350 var e; 33351 if (typeof WebSocket < "u") 33352 return { type: "native", wsConstructor: WebSocket }; 33353 const t = globalThis; 33354 if (typeof globalThis < "u" && typeof t.WebSocket < "u") 33355 return { type: "native", wsConstructor: t.WebSocket }; 33356 const i = typeof global < "u" ? global : void 0; 33357 if (i && typeof i.WebSocket < "u") 33358 return { type: "native", wsConstructor: i.WebSocket }; 33359 if (typeof globalThis < "u" && typeof t.WebSocketPair < "u" && typeof globalThis.WebSocket > "u") 33360 return { 33361 type: "cloudflare", 33362 error: "Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.", 33363 workaround: "Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime." 33364 }; 33365 if (typeof globalThis < "u" && t.EdgeRuntime || typeof navigator < "u" && (!((e = navigator.userAgent) === null || e === void 0) && e.includes("Vercel-Edge"))) 33366 return { 33367 type: "unsupported", 33368 error: "Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.", 33369 workaround: "Use serverless functions or a different deployment target for WebSocket functionality." 33370 }; 33371 const r = globalThis.process; 33372 if (r) { 33373 const s = r.versions; 33374 if (s && s.node) { 33375 const a = s.node, l = parseInt(a.replace(/^v/, "").split(".")[0]); 33376 return l >= 22 ? typeof globalThis.WebSocket < "u" ? { type: "native", wsConstructor: globalThis.WebSocket } : { 33377 type: "unsupported", 33378 error: `Node.js ${l} detected but native WebSocket not found.`, 33379 workaround: "Provide a WebSocket implementation via the transport option." 33380 } : { 33381 type: "unsupported", 33382 error: `Node.js ${l} detected without native WebSocket support.`, 33383 workaround: `For Node.js < 22, install "ws" package and provide it via the transport option: 33384import ws from "ws" 33385new RealtimeClient(url, { transport: ws })` 33386 }; 33387 } 33388 } 33389 return { 33390 type: "unsupported", 33391 error: "Unknown JavaScript runtime without WebSocket support.", 33392 workaround: "Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation." 33393 }; 33394 } 33395 /** 33396 * Returns the best available WebSocket constructor for the current runtime. 33397 * 33398 * @category Realtime 33399 * 33400 * @example Example with error handling 33401 * ```ts 33402 * try { 33403 * const WS = WebSocketFactory.getWebSocketConstructor() 33404 * const socket = new WS('wss://example.com/socket') 33405 * } catch (error) { 33406 * console.error('WebSocket not available in this environment.', error) 33407 * } 33408 * ``` 33409 */ 33410 static getWebSocketConstructor() { 33411 const e = this.detectEnvironment(); 33412 if (e.wsConstructor) 33413 return e.wsConstructor; 33414 let t = e.error || "WebSocket not supported in this environment."; 33415 throw e.workaround && (t += ` 33416 33417Suggested solution: ${e.workaround}`), new Error(t); 33418 } 33419 /** 33420 * Detects whether the runtime can establish WebSocket connections. 33421 * 33422 * @category Realtime 33423 * 33424 * @example Example in a Node.js script 33425 * ```ts 33426 * if (!WebSocketFactory.isWebSocketSupported()) { 33427 * console.error('WebSockets are required for this script.') 33428 * process.exitCode = 1 33429 * } 33430 * ``` 33431 */ 33432 static isWebSocketSupported() { 33433 try { 33434 const e = this.detectEnvironment(); 33435 return e.type === "native" || e.type === "ws"; 33436 } catch { 33437 return !1; 33438 } 33439 } 33440} 33441const MM = "2.108.1", TM = `realtime-js/${MM}`, AM = "1.0.0", wm = "2.0.0", RM = wm, CM = 1e4, PM = 100, Zi = { 33442 closed: "closed", 33443 errored: "errored", 33444 joined: "joined", 33445 joining: "joining", 33446 leaving: "leaving" 33447}, Sm = { 33448 close: "phx_close", 33449 error: "phx_error", 33450 join: "phx_join", 33451 leave: "phx_leave", 33452 access_token: "access_token" 33453}, ou = { 33454 connecting: "connecting", 33455 closing: "closing", 33456 closed: "closed" 33457}; 33458class LM { 33459 constructor(e) { 33460 this.HEADER_LENGTH = 1, this.USER_BROADCAST_PUSH_META_LENGTH = 6, this.KINDS = { userBroadcastPush: 3, userBroadcast: 4 }, this.BINARY_ENCODING = 0, this.JSON_ENCODING = 1, this.BROADCAST_EVENT = "broadcast", this.allowedMetadataKeys = [], this.allowedMetadataKeys = e ?? []; 33461 } 33462 encode(e, t) { 33463 if (e.event === this.BROADCAST_EVENT && !(e.payload instanceof ArrayBuffer) && typeof e.payload.event == "string") 33464 return t(this._binaryEncodeUserBroadcastPush(e)); 33465 let i = [e.join_ref, e.ref, e.topic, e.event, e.payload]; 33466 return t(JSON.stringify(i)); 33467 } 33468 _binaryEncodeUserBroadcastPush(e) { 33469 var t; 33470 return this._isArrayBuffer((t = e.payload) === null || t === void 0 ? void 0 : t.payload) ? this._encodeBinaryUserBroadcastPush(e) : this._encodeJsonUserBroadcastPush(e); 33471 } 33472 _encodeBinaryUserBroadcastPush(e) { 33473 var t, i; 33474 const r = (i = (t = e.payload) === null || t === void 0 ? void 0 : t.payload) !== null && i !== void 0 ? i : new ArrayBuffer(0); 33475 return this._encodeUserBroadcastPush(e, this.BINARY_ENCODING, r); 33476 } 33477 _encodeJsonUserBroadcastPush(e) { 33478 var t, i; 33479 const r = (i = (t = e.payload) === null || t === void 0 ? void 0 : t.payload) !== null && i !== void 0 ? i : {}, a = new TextEncoder().encode(JSON.stringify(r)).buffer; 33480 return this._encodeUserBroadcastPush(e, this.JSON_ENCODING, a); 33481 } 33482 _encodeUserBroadcastPush(e, t, i) { 33483 var r, s; 33484 const a = e.topic, l = (r = e.ref) !== null && r !== void 0 ? r : "", o = (s = e.join_ref) !== null && s !== void 0 ? s : "", c = e.payload.event, u = this.allowedMetadataKeys ? this._pick(e.payload, this.allowedMetadataKeys) : {}, h = Object.keys(u).length === 0 ? "" : JSON.stringify(u); 33485 if (o.length > 255) 33486 throw new Error(`joinRef length ${o.length} exceeds maximum of 255`); 33487 if (l.length > 255) 33488 throw new Error(`ref length ${l.length} exceeds maximum of 255`); 33489 if (a.length > 255) 33490 throw new Error(`topic length ${a.length} exceeds maximum of 255`); 33491 if (c.length > 255) 33492 throw new Error(`userEvent length ${c.length} exceeds maximum of 255`); 33493 if (h.length > 255) 33494 throw new Error(`metadata length ${h.length} exceeds maximum of 255`); 33495 const d = this.USER_BROADCAST_PUSH_META_LENGTH + o.length + l.length + a.length + c.length + h.length, f = new ArrayBuffer(this.HEADER_LENGTH + d); 33496 let p = new DataView(f), v = 0; 33497 p.setUint8(v++, this.KINDS.userBroadcastPush), p.setUint8(v++, o.length), p.setUint8(v++, l.length), p.setUint8(v++, a.length), p.setUint8(v++, c.length), p.setUint8(v++, h.length), p.setUint8(v++, t), Array.from(o, (g) => p.setUint8(v++, g.charCodeAt(0))), Array.from(l, (g) => p.setUint8(v++, g.charCodeAt(0))), Array.from(a, (g) => p.setUint8(v++, g.charCodeAt(0))), Array.from(c, (g) => p.setUint8(v++, g.charCodeAt(0))), Array.from(h, (g) => p.setUint8(v++, g.charCodeAt(0))); 33498 var m = new Uint8Array(f.byteLength + i.byteLength); 33499 return m.set(new Uint8Array(f), 0), m.set(new Uint8Array(i), f.byteLength), m.buffer; 33500 } 33501 decode(e, t) { 33502 if (this._isArrayBuffer(e)) { 33503 let i = this._binaryDecode(e); 33504 return t(i); 33505 } 33506 if (typeof e == "string") { 33507 const i = JSON.parse(e), [r, s, a, l, o] = i; 33508 return t({ join_ref: r, ref: s, topic: a, event: l, payload: o }); 33509 } 33510 return t({}); 33511 } 33512 _binaryDecode(e) { 33513 const t = new DataView(e), i = t.getUint8(0), r = new TextDecoder(); 33514 switch (i) { 33515 case this.KINDS.userBroadcast: 33516 return this._decodeUserBroadcast(e, t, r); 33517 } 33518 } 33519 _decodeUserBroadcast(e, t, i) { 33520 const r = t.getUint8(1), s = t.getUint8(2), a = t.getUint8(3), l = t.getUint8(4); 33521 let o = this.HEADER_LENGTH + 4; 33522 const c = i.decode(e.slice(o, o + r)); 33523 o = o + r; 33524 const u = i.decode(e.slice(o, o + s)); 33525 o = o + s; 33526 const h = i.decode(e.slice(o, o + a)); 33527 o = o + a; 33528 const d = e.slice(o, e.byteLength), f = l === this.JSON_ENCODING ? JSON.parse(i.decode(d)) : d, p = { 33529 type: this.BROADCAST_EVENT, 33530 event: u, 33531 payload: f 33532 }; 33533 return a > 0 && (p.meta = JSON.parse(h)), { join_ref: null, ref: null, topic: c, event: this.BROADCAST_EVENT, payload: p }; 33534 } 33535 _isArrayBuffer(e) { 33536 var t; 33537 return e instanceof ArrayBuffer || ((t = e?.constructor) === null || t === void 0 ? void 0 : t.name) === "ArrayBuffer"; 33538 } 33539 _pick(e, t) { 33540 return !e || typeof e != "object" ? {} : Object.fromEntries(Object.entries(e).filter(([i]) => t.includes(i))); 33541 } 33542} 33543var Ot; 33544(function(n) { 33545 n.abstime = "abstime", n.bool = "bool", n.date = "date", n.daterange = "daterange", n.float4 = "float4", n.float8 = "float8", n.int2 = "int2", n.int4 = "int4", n.int4range = "int4range", n.int8 = "
33545int8", n.int8range = "int8range", n.json = "json", n.jsonb = "jsonb", n.money = "money", n.numeric = "numeric", n.oid = "oid", n.reltime = "reltime", n.text = "text", n.time = "time", n.timestamp = "timestamp", n.timestamptz = "timestamptz", n.timetz = "timetz", n.tsrange = "tsrange", n.tstzrange = "tstzrange"; 33546})(Ot || (Ot = {})); 33547const sf = (n, e, t = {}) => { 33548 var i; 33549 const r = (i = t.skipTypes) !== null && i !== void 0 ? i : []; 33550 return e ? Object.keys(e).reduce((s, a) => (s[a] = NM(a, n, e, r), s), {}) : {}; 33551}, NM = (n, e, t, i) => { 33552 const r = e.find((l) => l.name === n), s = r?.type, a = t[n]; 33553 return s && !i.includes(s) ? Em(s, a) : lu(a); 33554}, Em = (n, e) => { 33555 if (n.charAt(0) === "_") { 33556 const t = n.slice(1, n.length); 33557 return OM(e, t); 33558 } 33559 switch (n) { 33560 case Ot.bool: 33561 return IM(e); 33562 case Ot.float4: 33563 case Ot.float8: 33564 case Ot.int2: 33565 case Ot.int4: 33566 case Ot.int8: 33567 case Ot.numeric: 33568 case Ot.oid: 33569 return DM(e); 33570 case Ot.json: 33571 case Ot.jsonb: 33572 return UM(e); 33573 case Ot.timestamp: 33574 return kM(e); 33575 // Format to be consistent with PostgREST 33576 case Ot.abstime: 33577 // To allow users to cast it based on Timezone 33578 case Ot.date: 33579 // To allow users to cast it based on Timezone 33580 case Ot.daterange: 33581 case Ot.int4range: 33582 case Ot.int8range: 33583 case Ot.money: 33584 case Ot.reltime: 33585 // To allow users to cast it based on Timezone 33586 case Ot.text: 33587 case Ot.time: 33588 // To allow users to cast it based on Timezone 33589 case Ot.timestamptz: 33590 // To allow users to cast it based on Timezone 33591 case Ot.timetz: 33592 // To allow users to cast it based on Timezone 33593 case Ot.tsrange: 33594 case Ot.tstzrange: 33595 return lu(e); 33596 default: 33597 return lu(e); 33598 } 33599}, lu = (n) => n, IM = (n) => { 33600 switch (n) { 33601 case "t": 33602 return !0; 33603 case "f": 33604 return !1; 33605 default: 33606 return n; 33607 } 33608}, DM = (n) => { 33609 if (typeof n == "string") { 33610 const e = parseFloat(n); 33611 if (!Number.isNaN(e)) 33612 return e; 33613 } 33614 return n; 33615}, UM = (n) => { 33616 if (typeof n == "string") 33617 try { 33618 return JSON.parse(n); 33619 } catch { 33620 return n; 33621 } 33622 return n; 33623}, OM = (n, e) => { 33624 if (typeof n != "string") 33625 return n; 33626 const t = n.length - 1, i = n[t]; 33627 if (n[0] === "{" && i === "}") { 33628 let s; 33629 const a = n.slice(1, t); 33630 try { 33631 s = JSON.parse("[" + a + "]"); 33632 } catch { 33633 s = a ? a.split(",") : []; 33634 } 33635 return s.map((l) => Em(e, l)); 33636 } 33637 return n; 33638}, kM = (n) => typeof n == "string" ? n.replace(" ", "T") : n, Mm = (n) => { 33639 const e = new URL(n); 33640 return e.protocol = e.protocol.replace(/^ws/i, "http"), e.pathname = e.pathname.replace(/\/+$/, "").replace(/\/socket\/websocket$/i, "").replace(/\/socket$/i, "").replace(/\/websocket$/i, ""), e.pathname === "" || e.pathname === "/" ? e.pathname = "/api/broadcast" : e.pathname = e.pathname + "/api/broadcast", e.href; 33641}; 33642var Qs = (n) => typeof n == "function" ? ( 33643 /** @type {() => T} */ 33644 n 33645) : function() { 33646 return n; 33647}, FM = typeof self < "u" ? self : null, ss = typeof window < "u" ? window : null, oi = FM || ss || globalThis, BM = "2.0.0", zM = 1e4, HM = 1e3, ci = ( 33648 /** @type {const} */ 33649 { connecting: 0, open: 1, closing: 2, closed: 3 } 33650), Sn = ( 33651 /** @type {const} */ 33652 { 33653 closed: "closed", 33654 errored: "errored", 33655 joined: "joined", 33656 joining: "joining", 33657 leaving: "leaving" 33658 } 33659), Pi = ( 33660 /** @type {const} */ 33661 { 33662 close: "phx_close", 33663 error: "phx_error", 33664 join: "phx_join", 33665 reply: "phx_reply", 33666 leave: "phx_leave" 33667 } 33668), cu = ( 33669 /** @type {const} */ 33670 { 33671 longpoll: "longpoll", 33672 websocket: "websocket" 33673 } 33674), GM = ( 33675 /** @type {const} */ 33676 { 33677 complete: 4 33678 } 33679), uu = "base64url.bearer.phx.", ro = class { 33680 /** 33681 * Initializes the Push 33682 * @param {Channel} channel - The Channel 33683 * @param {ChannelEvent} event - The event, for example `"phx_join"` 33684 * @param {() => Record<string, unknown>} payload - The payload, for example `{user_id: 123}` 33685 * @param {number} timeout - The push timeout in milliseconds 33686 */ 33687 constructor(n, e, t, i) { 33688 this.channel = n, this.event = e, this.payload = t || function() { 33689 return {}; 33690 }, this.receivedResp = null, this.timeout = i, this.timeoutTimer = null, this.recHo
vendor: 5,635 bytes, lines 33690-33844
33690oks = [], this.sent = !1, this.ref = void 0; 33691 } 33692 /** 33693 * 33694 * @param {number} timeout 33695 */ 33696 resend(n) { 33697 this.timeout = n, this.reset(), this.send(); 33698 } 33699 /** 33700 * 33701 */ 33702 send() { 33703 this.hasReceived("timeout") || (this.startTimeout(), this.sent = !0, this.channel.socket.push({ 33704 topic: this.channel.topic, 33705 event: this.event, 33706 payload: this.payload(), 33707 ref: this.ref, 33708 join_ref: this.channel.joinRef() 33709 })); 33710 } 33711 /** 33712 * 33713 * @param {string} status 33714 * @param {(response: any) => void} callback 33715 */ 33716 receive(n, e) { 33717 return this.hasReceived(n) && e(this.receivedResp.response), this.recHooks.push({ status: n, callback: e }), this; 33718 } 33719 reset() { 33720 this.cancelRefEvent(), this.ref = null, this.refEvent = null, this.receivedResp = null, this.sent = !1; 33721 } 33722 destroy() { 33723 this.cancelRefEvent(), this.cancelTimeout(); 33724 } 33725 /** 33726 * @private 33727 */ 33728 matchReceive({ status: n, response: e, _ref: t }) { 33729 this.recHooks.filter((i) => i.status === n).forEach((i) => i.callback(e)); 33730 } 33731 /** 33732 * @private 33733 */ 33734 cancelRefEvent() { 33735 this.refEvent && this.channel.off(this.refEvent); 33736 } 33737 cancelTimeout() { 33738 clearTimeout(this.timeoutTimer), this.timeoutTimer = null; 33739 } 33740 startTimeout() { 33741 this.timeoutTimer && this.cancelTimeout(), this.ref = this.channel.socket.makeRef(), this.refEvent = this.channel.replyEventName(this.ref), this.channel.on(this.refEvent, (n) => { 33742 this.cancelRefEvent(), this.cancelTimeout(), this.receivedResp = n, this.matchReceive(n); 33743 }), this.timeoutTimer = setTimeout(() => { 33744 this.trigger("timeout", {}); 33745 }, this.timeout); 33746 } 33747 /** 33748 * @private 33749 */ 33750 hasReceived(n) { 33751 return this.receivedResp && this.receivedResp.status === n; 33752 } 33753 trigger(n, e) { 33754 this.channel.trigger(this.refEvent, { status: n, response: e }); 33755 } 33756}, Tm = class { 33757 /** 33758 * @param {() => void} callback 33759 * @param {(tries: number) => number} timerCalc 33760 */ 33761 constructor(n, e) { 33762 this.callback = n, this.timerCalc = e, this.timer = void 0, this.tries = 0; 33763 } 33764 reset() { 33765 this.tries = 0, clearTimeout(this.timer); 33766 } 33767 /** 33768 * Cancels any previous scheduleTimeout and schedules callback 33769 */ 33770 scheduleTimeout() { 33771 clearTimeout(this.timer), this.timer = setTimeout(() => { 33772 this.tries = this.tries + 1, this.callback(); 33773 }, this.timerCalc(this.tries + 1)); 33774 } 33775}, VM = class { 33776 /** 33777 * @param {string} topic 33778 * @param {Params | (() => Params)} params 33779 * @param {Socket} socket 33780 */ 33781 constructor(n, e, t) { 33782 this.state = Sn.closed, this.topic = n, this.params = Qs(e || {}), this.socket = t, this.bindings = [], this.bindingRef = 0, this.timeout = this.socket.timeout, this.joinedOnce = !1, this.joinPush = new ro(this, Pi.join, this.params, this.timeout), this.pushBuffer = [], this.stateChangeRefs = [], this.rejoinTimer = new Tm(() => { 33783 this.socket.isConnected() && this.rejoin(); 33784 }, this.socket.rejoinAfterMs), this.stateChangeRefs.push(this.socket.onError(() => this.rejoinTimer.reset())), this.stateChangeRefs.push( 33785 this.socket.onOpen(() => { 33786 this.rejoinTimer.reset(), this.isErrored() && this.rejoin(); 33787 }) 33788 ), this.joinPush.receive("ok", () => { 33789 this.state = Sn.joined, this.rejoinTimer.reset(), this.pushBuffer.forEach((i) => i.send()), this.pushBuffer = []; 33790 }), this.joinPush.receive("error", (i) => { 33791 this.state = Sn.errored, this.socket.hasLogger() && this.socket.log("channel", `error ${this.topic}`, i), this.socket.isConnected() && this.rejoinTimer.scheduleTimeout(); 33792 }), this.onClose(() => { 33793 this.rejoinTimer.reset(), this.socket.hasLogger() && this.socket.log("channel", `close ${this.topic}`), this.state = Sn.closed, this.socket.remove(this); 33794 }), this.onError((i) => { 33795 this.socket.hasLogger() && this.socket.log("channel", `error ${this.topic}`, i), this.isJoining() && this.joinPush.reset(), this.state = Sn.errored, this.socket.isConnected() && this.rejoinTimer.scheduleTimeout(); 33796 }), this.joinPush.receive("timeout", () => { 33797 this.socket.hasLogger() && this.socket.log("channel", `timeout ${this.topic}`, this.joinPush.timeout), new ro(this, Pi.leave, Qs({}), this.timeout).send(), this.state = Sn.errored, this.joinPush.reset(), this.socket.isConnected() && this.rejoinTimer.scheduleTimeout(); 33798 }), this.on(Pi.reply, (i, r) => { 33799 this.trigger(this.replyEventName(r), i); 33800 }); 33801 } 33802 /** 33803 * Join the channel 33804 * @param {number} timeout 33805 * @returns {Push} 33806 */ 33807 join(n = this.timeout) { 33808 if (this.joinedOnce) 33809 throw new Error("tried to join multiple times. 'join' can only be called a single time per channel instance"); 33810 return this.timeout = n, this.joinedOnce = !0, this.rejoin(), this.joinPush; 33811 } 33812 /** 33813 * Teardown the channel. 33814 * 33815 * Destroys and stops related timers. 33816 */ 33817 teardown() { 33818 this.pushBuffer.forEach((n) => n.destroy()), this.pushBuffer = [], this.rejoinTimer.reset(), this.joinPush.destroy(), this.state = Sn.closed, this.bindings = []; 33819 } 33820 /** 33821 * Hook into channel close 33822 * @param {ChannelBindingCallback} callback 33823 */ 33824 onClose(n) { 33825 this.on(Pi.close, n); 33826 } 33827 /** 33828 * Hook into channel errors 33829 * @param {ChannelOnErrorCallback} callback 33830 * @return {number} 33831 */ 33832 onError(n) { 33833 return this.on(Pi.error, (e) => n(e)); 33834 } 33835 /** 33836 * Subscribes on channel events 33837 * 33838 * Subscription returns a ref counter, which can be used later to 33839 * unsubscribe the exact event listener 33840 * 33841 * @example 33842 * const ref1 = channel.on("event", do_stuff) 33843 * const ref2 = channel.on("event", do_other_stuff) 33844 * channel.off("event", ref1)
33845 * // Since unsubscription, do_stuff won't fire, 33846 * // while do_other_stuff will keep firing on the "event" 33847 * 33848 * @param {string} event 33849 * @param {ChannelBindingCallback} callback 33850 * @returns {number} ref 33851 */ 33852 on(n, e) { 33853 let t = this.bindingRef++; 33854 return this.bindings.push({ event: n, ref: t, callback: e }), t; 33855 } 33856 /** 33857 * Unsubscribes off of channel events 33858 * 33859 * Use the ref returned from a channel.on() to unsubscribe one 33860 * handler, or pass nothing for the ref to unsubscribe all 33861 * handlers for the given event. 33862 * 33863 * @example 33864 * // Unsubscribe the do_stuff handler 33865 * const ref1 = channel.on("event", do_stuff) 33866 * channel.off("event", ref1) 33867 * 33868 * // Unsubscribe all handlers from event 33869 * channel.off("event") 33870 * 33871 * @param {string} event 33872 * @param {number} [ref] 33873 */ 33874 off(n, e) { 33875 this.bindings = this.bindings.filter((t) => !(t.event === n && (typeof e > "u" || e === t.ref))); 33876 } 33877 /** 33878 * @private 33879 */ 33880 canPush() { 33881 return this.socket.isConnected() && this.isJoined(); 33882 } 33883 /** 33884 * Sends a message `event` to phoenix with the payload `payload`. 33885 * Phoenix receives this in the `handle_in(event, payload, socket)` 33886 * function. if phoenix replies or it times out (default 10000ms), 33887 * then optionally the reply can be received. 33888 * 33889 * @example 33890 * channel.push("event") 33891 * .receive("ok", payload => console.log("phoenix replied:", payload)) 33892 * .receive("error", err => console.log("phoenix errored", err)) 33893 * .receive("timeout", () => console.log("timed out pushing")) 33894 * @param {string} event 33895 * @param {Object} payload 33896 * @param {number} [timeout] 33897 * @returns {Push} 33898 */ 33899 push(n, e, t = this.timeout) { 33900 if (e = e || {}, !this.joinedOnce) 33901 throw new Error(`tried to push '${n}' to '${this.topic}' before joining. Use channel.join() before pushing events`); 33902 let i = new ro(this, n, function() { 33903 return e; 33904 }, t); 33905 return this.canPush() ? i.send() : (i.startTimeout(), this.pushBuffer.push(i)), i; 33906 } 33907 /** Leaves the channel 33908 * 33909 * Unsubscribes from server events, and 33910 * instructs channel to terminate on server 33911 * 33912 * Triggers onClose() hooks 33913 * 33914 * To receive leave acknowledgements, use the `receive` 33915 * hook to bind to the server ack, ie: 33916 * 33917 * @example 33918 * channel.leave().receive("ok", () => alert("left!") ) 33919 * 33920 * @param {number} timeout 33921 * @returns {Push} 33922 */ 33923 leave(n = this.timeout) { 33924 this.rejoinTimer.reset(), this.joinPush.cancelTimeout(), this.state = Sn.leaving; 33925 let e = () => { 33926 this.socket.hasLogger() && this.socket.log("channel", `leave ${this.topic}`), this.trigger(Pi.close, "leave"); 33927 }, t = new ro(this, Pi.leave, Qs({}), n); 33928 return t.receive("ok", () => e()).receive("timeout", () => e()), t.send(), this.canPush() || t.trigger("ok", {}), t; 33929 } 33930 /** 33931 * Overridable message hook 33932 * 33933 * Receives all events for specialized message handling 33934 * before dispatching to the channel callbacks. 33935 * 33936 * Must return the payload, modified or unmodified 33937 * @type{ChannelOnMessage} 33938 */ 33939 onMessage(n, e, t) { 33940 return e; 33941 } 33942 /** 33943 * Overridable filter hook 33944 * 33945 * If this function returns `true`, `binding`'s callback will be called. 33946 * 33947 * @type{ChannelFilterBindings} 33948 */ 33949 filterBindings(n, e, t) { 33950 return !0; 33951 } 33952 isMember(n, e, t, i) { 33953 return this.topic !== n ? !1 : i && i !== this.joinRef() ? (this.socket.hasLogger() && this.socket.log("channel", "dropping outdated message", { topic: n, event: e, payload: t, joinRef: i }), !1) : !0; 33954 } 33955 joinRef() { 33956 return this.joinPush.ref; 33957 } 33958 /** 33959 * @private 33960 */ 33961 rejoin(n = this.timeout) { 33962 this.isLeaving() || (this.socket.leaveOpenTopic(this.topic), this.state = Sn.joining, this.joinPush.resend(n)); 33963 } 33964 /** 33965 * @param {string} event 33966 * @param {unknown} [payload] 33967 * @param {?string} [ref] 33968 * @param {?string} [joinRef] 33969 */ 33970 trigger(n, e, t, i) { 33971 let r = this.onMessage(n, e, t, i); 33972 if (e && !r) 33973 throw new Error("channel onMessage callbacks must return the payload, modified or unmodified"); 33974 let s = this.bindings.filter((a) => a.event === n && this.filterBindings(a, e, t)); 33975 for (let a = 0; a < s.length; a++) 33976 s[a].callback(r, t, i || this.joinRef()); 33977 } 33978 /** 33979 * @param {string} ref 33980 */ 33981 replyEventName(n) { 33982 return `chan_reply_${n}`; 33983 } 33984 isClosed() { 33985 return this.state === Sn.closed; 33986 } 33987 isErrored() { 33988 return this.state === Sn.errored; 33989 } 33990 isJoined() { 33991 return this.state === Sn.joined; 33992 } 33993 isJoining() { 33994 return this.state === Sn.joining; 33995 } 33996 isLeaving() { 33997 return this.state === Sn.leaving; 33998 } 33999}, Do = class { 34000 static request(n, e, t, i, r, s, a) { 34001 if (oi.XDomainRequest) { 34002 let l = new oi.XDomainRequest(); 34003 return this.xdomainRequest(l, n, e, i, r, s, a); 34004 } else if (oi.XMLHttpRequest) { 34005 let l = new oi.XMLHttpRequest(); 34006 return this.xhrRequest(l, n, e, t, i, r, s, a); 34007 } else { 34008 if (oi.fetch && oi.AbortController) 34009 return this.fetchRequest(n, e, t, i, r, s, a); 34010 throw new Error("No suitable XMLHttpRequest implementation found"); 34011 } 34012 } 34013 static fetchRequest(n, e, t, i, r, s, a) { 34014 let l = { 34015 method: n, 34016 headers: t, 34017 body: i 34018 }, o = null; 34019 return r && (o = new AbortController(), setTimeout(() => o.abort(), r), l.signal = o.signal), oi.fetch(e, l).then((c) => c.text()).then((c) => this.parseJSON(c)).then((c) => a && a(c)).catch((c) => { 34020 c.name === "AbortError" && s ? s() : a && a(null); 34021 }), o; 34022 } 34023 static xdomainRequest(n, e, t, i, r, s, a) { 34024 return n.timeout = r, n.open(e, t), n.onload = () => { 34025 let l = this.parseJSON(n.responseText); 34026 a && a(l); 34027 }, s && (n.ontimeout = s), n.onprogress = () => { 34028 }, n.send(i), n; 34029 } 34030 static xhrRequest(n, e, t, i, r, s, a, l) { 34031 n.open(e, t, !0), n.timeout = s; 34032 for (let [o, c] of Object.entries(i)) 34033 n.setRequestHeader(o, c); 34034 return n.onerror = () => l && l(null), n.onreadystatechange = () => { 34035 if (n.readyState === GM.complete && l) { 34036 let o = this.parseJSON(n.responseText);
34037 l(o); 34038 } 34039 }, a && (n.ontimeout = a), n.send(r), n; 34040 } 34041 static parseJSON(n) { 34042 if (!n || n === "") 34043 return null; 34044 try { 34045 return JSON.parse(n); 34046 } catch { 34047 return console && console.log("failed to parse JSON response", n), null; 34048 } 34049 } 34050 static serialize(n, e) { 34051 let t = []; 34052 for (var i in n) { 34053 if (!Object.prototype.hasOwnProperty.call(n, i)) 34054 continue; 34055 let r = e ? `${e}[${i}]` : i, s = n[i]; 34056 typeof s == "object" ? t.push(this.serialize(s, r)) : t.push(encodeURIComponent(r) + "=" + encodeURIComponent(s)); 34057 } 34058 return t.join("&"); 34059 } 34060 static appendParams(n, e) { 34061 if (Object.keys(e).length === 0) 34062 return n; 34063 let t = n.match(/\?/) ? "&" : "?"; 34064 return `${n}${t}${this.serialize(e)}`; 34065 } 34066}, WM = (n) => { 34067 let e = "", t = new Uint8Array(n), i = t.byteLength; 34068 for (let r = 0; r < i; r++) 34069 e += String.fromCharCode(t[r]); 34070 return btoa(e); 34071}, Zr = class { 34072 constructor(n, e) { 34073 e && e.length === 2 && e[1].startsWith(uu) && (this.authToken = atob(e[1].slice(uu.length))), this.endPoint = null, this.token = null, this.skipHeartbeat = !0, this.reqs = /* @__PURE__ */ new Set(), this.awaitingBatchAck = !1, this.currentBatch = null, this.currentBatchTimer = null, this.batchBuffer = [], this.onopen = function() { 34074 }, this.onerror = function() { 34075 }, this.onmessage = function() { 34076 }, this.onclose = function() { 34077 }, this.pollEndpoint = this.normalizeEndpoint(n), this.readyState = ci.connecting, setTimeout(() => this.poll(), 0); 34078 } 34079 normalizeEndpoint(n) { 34080 return n.replace("ws://", "http://").replace("wss://", "https://").replace(new RegExp("(.*)/" + cu.websocket), "$1/" + cu.longpoll); 34081 } 34082 endpointURL() { 34083 return Do.appendParams(this.pollEndpoint, { token: this.token }); 34084 } 34085 closeAndRetry(n, e, t) { 34086 this.close(n, e, t), this.readyState = ci.connecting; 34087 } 34088 ontimeout() { 34089 this.onerror("timeout"), this.closeAndRetry(1005, "timeout", !1); 34090 } 34091 isActive() { 34092 return this.readyState === ci.open || this.readyState === ci.connecting; 34093 } 34094 poll() { 34095 const n = { Accept: "application/json" }; 34096 this.authToken && (n["X-Phoenix-AuthToken"] = this.authToken), this.ajax("GET", n, null, () => this.ontimeout(), (e) => { 34097 if (e) { 34098 var { status: t, token: i, messages: r } = e; 34099 if (t === 410 && this.token !== null) { 34100 this.onerror(410), this.closeAndRetry(3410, "session_gone", !1); 34101 return; 34102 } 34103 this.token = i; 34104 } else 34105 t = 0; 34106 switch (t) { 34107 case 200: 34108 r.forEach((s) => { 34109 setTimeout(() => this.onmessage({ data: s }), 0); 34110 }), this.poll(); 34111 break; 34112 case 204: 34113 this.poll(); 34114 break; 34115 case 410: 34116 this.readyState = ci.open, this.onopen({}), this.poll(); 34117 break; 34118 case 403: 34119 this.onerror(403), this.close(1008, "forbidden", !1); 34120 break; 34121 case 0: 34122 case 500: 34123 this.onerror(500), this.closeAndRetry(1011, "internal server error", 500); 34124 break; 34125 default: 34126 throw new Error(`unhandled poll status ${t}`); 34127 } 34128 }); 34129 } 34130 // we collect all pushes within the current event loop by 34131 // setTimeout 0, which optimizes back-to-back procedural 34132 // pushes against an empty buffer 34133 send(n) { 34134 typeof n != "string" && (n = WM(n)), this.currentBatch ? this.currentBatch.push(n) : this.awaitingBatchAck ? this.batchBuffer.push(n) : (this.currentBatch = [n], this.currentBatchTimer = setTimeout(() => { 34135 this.batchSend(this.currentBatch), this.currentBatch = null; 34136 }, 0)); 34137 } 34138 batchSend(n) { 34139 this.awaitingBatchAck = !0, this.ajax("POST", { "Content-Type": "application/x-ndjson" }, n.join(` 34140`), () => this.onerror("timeout"), (e) => { 34141 this.awaitingBatchAck = !1, !e || e.status !== 200 ? (this.onerror
34141(e && e.status), this.closeAndRetry(1011, "internal server error", !1)) : this.batchBuffer.length > 0 && (this.batchSend(this.batchBuffer), this.batchBuffer = []); 34142 }); 34143 } 34144 close(n, e, t) { 34145 for (let r of this.reqs) 34146 r.abort(); 34147 this.readyState = ci.closed; 34148 let i = Object.assign({ code: 1e3, reason: void 0, wasClean: !0 }, { code: n, reason: e, wasClean: t }); 34149 this.batchBuffer = [], clearTimeout(this.currentBatchTimer), this.currentBatchTimer = null, typeof CloseEvent < "u" ? this.onclose(new CloseEvent("close", i)) : this.onclose(i); 34150 } 34151 ajax(n, e, t, i, r) { 34152 let s, a = () => { 34153 this.reqs.delete(s), i(); 34154 }; 34155 s = Do.request(n, this.endpointURL(), e, t, this.timeout, a, (l) => { 34156 this.reqs.delete(s), this.isActive() && r(l); 34157 }), this.reqs.add(s); 34158 } 34159}, $M = class qs { 34160 /** 34161 * Initializes the Presence 34162 * @param {Channel} channel - The Channel 34163 * @param {PresenceOptions} [opts] - The options, for example `{events: {state: "state", diff: "diff"}}` 34164 */ 34165 constructor(e, t = {}) { 34166 let i = t.events || /** @type {PresenceEvents} */ 34167 { state: "presence_state", diff: "presence_diff" }; 34168 this.state = {}, this.pendingDiffs = [], this.channel = e, this.joinRef = null, this.caller = { 34169 onJoin: function() { 34170 }, 34171 onLeave: function() { 34172 }, 34173 onSync: function() { 34174 } 34175 }, this.channel.on(i.state, (r) => { 34176 let { onJoin: s, onLeave: a, onSync: l } = this.caller; 34177 this.joinRef = this.channel.joinRef(), this.state = qs.syncState(this.state, r, s, a), this.pendingDiffs.forEach((o) => { 34178 this.state = qs.syncDiff(this.state, o, s, a); 34179 }), this.pendingDiffs = [], l(); 34180 }), this.channel.on(i.diff, (r) => { 34181 let { onJoin: s, onLeave: a, onSync: l } = this.caller; 34182 this.inPendingSyncState() ? this.pendingDiffs.push(r) : (this.state = qs.syncDiff(this.state, r, s, a), l()); 34183 }); 34184 } 34185 /** 34186 * @param {PresenceOnJoin} callback 34187 */ 34188 onJoin(e) { 34189 this.caller.onJoin = e; 34190 } 34191 /** 34192 * @param {PresenceOnLeave} callback 34193 */ 34194 onLeave(e) { 34195 this.caller.onLeave = e; 34196 } 34197 /** 34198 * @param {PresenceOnSync} callback 34199 */ 34200 onSync(e) { 34201 this.caller.onSync = e; 34202 } 34203 /** 34204 * Returns the array of presences, with selected metadata. 34205 * 34206 * @template [T=PresenceState] 34207 * @param {((key: string, obj: PresenceState) => T)} [by] 34208 * 34209 * @returns {T[]} 34210 */ 34211 list(e) { 34212 return qs.list(this.state, e); 34213 } 34214 inPendingSyncState() { 34215 return !this.joinRef || this.joinRef !== this.channel.joinRef(); 34216 } 34217 // lower-level public static API 34218 /** 34219 * Used to sync the list of presences on the server 34220 * with the client's state. An optional `onJoin` and `onLeave` callback can 34221 * be provided to react to changes in the client's local presences across 34222 * disconnects and reconnects with the server. 34223 * 34224 * @param {Record<string, PresenceState>} currentState 34225 * @param {Record<string, PresenceState>} newState 34226 * @param {PresenceOnJoin} onJoin 34227 * @param {PresenceOnLeave} onLeave 34228 * 34229 * @returns {Record<string, PresenceState>} 34230 */ 34231 static syncState(e, t, i, r) { 34232 let s = this.clone(e), a = {}, l = {}; 34233 return this.map(s, (o, c) => { 34234 t[o] || (l[o] = c); 34235 }), this.map(t, (o, c) => { 34236 let u = s[o]; 34237 if (u) { 34238 let h = c.metas.map((v) => v.phx_ref), d = u.metas.map((v) => v.phx_ref), f = c.metas.filter((v) => d.indexOf(v.phx_ref) < 0), p = u.metas.filter((v) => h.indexOf(v.phx_ref) < 0); 34239 f.length > 0 && (a[o] = c, a[o].metas = f), p.length > 0 && (l[o] = this.clone(u), l[o].metas = p); 34240 } else 34241 a[o] = c; 34242 }), this.syncDiff(s, { joins: a, leaves: l }, i, r); 34243 } 34244 /** 34245 * 34246 * Used to sync a diff of presence join and leave 34247 * events from the server, as they happen. Like `syncState`, `syncDiff` 34248 * accepts optional `onJoin` and `onLeave` callbacks to react to a user 34249 * joining or leaving from a device. 34250 * 34251 * @param {Record<string, PresenceState>} state 34252 * @param {PresenceDiff} diff 34253 * @param {PresenceOnJoin} onJoin 34254 * @param {PresenceOnLeave} onLeave 34255 * 34256 * @returns {Record<string, PresenceState>} 34257 */ 34258 static syncDiff(e, t, i, r) { 34259 let { joins: s, leaves: a } = this.clone(t); 34260 return i || (i = function() { 34261 }), r || (r = function() { 34262 }), this.map(s, (l, o) => { 34263 let c = e[l]; 34264 if (e[l] = this.clone(o), c) { 34265 let u = e[l].metas.map((d) => d.phx_ref), h = c.metas.filter((d) => u.indexOf(d.phx_ref) < 0); 34266 e[l].metas.unshift(...h); 34267 } 34268 i(l, c, o); 34269 }), this.map(a, (l, o) => { 34270 let c = e[l]; 34271 if (!c) 34272 return; 34273 let u = o.metas.map((h) => h.phx_ref); 34274 c.metas = c.metas.filter((h) => u.indexOf(h.phx_ref) < 0), r(l, c, o), c.metas.length === 0 && delete e[l]; 34275 }), e; 34276 } 34277 /** 34278 * Returns the array of presences, with selected metadata. 34279 * 34280 * @template [T=PresenceState] 34281 * @param {Record<string, PresenceState>} presences 34282 * @param {((key: string, obj: PresenceState) => T)} [chooser] 34283 * 34284 * @returns {T[]} 34285 */ 34286 static list(e, t) { 34287 return t || (t = function(i, r) { 34288 return r; 34289 }), this.map(e, (i, r) => t(i, r)); 34290 } 34291 // private 34292 /** 34293 * @template T 34294 * @param {Record<string, PresenceState>} obj 34295 * @param {(key: string, obj: PresenceState) => T} func 34296 */ 34297 static map(e, t) { 34298 return Object.getOwnPropertyNames(e).map((i) => t(i, e[i])); 34299 } 34300 /** 34301 * @template T 34302 * @param {T} obj 34303 * @returns {T} 34304 */ 34305 static clone(e) { 34306 return JSON.parse(JSON.stringify(e)); 34307 } 34308}, so = { 34309 HEADER_LENGTH: 1, 34310 META_LENGTH: 4, 34311 KINDS: { push: 0, reply: 1, broadcast: 2 }, 34312 /** 34313 * @template T 34314 * @param {Message<Record<string, any>>} msg 34315 * @param {(msg: ArrayBuffer | string) => T} callback 34316 * @returns {T} 34317 */ 34318 encode(n, e) { 34319 if (n.payload.constructor === ArrayBuffer) 34320 return e(this.binaryEncode(n)); 34321 { 34322 let t = [n.join_ref, n.ref, n.topic, n.event, n.payload]; 34323 return e(JSON.stringify(t)); 34324 } 34325 }, 34326 /** 34327 * @template T 34328 * @param {ArrayBuffer | string} rawPayload 34329 * @param {(msg: Message<unknown>) => T} callback 34330 * @returns {T} 34331 */ 34332 decode(n, e) { 34333 if (n.constructor === ArrayBuffer) 34334 return e(this.binaryDecode(n)); 34335 { 34336 let [t, i, r, s, a] = JSON.parse(n); 34337 return e({ join_ref: t, ref: i, topic: r, event: s, payload: a }); 34338 } 34339 }, 34340 /** @private */ 34341 binaryEncode(n) { 34342 let { join_ref: e, ref: t, event: i, topic: r, payload: s } = n, a = this.META_LENGTH + e.length + t.length + r.length + i.length, l = new ArrayBuffer(this.HEADER_LENGTH + a), o = new DataView(l), c = 0; 34343 o.setUint8(c++, this.KINDS.push), o.setUint8(c++, e.length), o.setUint8(c++, t.length), o.setUint8(c++, r.length), o.setUint8(c++, i.length), Array.from(e, (h) => o.setUint8(c++, h.charCodeAt(0))), Array.from(t, (h) => o.setUint8(c++, h.charCodeAt(0))), Array.from(r, (h) => o.setUint8(c++, h.charCodeAt(0))), Array.from(i, (h) => o.setUint8(c++, h.charCodeAt(0))); 34344 var u = new Uint8Array(l.byteLength + s.byteLength); 34345 return u.set(new Uint8Array(l), 0), u.set(new Uint8Array(s), l.byteLength), u.buffer; 34346 }, 34347 /** 34348 * @private 34349 */ 34350 binaryDecode(n) { 34351 let e = new DataView(n), t = e.getUint8(0), i = new TextDecoder(); 34352 switch (t) { 34353 case this.KINDS.push: 34354 return this.decodePush(n, e, i); 34355 case this.KINDS.reply: 34356 return this.decodeReply(n, e, i); 34357 case this.KINDS.broadcast: 34358 return this.decodeBroadcast(n, e, i); 34359 } 34360 }, 34361 /** @private */ 34362 decodePush(n, e, t) { 34363 let i = e.getUint8(1), r = e.getUint8(2), s = e.getUint8(3), a = this.HEADER_LENGTH + this.META_LENGTH - 1, l = t.decode(n.slice(a, a + i)); 34364 a = a + i; 34365 let o = t.decode(n.slice(a, a + r)); 34366 a = a + r;
34367 let c = t.decode(n.slice(a, a + s)); 34368 a = a + s; 34369 let u = n.slice(a, n.byteLength); 34370 return { join_ref: l, ref: null, topic: o, event: c, payload: u }; 34371 }, 34372 /** @private */ 34373 decodeReply(n, e, t) { 34374 let i = e.getUint8(1), r = e.getUint8(2), s = e.getUint8(3), a = e.getUint8(4), l = this.HEADER_LENGTH + this.META_LENGTH, o = t.decode(n.slice(l, l + i)); 34375 l = l + i; 34376 let c = t.decode(n.slice(l, l + r)); 34377 l = l + r; 34378 let u = t.decode(n.slice(l, l + s)); 34379 l = l + s; 34380 let h = t.decode(n.slice(l, l + a)); 34381 l = l + a; 34382 let d = n.slice(l, n.byteLength), f = { status: h, response: d }; 34383 return { join_ref: o, ref: c, topic: u, event: Pi.reply, payload: f }; 34384 }, 34385 /** @private */ 34386 decodeBroadcast(n, e, t) { 34387 let i = e.getUint8(1), r = e.getUint8(2), s = this.HEADER_LENGTH + 2, a = t.decode(n.slice(s, s + i)); 34388 s = s + i; 34389 let l = t.decode(n.slice(s, s + r)); 34390 s = s + r; 34391 let o = n.slice(s, n.byteLength); 34392 return { join_ref: null, ref: null, topic: a, event: l, payload: o }; 34393 } 34394}, jM = class { 34395 /** Initializes the Socket * 34396 * 34397 * For IE8 support use an ES5-shim (https://github.com/es-shims/es5-shim) 34398 * 34399 * @constructor 34400 * @param {string} endPoint - The string WebSocket endpoint, ie, `"ws://example.com/socket"`, 34401 * `"wss://example.com"` 34402 * `"/socket"` (inherited host & protocol) 34403 * @param {SocketOptions} [opts] - Optional configuration 34404 */ 34405 constructor(n, e = {}) { 34406 this.stateChangeCallbacks = { open: [], close: [], error: [], message: [] }, this.channels = [], this.sendBuffer = [], this.ref = 0, this.fallbackRef = null, this.timeout = e.timeout || zM, this.transport = e.transport || oi.WebSocket || Zr, this.conn = void 0, this.primaryPassedHealthCheck = !1, this.longPollFallbackMs = e.longPollFallbackMs, this.fallbackTimer = null; 34407 let t = null; 34408 try { 34409 t = oi && oi.sessionStorage; 34410 } catch { 34411 } 34412 this.sessionStore = e.sessionStorage || t, this.establishedConnections = 0, this.defaultEncoder = so.encode.bind(so), this.defaultDecoder = so.decode.bind(so), this.closeWasClean = !0, this.disconnecting = !1, this.binaryType = e.binaryType || "arraybuffer", this.connectClock = 1, this.pageHidden = !1, this.encode = void 0, this.decode = void 0, this.transport !== Zr ? (this.encode = e.encode || this.defaultEncoder, this.decode = e.decode || this.defaultDecoder) : (this.encode = this.defaultEncoder, this.decode = this.defaultDecoder); 34413 let i = null; 34414 ss && ss.addEventListener && (ss.addEventListener("pagehide", (r) => { 34415 this.conn && (this.disconnect(), i = this.connectClock); 34416 }), ss.addEventListener("pageshow", (r) => { 34417 i === this.connectClock && (i = null, this.connect()); 34418 }), ss.addEventListener("visibilitychange", () => { 34419 document.visibilityState === "hidden" ? this.pageHidden = !0 : (this.pageHidden = !1, !this.isConnected() && !this.closeWasClean && this.teardown(() => this.connect())); 34420 })), this.heartbeatIntervalMs = e.heartbeatIntervalMs || 3e4, this.autoSendHeartbeat = e.autoSendHeartbeat ?? !0, this.heartbeatCallback = e.heartbeatCallback ?? (() => { 34421 }), this.rejoinAfterMs = (r) => e.rejoinAfterMs ? e.rejoinAfterMs(r) : [1e3, 2e3, 5e3][r - 1] || 1e4, this.reconnectAfterMs = (r) => e.reconnectAfterMs ? e.reconnectAfterMs(r) : [10, 50, 100, 150, 200, 250, 500, 1e3, 2e3][r - 1] || 5e3, this.logger = e.logger || null, !this.logger && e.debug && (this.logger = (r, s, a) => { 34422 console.log(`${r}: ${s}`, a); 34423 }), this.longpollerTimeout = e.longpollerTimeout || 2e4, this.params = Qs(e.params || {}), this.endPoint = `${n}/${cu.websocket}`, this.vsn = e.vsn || BM, this.heartbeatTimeoutTimer = null, this.heartbeatTimer = null, this.heartbeatSentAt = null, this.pendingHeartbeatRef = null, this.reconnectTimer = new Tm(() => { 34424 if (this.pageHidden) { 34425 this.log("Not reconnecting as page is hidden!"), this.teardown(); 34426 return; 34427 } 34428 this.teardown(async () => { 34429 e.beforeReconnect && await e.beforeReconnect(), this.connect(); 34430 }); 34431 }, this.reconnectAfterMs), this.authToken = e.authToken; 34432 } 34433 /** 34434 * Returns the LongPoll transport reference 34435 */
34436 getLongPollTransport() { 34437 return Zr; 34438 } 34439 /** 34440 * Disconnects and replaces the active transport 34441 * 34442 * @param {SocketTransport} newTransport - The new transport class to instantiate 34443 * 34444 */ 34445 replaceTransport(n) { 34446 this.connectClock++, this.closeWasClean = !0, clearTimeout(this.fallbackTimer), this.reconnectTimer.reset(), this.conn && (this.conn.close(), this.conn = null), this.transport = n; 34447 } 34448 /** 34449 * Returns the socket protocol 34450 * 34451 * @returns {"wss" | "ws"} 34452 */ 34453 protocol() { 34454 return location.protocol.match(/^https/) ? "wss" : "ws"; 34455 } 34456 /** 34457 * The fully qualified socket url 34458 * 34459 * @returns {string} 34460 */ 34461 endPointURL() { 34462 let n = Do.appendParams( 34463 Do.appendParams(this.endPoint, this.params()), 34464 { vsn: this.vsn } 34465 ); 34466 return n.charAt(0) !== "/" ? n : n.charAt(1) === "/" ? `${this.protocol()}:${n}` : `${this.protocol()}://${location.host}${n}`; 34467 } 34468 /** 34469 * Disconnects the socket 34470 * 34471 * See https://developer.mozilla.org/en-US/docs/Web/API/CloseEvent#Status_codes for valid status codes. 34472 * 34473 * @param {() => void} [callback] - Optional callback which is called after socket is disconnected. 34474 * @param {number} [code] - A status code for disconnection (Optional). 34475 * @param {string} [reason] - A textual description of the reason to disconnect. (Optional) 34476 */ 34477 disconnect(n, e, t) { 34478 this.connectClock++, this.disconnecting = !0, this.closeWasClean = !0, clearTimeout(this.fallbackTimer), this.reconnectTimer.reset(), this.teardown(() => { 34479 this.disconnecting = !1, n && n(); 34480 }, e, t); 34481 } 34482 /** 34483 * @param {Params} [params] - [DEPRECATED] The params to send when connecting, for example `{user_id: userToken}` 34484 * 34485 * Passing params to connect is deprecated; pass them in the Socket constructor instead: 34486 * `new Socket("/socket", {params: {user_id: userToken}})`. 34487 */ 34488 connect(n) { 34489 n && (console && console.log("passing params to connect is deprecated. Instead pass :params to the Socket constructor"), this.params = Qs(n)), !(this.conn && !this.disconnecting) && (this.longPollFallbackMs && this.transport !== Zr ? this.connectWithF
34489allback(Zr, this.longPollFallbackMs) : this.transportConnect()); 34490 } 34491 /** 34492 * Logs the message. Override `this.logger` for specialized logging. noops by default 34493 * @param {string} kind 34494 * @param {string} msg 34495 * @param {Object} data 34496 */ 34497 log(n, e, t) { 34498 this.logger && this.logger(n, e, t); 34499 } 34500 /** 34501 * Returns true if a logger has been set on this socket. 34502 */ 34503 hasLogger() { 34504 return this.logger !== null; 34505 } 34506 /** 34507 * Registers callbacks for connection open events 34508 * 34509 * @example socket.onOpen(function(){ console.info("the socket was opened") }) 34510 * 34511 * @param {SocketOnOpen} callback 34512 */ 34513 onOpen(n) { 34514 let e = this.makeRef(); 34515 return this.stateChangeCallbacks.open.push([e, n]), e; 34516 } 34517 /** 34518 * Registers callbacks for connection close events 34519 * @param {SocketOnClose} callback 34520 * @returns {string} 34521 */ 34522 onClose(n) { 34523 let e = this.makeRef(); 34524 return this.stateChangeCallbacks.close.push([e, n]), e; 34525 } 34526 /** 34527 * Registers callbacks for connection error events 34528 * 34529 * @example socket.onError(function(error){ alert("An error occurred") }) 34530 * 34531 * @param {SocketOnError} callback 34532 * @returns {string} 34533 */ 34534 onError(n) { 34535 let e = this.makeRef(); 34536 return this.stateChangeCallbacks.error.push([e, n]), e; 34537 } 34538 /** 34539 * Registers callbacks for connection message events 34540 * @param {SocketOnMessage} callback 34541 * @returns {string} 34542 */ 34543 onMessage(n) { 34544 let e = this.makeRef(); 34545 return this.stateChangeCallbacks.message.push([e, n]), e; 34546 } 34547 /** 34548 * Sets a callback that receives lifecycle events for internal heartbeat messages. 34549 * Useful for instrumenting connection health (e.g. sent/ok/timeout/disconnected). 34550 * @param {HeartbeatCallback} callback 34551 */ 34552 onHeartbeat(n) { 34553 this.heartbeatCallback = n; 34554 } 34555 /** 34556 * Pings the server and invokes the callback with the RTT in milliseconds 34557 * @param {(timeDelta: number) => void} callback 34558 * 34559 * Returns true if the ping was pushed or false if unable to be pushed. 34560 */ 34561 ping(n) { 34562 if (!this.isConnected()) 34563 return !1; 34564 let e = this.makeRef(), t = Date.now(); 34565 this.push({ topic: "phoenix", event: "heartbeat", payload: {}, ref: e }); 34566 let i = this.onMessage((r) => { 34567 r.ref === e && (this.off([i]), n(Date.now() - t)); 34568 }); 34569 return !0; 34570 } 34571 /** 34572 * @private 34573 * 34574 * @param {Function} 34575 */ 34576 transportName(n) { 34577 switch (n) { 34578 case Zr: 34579 return "LongPoll"; 34580 default: 34581 return n.name; 34582 } 34583 } 34584 /** 34585 * @private 34586 */ 34587 transportConnect() { 34588 this.connectClock++, this.closeWasClean = !1; 34589 let n; 34590 this.authToken && (n = ["phoenix", `${uu}${btoa(this.authToken).replace(/=/g, "")}`]), this.conn = new this.transport(this.endPointURL(), n), this.conn.binaryType = this.binaryType, this.conn.timeout = this.longpollerTimeout, this.conn.onopen = () => this.onConnOpen(), this.conn.onerror = (e) => this.onConnError(e), this.conn.onmessage = (e) => this.onConnMessage(e), this.conn.onclose = (e) => this.onConnClose(e); 34591 } 34592 getSession(n) { 34593 return this.sessionStore && this.sessionStore.getItem(n); 34594 } 34595 storeSession(n, e) { 34596 this.sessionStore && this.sessionStore.setItem(n, e); 34597 }
34598 connectWithFallback(n, e = 2500) { 34599 clearTimeout(this.fallbackTimer); 34600 let t = !1, i = !0, r, s, a = this.transportName(n), l = (o) => { 34601 this.log("transport", `falling back to ${a}...`, o), this.off([r, s]), i = !1, this.replaceTransport(n), this.transportConnect(); 34602 }; 34603 if (this.getSession(`phx:fallback:${a}`)) 34604 return l("memorized"); 34605 this.fallbackTimer = setTimeout(l, e), s = this.onError((o) => { 34606 this.log("transport", "error", o), i && !t && (clearTimeout(this.fallbackTimer), l(o)); 34607 }), this.fallbackRef && this.off([this.fallbackRef]), this.fallbackRef = this.onOpen(() => { 34608 if (t = !0, !i) { 34609 let o = this.transportName(n); 34610 return this.primaryPassedHealthCheck || this.storeSession(`phx:fallback:${o}`, "true"), this.log("transport", `established ${o} fallback`); 34611 } 34612 clearTimeout(this.fallbackTimer), this.fallbackTimer = setTimeout(l, e), this.ping((o) => { 34613 this.log("transport", "connected to primary after", o), this.primaryPassedHealthCheck = !0, clearTimeout(this.fallbackTimer); 34614 }); 34615 }), this.transportConnect(); 34616 } 34617 clearHeartbeats() { 34618 clearTimeout(this.heartbeatTimer), clearTimeout(this.heartbeatTimeoutTimer); 34619 } 34620 onConnOpen() { 34621 this.hasLogger() && this.log("transport", `connected to ${this.endPointURL()}`), this.closeWasClean = !1, this.disconnecting = !1, this.establishedConnections++, this.flushSendBuffer(), this.reconnectTimer.reset(), this.autoSendHeartbeat && this.resetHeartbeat(), this.triggerStateCallbacks("open"); 34622 } 34623 /** 34624 * @private 34625 */ 34626 heartbeatTimeout() { 34627 if (this.pendingHeartbeatRef) { 34628 this.pendingHeartbeatRef = null, this.heartbeatSentAt = null, this.hasLogger() && this.log("transport", "heartbeat timeout. Attempting to re-establish connection");
34629 try { 34630 this.heartbeatCallback("timeout"); 34631 } catch (n) { 34632 this.log("error", "error in heartbeat callback", n); 34633 } 34634 this.triggerChanError(new Error("heartbeat timeout")), this.closeWasClean = !1, this.teardown(() => this.reconnectTimer.scheduleTimeout(), HM, "heartbeat timeout"); 34635 } 34636 } 34637 resetHeartbeat() { 34638 this.conn && this.conn.skipHeartbeat || (this.pendingHeartbeatRef = null, this.clearHeartbeats(), this.heartbeatTimer = setTimeout(() => this.sendHeartbeat(), this.heartbeatIntervalMs)); 34639 } 34640 teardown(n, e, t) { 34641 if (!this.conn) 34642 return n && n(); 34643 const i = this.conn; 34644 this.waitForBufferDone(i, () => { 34645 e ? i.close(e, t || "") : i.close(), this.waitForSocketClosed(i, () => { 34646 this.conn === i && (this.conn.onopen = function() { 34647 }, this.conn.onerror = function() { 34648 }, this.conn.onmessage = function() { 34649 }, this.conn.onclose = function() { 34650 }, this.conn = null), n && n(); 34651 }); 34652 }); 34653 } 34654 waitForBufferDone(n, e, t = 1) { 34655 if (t === 5 || !n.bufferedAmount) { 34656 e(); 34657 return; 34658 } 34659 setTimeout(() => { 34660 this.waitForBufferDone(n, e, t + 1); 34661 }, 150 * t); 34662 } 34663 waitForSocketClosed(n, e, t = 1) { 34664 if (t === 5 || n.readyState === ci.closed) { 34665 e(); 34666 return; 34667 } 34668 setTimeout(() => { 34669 this.waitForSocketClosed(n, e, t + 1); 34670 }, 150 * t); 34671 } 34672 /** 34673 * @param {CloseEvent} event 34674 */ 34675 onConnClose(n) { 34676 this.conn && (this.conn.onclose = () => { 34677 }), this.hasLogger() && this.log("transport", "close", n), this.triggerChanError(n), this.clearHeartbeats(), this.closeWasClean || this.reconnectTimer.scheduleTimeout(), this.triggerStateCallbacks("close", n); 34678 } 34679 /** 34680 * @private 34681 * @param {Event} error 34682 */ 34683 onConnError(n) { 34684 this.hasLogger() && this.log("transport", "error", n); 34685 let e = this.transport, t = this.establishedConnections; 34686 this.triggerStateCallbacks("error", n, e, t), (e === this.transport || t > 0) && this.triggerChanError(n); 34687 } 34688 /** 34689 * @private 34690 * @param {unknown} [reason] underlying close/error event forwarded to channel error listeners 34691 */ 34692 triggerChanError(n) { 34693 this.channels.forEach((e) => { 34694 e.isErrored() || e.isLeaving() || e.isClosed() || e.trigger(Pi.error, n); 34695 }); 34696 } 34697 /** 34698 * @returns {string} 34699 */ 34700 connectionState() { 34701 switch (this.conn && this.conn.readyState) { 34702 case ci.connecting: 34703 return "connecting"; 34704 case ci.open: 34705 return "open"; 34706 case ci.closing: 34707 return "closing"; 34708 default: 34709 return "closed"; 34710 } 34711 } 34712 /** 34713 * @returns {boolean} 34714 */ 34715 isConnected() { 34716 return this.connectionState() === "open"; 34717 } 34718 /** 34719 * 34720 * @param {Channel} channel 34721 */ 34722 remove(n) { 34723 this.off(n.stateChangeRefs), this.channels = this.channels.filter((e) => e !== n); 34724 } 34725 /** 34726 * Removes `onOpen`, `onClose`, `onError,` and `onMessage` registrations. 34727 * 34728 * @param {string[]} refs - list of refs returned by calls to 34729 * `onOpen`, `onClose`, `onError,` and `onMessage` 34730 */ 34731 off(n) { 34732 for (let e in this.stateChangeCallbacks)
34733 this.stateChangeCallbacks[e] = this.stateChangeCallbacks[e].filter(([t]) => n.indexOf(t) === -1); 34734 } 34735 /** 34736 * Initiates a new channel for the given topic 34737 * 34738 * @param {string} topic 34739 * @param {Params | (() => Params)} [chanParams]- Parameters for the channel 34740 * @returns {Channel} 34741 */ 34742 channel(n, e = {}) { 34743 let t = new VM(n, e, this); 34744 return this.channels.push(t), t; 34745 } 34746 /** 34747 * @param {Message<Record<string, any>>} data 34748 */ 34749 push(n) { 34750 if (this.hasLogger()) { 34751 let { topic: e, event: t, payload: i, ref: r, join_ref: s } = n; 34752 this.log("push", `${e} ${t} (${s}, ${r})`, i); 34753 } 34754 this.isConnected() ? this.encode(n, (e) => this.conn.send(e)) : this.sendBuffer.push(() => this.encode(n, (e) => this.conn.send(e))); 34755 } 34756 /** 34757 * Return the next message ref, accounting for overflows 34758 * @returns {string} 34759 */ 34760 makeRef() { 34761 let n = this.ref + 1; 34762 return n === this.ref ? this.ref = 0 : this.ref = n, this.ref.toString(); 34763 } 34764 sendHeartbeat() { 34765 if (!this.isConnected()) { 34766 try { 34767 this.heartbeatCallback("disconnected"); 34768 } catch (n) { 34769 this.log("error", "error in heartbeat callback", n); 34770 } 34771 return; 34772 } 34773 if (this.pendingHeartbeatRef) { 34774 this.heartbeatTimeout(); 34775 return; 34776 } 34777 this.pendingHeartbeatRef = this.makeRef(), this.heartbeatSentAt = Date.now(), this.push({ topic: "phoenix", event: "heartbeat", payload: {}, ref: this.pendingHeartbeatRef }); 34778 try { 34779 this.heartbeatCallback("sent"); 34780 } catch (n) { 34781 this.log("error", "error in heartbeat callback", n); 34782 } 34783 this.heartbeatTimeoutTimer = setTimeout(() => this.heartbeatTimeout(), this.heartbeatIntervalMs); 34784 } 34785 flushSendBuffer() { 34786 this.isConnected() && this.sendBuffer.length > 0 && (this.sendBuffer.forEach((n) => n()), this.sendBuffer = []); 34787 } 34788 /** 34789 * @param {MessageEvent<any>} rawMessage 34790 */ 34791 onConnMessage(n) { 34792 this.decode(n.data, (e) => { 34793 let { topic: t, event: i, payload: r, ref: s, join_ref: a } = e; 34794 if (s && s === this.pendingHeartbeatRef) { 34795 const l = this.heartbeatSentAt ? Date.now() - this.heartbeatSentAt : void 0; 34796 this.clearHeartbeats(); 34797 try { 34798 this.heartbeatCallback(r.status === "ok" ? "ok" : "error", l); 34799 } catch (o) { 34800 this.log("error", "error in heartbeat callback", o); 34801 } 34802 this.pendingHeartbeatRef = null, this.heartbeatSentAt = null, this.autoSendHeartbeat && (this.heartbeatTimer = setTimeout(() => this.sendHeartbeat(), this.heartbeatIntervalMs)); 34803 } 34804 this.hasLogger() && this.log("receive", `${r.status || ""} ${t} ${i} ${s && "(" + s + ")" || ""}`.trim(), r); 34805 for (let l = 0; l < this.channels.length; l++) { 34806 const o = this.channels[l]; 34807 o.isMember(t, i, r, a) && o.trigger(i, r, s, a); 34808 } 34809 this.triggerStateCallbacks("message", e); 34810 }); 34811 } 34812 /** 34813 * @private 34814 * @template {keyof SocketStateChangeCallbacks} K 34815 * @param {K} event 34816 * @param {...Parameters<SocketStateChangeCallbacks[K][number][1]>} args 34817 * @returns {void} 34818 */ 34819 triggerStateCallbacks(n, ...e) { 34820 try { 34821 this.stateChangeCallbacks[n].forEach(([t, i]) => { 34822 try { 34823 i(...e); 34824 } catch (r) { 34825 this.log("error", `error in ${n} callback`, r); 34826 } 34827 }); 34828 } catch (t) { 34829 this.log("error", `error triggering ${n} callbacks`, t); 34830 } 34831 } 34832 leaveOpenTopic(n) { 34833 let e = this.channels.find((t) => t.topic === n && (t.isJoined() || t.isJoining())); 34834 e && (this.hasLogger() && this.log("transport", `leaving duplicate topic "${n}"`), e.leave()); 34835 } 34836}; 34837class ea { 34838 constructor(e, t) { 34839 const i = qM(t); 34840 this.presence = new $M(e.getChannel(), i), this.presence.onJoin((r, s, a) => { 34841 const l = ea.onJoinPayload(r, s, a); 34842 e.getChannel().trigger("presence", l); 34843 }), this.presence.onLeave((r, s, a) => { 34844 const l = ea.onLeavePayload(r, s, a); 34845 e.getChannel().trigger("presence", l); 34846 }), this.presence.onSync(() => { 34847 e.getChannel().trigger("presence", { event: "sync" }); 34848 }); 34849 } 34850 get state() { 34851 return ea.transformState(this.presence.state); 34852 } 34853 /** 34854 * @private 34855 * Remove 'metas' key 34856 * Change 'phx_ref' to 'presence_ref' 34857 * Remove 'phx_ref' and 'phx_ref_prev' 34858 * 34859 * @example Transform state 34860 * // returns { 34861 * abc123: [ 34862 * { presence_ref: '2', user_id: 1 }, 34863 * { presence_ref: '3', user_id: 2 } 34864 * ] 34865 * } 34866 * RealtimePresence.transformState({ 34867 * abc123: { 34868 * metas: [ 34869 * { phx_ref: '2', phx_ref_prev: '1' user_id: 1 }, 34870 * { phx_ref: '3', user_id: 2 } 34871 * ] 34872 * } 34873 * }) 34874 * 34875 */ 34876 static transformState(e) { 34877 return e = XM(e), Object.getOwnPropertyNames(e).reduce((t, i) => { 34878 const r = e[i]; 34879 return t[i] = Eo(r), t; 34880 }, {}); 34881 } 34882 static onJoinPayload(e, t, i) { 34883 const r = af(t), s = Eo(i); 34884 return { 34885 event: "join", 34886 key: e, 34887 currentPresences: r, 34888 newPresences: s 34889 }; 34890 } 34891 static onLeavePayload(e, t, i) { 34892 const r = af(t), s = Eo(i); 34893 return { 34894 event: "leave", 34895 key: e, 34896 currentPresences: r, 34897 leftPresences: s 34898 }; 34899 } 34900} 34901function Eo(n) { 34902 return n.metas.map((e) => (e.presence_ref = e.phx_ref, delete e.phx_ref, delete e.phx_ref_prev, e)); 34903} 34904function XM(n) { 34905 return JSON.parse(JSON.stringify(n)); 34906} 34907function qM(n) { 34908 return n?.events && { events: n.events }; 34909} 34910function af(n) { 34911 return n?.metas ? Eo(n) : []; 34912} 34913var of; 34914(function(n) { 34915 n.SYNC = "sync", n.JOIN = "join", n.LEAVE = "leave"; 34916})(of || (of = {})); 34917class YM { 34918 get state() { 34919 return this.presenceAdapter.state; 34920 } 34921 /** 34922 * Creates a Presence helper that keeps the local presence state in sync with the server. 34923 * 34924 * @param channel - The realtime channel to bind to. 34925 * @param opts - Optional custom event names, e.g. `{ events: { state: 'state', diff: 'diff' } }`. 34926 * 34927 * @category Realtime 34928 * 34929 * @example Example for a presence channel 34930 * ```ts 34931 * const presence = new RealtimePresence(channel) 34932 * 34933 * channel.on('presence', ({ event, key }) => { 34934 * console.log(`Presence ${event} on ${key}`) 34935 * }) 34936 * ``` 34937 */ 34938 constructor(e, t) { 34939 this.channel = e, this.presenceAdapter = new ea(this.channel.channelAdapter, t); 34940 } 34941} 34942function KM(n) { 34943 if (n instanceof Error) 34944 return n; 34945 if (typeof n == "string") 34946 return new Error(n); 34947 if (n && typeof n == "object") { 34948 const e = n; 34949 if (typeof e.code == "number") { 34950 const t = typeof e.reason == "string" && e.reason ? ` (${e.reason})` : ""; 34951 return new Error(`socket closed: ${e.code}${t}`, { cause: n }); 34952 } 34953 return new Error("channel error: transport failure", { cause: n }); 34954 } 34955 return new Error("channel error: connection lost"); 34956} 34957class JM { 34958 constructor(e, t, i) { 34959 const r = ZM(i); 34960 this.channel = e.getSocket().channel(t, r), this.socket = e; 34961 } 34962 get state() { 34963 return this.channel.state; 34964 } 34965 set state(e) { 34966 this.channel.state = e; 34967 } 34968 get joinedOnce() { 34969 return this.channel.joinedOnce; 34970 } 34971 get joinPush() { 34972 return this.channel.joinPush; 34973 } 34974 get rejoinTimer() { 34975 return this.channel.rejoinTimer; 34976 } 34977 on(e, t) { 34978 return this.channel.on(e, t); 34979 } 34980 off(e, t) { 34981 this.channel.off(e, t); 34982 } 34983 subscribe(e) { 34984 return this.channel.join(e); 34985 } 34986 unsubscribe(e) { 34987 return this.channel.leave(e); 34988 } 34989 teardown() { 34990 this.channel.teardown(); 34991 } 34992 onClose(e) { 34993 this.channel.onClose(e); 34994 } 34995 onError(e) { 34996 return this.channel.onError(e); 34997 } 34998 push(e, t, i) { 34999 let r; 35000 try { 35001 r = this.channel.push(e, t, i); 35002 } catch { 35003 throw new Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`); 35004 } 35005 if (this.channel.pushBuffer.length > PM) { 35006 const s = this.channel.pushBuffer.shift(); 35007 s.cancelTimeout(), this.socket.log("channel", `discarded push due to buffer overflow: ${s.event}`, s.payload()); 35008 } 35009 return r; 35010 } 35011 updateJoinPayload(e) { 35012 const t = this.channel.joinPush.payload(); 35013 this.channel.joinPush.payload = () => Object.assign(Object.assign({}, t), e); 35014 } 35015 canPush() { 35016 return this.socket.isConnected() && this.state === Zi.joined; 35017 } 35018 isJoined() { 35019 return this.state === Zi.joined; 35020 } 35021 isJoining() { 35022 return this.state === Zi.joining; 35023 } 35024 isClosed() { 35025 return this.state === Zi.closed; 35026 } 35027 isLeaving() {
35028 return this.state === Zi.leaving; 35029 } 35030 updateFilterBindings(e) { 35031 this.channel.filterBindings = e; 35032 } 35033 updatePayloadTransform(e) { 35034 this.channel.onMessage = e; 35035 } 35036 /** 35037 * @internal 35038 */ 35039 getChannel() { 35040 return this.channel; 35041 } 35042} 35043function ZM(n) { 35044 return { 35045 config: Object.assign({ 35046 broadcast: { ack: !1, self: !1 }, 35047 presence: { key: "", enabled: !1 }, 35048 private: !1 35049 }, n.config) 35050 }; 35051} 35052var lf; 35053(function(n) { 35054 n.ALL = "*", n.INSERT = "INSERT", n.UPDATE = "UPDATE", n.DELETE = "DELETE"; 35055})(lf || (lf = {})); 35056var cs; 35057(function(n) { 35058 n.BROADCAST = "broadcast", n.PRESENCE = "presence", n.POSTGRES_CHANGES = "postgres_changes", n.SYSTEM = "system"; 35059})(cs || (cs = {})); 35060var Li; 35061(function(n) { 35062 n.SUBSCRIBED = "SUBSCRIBED", n.TIMED_OUT = "TIMED_OUT", n.CLOSED = "CLOSED", n.CHANNEL_ERROR = "CHANNEL_ERROR"; 35063})(Li || (Li = {})); 35064class ta { 35065 get state() { 35066 return this.channelAdapter.state; 35067 } 35068 set state(e) { 35069 this.channelAdapter.state = e; 35070 } 35071 get joinedOnce() { 35072 return this.channelAdapter.joinedOnce; 35073 } 35074 get timeout() { 35075 return this.socket.timeout; 35076 } 35077 get joinPush() { 35078 return this.channelAdapter.joinPush; 35079 } 35080 get rejoinTimer() { 35081 return this.channelAdapter.rejoinTimer; 35082 } 35083 /** 35084 * Creates a channel that can broadcast messages, sync presence, and listen to Postgres changes. 35085 * 35086 * The topic determines which realtime stream you are subscribing to. Config options let you 35087 * enable acknowledgement for broadcasts, presence tracking, or private channels. 35088 * 35089 * @category Realtime 35090 * 35091 * @example Using supabase-js (recommended) 35092 * ```ts 35093 * import { createClient } from '@supabase/supabase-js' 35094 * 35095 * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key') 35096 * const channel = supabase.channel('room1') 35097 * channel 35098 * .on('broadcast', { event: 'cursor-pos' }, (payload) => console.log(payload)) 35099 * .subscribe() 35100 * ``` 35101 * 35102 * @example Standalone import for bundle-sensitive environments 35103 * ```ts 35104 * import RealtimeClient from '@supabase/realtime-js' 35105 * 35106 * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', { 35107 * params: { apikey: 'your-publishable-key' }, 35108 * }) 35109 * const channel = new RealtimeChannel('realtime:public:messages', { config: {} }, client) 35110 * ``` 35111 */ 35112 constructor(e, t = { config: {} }, i) { 35113 var r, s; 35114 if (this.topic = e, this.params = t, this.socket = i, this.bindings = {}, this.subTopic = e.replace(/^realtime:/i, ""), this.params.config = Object.assign({ 35115 broadcast: { ack: !1, self: !1 }, 35116 presence: { key: "", enabled: !1 }, 35117 private: !1 35118 }, t.config), this.channelAdapter = new JM(this.socket.socketAdapter, e, this.params), this.presence = new YM(this), this._onClose(() => { 35119 this.socket._remove(this); 35120 }), this._updateFilterTransform(), this.broadcastEndpointURL = Mm(this.socket.socketAdapter.endPointURL()), this.private = this.params.config.private || !1, !this.private && (!((s = (r = this.params.config) === null || r === void 0 ? void 0 : r.broadcast) === null || s === void 0) && s.replay)) 35121 throw new Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`); 35122 } 35123 /** 35124 * Subscribe registers your client with the server. 35125 * 35126 * The optional `callback` receives a `status` and, on failure, an `err` argument. 35127 * Log the full `err` so its `cause`, `name`, and any structured fields aren't hidden 35128 * behind `err.message`. 35129 * 35130 * @category Realtime 35131 * 35132 * @example Handling errors 35133 * ```js 35134 * supabase.channel('room1').subscribe((status, err) => { 35135 * if (status === 'CHANNEL_ERROR' || status === 'TIMED_OUT') { 35136 * // Log the full error: its `cause` often holds the underlying reason. 35137 * console.error(status, err) 35138 * } 35139 * }) 35140 * ``` 35141 */ 35142 subscribe(e, t = this.timeout) { 35143 var i, r, s; 35144 if (this.socket.isConnected() || this.socket.connect(), this.channelAdapter.isClosed()) { 35145 const { config: { broadcast: a, presence: l, private: o } } = this.params, c = (r = (i = this.bindings.postgres_changes) === null || i === void 0 ? void 0 : i.map((f) => f.filter)) !== null && r !== void 0 ? r : [], u = !!this.bindings[cs.PRESENCE] && this.bindings[cs.PRESENCE].length > 0 || ((s = this.params.config.presence) === null || s === void 0 ? void 0 : s.enabled) === !0, h = {}, d = { 35146 broadcast: a, 35147 presence: Object.assign(Object.assign({}, l), { enabled: u }), 35148 postgres_changes: c, 35149 private: o 35150 }; 35151 this.socket.accessTokenValue && (h.access_token = this.socket.accessTokenValue), this._onError((f) => { 35152 e?.(Li.CHANNEL_ERROR, KM(f)); 35153 }), this._onClose(() => e?.(Li.CLOSED)), this.updateJoinPayload(Object.assign({ config: d }, h)), this._updateFilterMessage(), this.channelAdapter.subscribe(t).receive("ok", async ({ postgres_changes: f }) => { 35154 if (this.socket._isManualToken() || this.socket.setAuth(), f === void 0) { 35155 e?.(Li.SUBSCRIBED); 35156 return; 35157 } 35158 this._updatePostgresBindings(f, e); 35159 }).receive("error", (f) => { 35160 this.state = Zi.errored; 35161 const p = Object.values(f).join(", ") || "error"; 35162 e?.(Li.CHANNEL_ERROR, new Error(p, { cause: f })); 35163 }).receive("timeout", () => { 35164 e?.(Li.TIMED_OUT); 35165 }); 35166 } 35167 return this; 35168 } 35169 _updatePostgresBindings(e, t) { 35170 var i; 35171 const r = this.bindings.postgres_changes, s = (i = r?.length) !== null && i !== void 0 ? i : 0, a = []; 35172 for (let l = 0; l < s; l++) { 35173 const o = r[l], { filter: { event: c, schema: u, table: h, filter: d } } = o, f = e && e[l]; 35174 if (f && f.event === c && ta.isFilterValueEqual(f.schema, u) && ta.isFilterValueEqual(f.table, h) && ta.isFilterValueEqual(f.filter, d)) 35175 a.push(Object.assign(Object.assign({}, o), { id: f.id })); 35176 else { 35177 this.unsubscribe(), this.state = Zi.errored, t?.(Li.CHANNEL_ERROR, new Error("mismatch between server and client bindings for postgres changes")); 35178 return; 35179 } 35180 } 35181 this.bindings.postgres_changes = a, this.state != Zi.errored && t && t(Li.SUBSCRIBED); 35182 } 35183 /** 35184 * Returns the current presence state for this channel. 35185 * 35186 * The shape is a map keyed by presence key (for example a user id) where each entry contains the 35187 * tracked metadata for that user. 35188 * 35189 * @category Realtime 35190 */ 35191 presenceState() { 35192 return this.presence.state; 35193 } 35194 /** 35195 * Sends the supplied payload to the presence tracker so other subscribers can see that this 35196 * client is online. Use `untrack` to stop broadcasting presence for the same key. 35197 * 35198 * @category Realtime 35199 */ 35200 async track(e, t = {}) { 35201 return await this.send({ 35202 type: "presence", 35203 event: "track", 35204 payload: e 35205 }, t.timeout || this.timeout); 35206 } 35207 /** 35208 * Removes the current presence state for this client. 35209 * 35210 * @category Realtime 35211 */ 35212 async untrack(e = {}) { 35213 return await this.send({ 35214 type: "presence", 35215 event: "untrack" 35216 }, e); 35217 } 35218 /** 35219 * Listen to realtime events on this channel. 35220 * @category Realtime 35221 * 35222 * @remarks 35223 * - By default, Broadcast and Presence are enabled for all projects. 35224 * - By default, listening to database changes is disabled for new projects due to database performance and security concerns. You can turn it on by managing Realtime's [replication](/docs/guides/api#realtime-api-overview). 35225 * - You can receive the "previous" data for updates and deletes by setting the table's `REPLICA IDENTITY` to `FULL` (e.g., `ALTER TABLE your_table REPLICA IDENTITY FULL;`). 35226 * - Row level security is not applied to delete statements. When RLS is enabled and replica identity is set to full, only the primary key is sent to clients. 35227 * 35228 * @example Listen to broadcast messages 35229 * ```js 35230 * const channel = supabase.channel("room1") 35231 * 35232 * channel.on("broadcast", { event: "cursor-pos" }, (payload) => { 35233 * console.log("Cursor position received!", payload); 35234 * }).subscribe((status) => { 35235 * if (status === "SUBSCRIBED") { 35236 * channel.send({ 35237 * type: "broadcast", 35238 * event: "cursor-pos", 35239 * payload: { x: Math.random(), y: Math.random() }, 35240 * }); 35241 * } 35242 * }); 35243 * ``` 35244 * 35245 * @example Listen to presence sync 35246 * ```js 35247 * const channel = supabase.channel('room1') 35248 * channel 35249 * .on('presence', { event: 'sync' }, () => { 35250 * console.log('Synced presence state: ', channel.presenceState()) 35251 * }) 35252 * .subscribe(async (status) => { 35253 * if (status === 'SUBSCRIBED') { 35254 * await channel.track({ online_at: new Date().toISOString() }) 35255 * } 35256 * }) 35257 * ``` 35258 * 35259 * @example Listen to presence join 35260 * ```js 35261 * const channel = supabase.channel('room1') 35262 * channel 35263 * .on('presence', { event: 'join' }, ({ newPresences }) => { 35264 * console.log('Newly joined presences: ', newPresences) 35265 * }) 35266 * .subscribe(async (status) => { 35267 * if (status === 'SUBSCRIBED') { 35268 * await channel.track({ online_at: new Date().toISOString() }) 35269 * } 35270 * }) 35271 * ``` 35272 * 35273 * @example Listen to presence leave 35274 * ```js 35275 * const channel = supabase.channel('room1') 35276 * channel 35277 * .on('presence', { event: 'leave' }, ({ leftPresences }) => { 35278 * console.log('Newly left presences: ', leftPresences) 35279 * }) 35280 * .subscribe(async (status) => { 35281 * if (status === 'SUBSCRIBED') { 35282 * await channel.track({ online_at: new Date().toISOString() }) 35283 * await channel.untrack() 35284 * } 35285 * }) 35286 * ``` 35287 * 35288 * @example Listen to all database changes 35289 * ```js 35290 * supabase 35291 * .channel('room1') 35292 * .on('postgres_changes', { event: '*', schema: '*' }, payload => { 35293 * console.log('Change received!', payload) 35294 * }) 35295 * .subscribe() 35296 * ``` 35297 * 35298 * @example Listen to a specific table 35299 * ```js 35300 * supabase 35301 * .channel('room1') 35302 * .on('postgres_changes', { event: '*', schema: 'public', table: 'countries' }, payload => { 35303 * console.log('Change received!', payload) 35304 * }) 35305 * .subscribe() 35306 * ``` 35307 * 35308 * @example Listen to inserts 35309 * ```js 35310 * supabase 35311 * .channel('room1') 35312 * .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'countries' }, payload => { 35313 * console.log('Change received!', payload) 35314 * }) 35315 * .subscribe() 35316 * ``` 35317 * 35318 * @exampleDescription Listen to updates 35319 * By default, Supabase will send only the updated record. If you want to re
35319ceive the previous values as well you can 35320 * enable full replication for the table you are listening to: 35321 * 35322 * ```sql 35323 * alter table "your_table" replica identity full; 35324 * ``` 35325 * 35326 * @example Listen to updates 35327 * ```js 35328 * supabase 35329 * .channel('room1') 35330 * .on('postgres_changes', { event: 'UPDATE', schema: 'public', table: 'countries' }, payload => { 35331 * console.log('Change received!', payload) 35332 * }) 35333 * .subscribe() 35334 * ``` 35335 * 35336 * @exampleDescription Listen to deletes 35337 * By default, Supabase does not send deleted records. If you want to receive the deleted record you can 35338 * enable full replication for the table you are listening to: 35339 * 35340 * ```sql 35341 * alter table "your_table" replica identity full; 35342 * ``` 35343 * 35344 * @example Listen to deletes 35345 * ```js 35346 * supabase 35347 * .channel('room1') 35348 * .on('postgres_changes', { event: 'DELETE', schema: 'public', table: 'countries' }, payload => { 35349 * console.log('Change received!', payload) 35350 * }) 35351 * .subscribe() 35352 * ``` 35353 * 35354 * @exampleDescription Listen to multiple events 35355 * You can chain listeners if you want to listen to multiple events for each table. 35356 * 35357 * @example Listen to multiple events 35358 * ```js 35359 * supabase 35360 * .channel('room1') 35361 * .on('postgres_changes', { event: 'INSERT', schema: 'public', table: 'countries' }, handleRecordInserted) 35362 * .on('postgres_changes', { event: 'DELETE', schema: 'public', table: 'countries' }, handleRecordDeleted) 35363 * .subscribe() 35364 * ``` 35365 * 35366 * @exampleDescription Listen to row level changes 35367 * You can listen to individual rows using the format `{table}:{col}=eq.{val}` - where `{col}` is the column name, and `{val}` is the value which you want to match. 35368 * 35369 * @example Listen to row level changes 35370 * ```js 35371 * supabase 35372 * .channel('room1') 35373 * .on('postgres_changes', { event: 'UPDATE', schema: 'public', table: 'countries', filter: 'id=eq.200' }, handleRecordUpdated) 35374 * .subscribe() 35375 * ``` 35376 */ 35377 on(e, t, i) { 35378 const r = this.channelAdapter.isJoined() || this.channelAdapter.isJoining(), s = e === cs.PRESENCE || e === cs.POSTGRES_CHANGES; 35379 if (r && s) 35380 throw this.socket.log("channel", `cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`), new Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`); 35381 return this._on(e, t, i); 35382 } 35383 /** 35384 * Sends a broadcast message explicitly via REST API. 35385 * 35386 * This method always uses the REST API endpoint regardless of WebSocket connection state. 35387 * Useful when you want to guarantee REST delivery or when gradually migrating from implicit REST fallback. 35388 * 35389 * Payloads that are `ArrayBuffer` or `ArrayBufferView` (e.g. `Uint8Array`) are sent as 35390 * `application/octet-stream`; all other payloads are JSON-encoded. 35391 * 35392 * @param event The name of the broadcast event 35393 * @param payload Payload to be sent (required) 35394 * @param opts Options including timeout 35395 * @returns Promise resolving to object with success status, and error details if failed 35396 * 35397 * @category Realtime 35398 */ 35399 async httpSend(e, t, i = {}) { 35400 var r; 35401 if (t == null) 35402 return Promise.reject(new Error("Payload is required for httpSend()")); 35403 const s = t instanceof ArrayBuffer || ArrayBuffer.isView(t), a = { 35404 apikey: this.socket.apiKey ? this.socket.apiKey : "", 35405 "Content-Type": s ? "application/octet-stream" : "application/json" 35406 }; 35407 this.socket.accessTokenValue && (a.Authorization = `Bearer ${this.socket.accessTokenValue}`); 35408 const l = new URL(this.broadcastEndpointURL); 35409 l.pathname += `/${encodeURIComponent(this.subTopic)}/events/${encodeURIComponent(e)}`, this.private && l.searchParams.set("private", "true"); 35410 const o = { 35411 method: "POST", 35412 headers: a, 35413 body: s ? t : JSON.stringify(t) 35414 }, c = await this._fetchWithTimeout(l.toString(), o, (r = i.timeout) !== null && r !== void 0 ? r : this.timeout); 35415 if (c.status === 202) 35416 return { success: !0 }; 35417 let u = c.statusText; 35418 try { 35419 const h = await c.json(); 35420 u = h.error || h.message || u; 35421 } catch { 35422 } 35423 return Promise.reject(new Error(u)); 35424 } 35425 /** 35426 * Sends a message into the channel. 35427 * 35428 * @param args Arguments to send to channel 35429 * @param args.type The type of event to send 35430 * @param args.event The name of the event being sent 35431 * @param args.payload Payload to be sent 35432 * @param opts Options to be used during the send process 35433 * 35434 * @category Realtime 35435 * 35436 * @remarks 35437 * - When using REST you don't need to subscribe to the channel 35438 * - REST calls are only available from 2.37.0 onwards 35439 * - If you create a channel only to send a REST broadcast, remove it from 35440 * the client when the send completes 35441 * 35442 * @example Send a message via websocket 35443 * ```js 35444 * const channel = supabase.channel('room1') 35445 * 35446 * channel.subscribe((status) => { 35447 * if (status === 'SUBSCRIBED') { 35448 * channel.send({ 35449 * type: 'broadcast', 35450 * event: 'cursor-pos', 35451 * payload: { x: Math.random(), y: Math.random() }, 35452 * }) 35453 * } 35454 * }) 35455 * ``` 35456 * 35457 * @exampleResponse Send a message via websocket 35458 * ```js 35459 * ok | timed out | error 35460 * ``` 35461 * 35462 * @example Send a message via REST 35463 * ```js 35464 * const channel = supabase.channel('room1') 35465 * 35466 * try { 35467 * await channel.httpSend('cursor-pos', { x: Math.random(), y: Math.random() }) 35468 * } finally { 35469 * await supabase.removeChannel(channel) 35470 * } 35471 * ``` 35472 */ 35473 async send(e, t = {}) { 35474 var i, r; 35475 if (!this.channelAdapter.canPush() && e.type === "broadcast") { 35476 console.warn("Realtime send() is automatically falling back to REST API. This behavior will be deprecated
35476in the future. Please use httpSend() explicitly for REST delivery."); 35477 const { event: s, payload: a } = e, l = { 35478 apikey: this.socket.apiKey ? this.socket.apiKey : "", 35479 "Content-Type": "application/json" 35480 }; 35481 this.socket.accessTokenValue && (l.Authorization = `Bearer ${this.socket.accessTokenValue}`); 35482 const o = { 35483 method: "POST", 35484 headers: l, 35485 body: JSON.stringify({ 35486 messages: [ 35487 { 35488 topic: this.subTopic, 35489 event: s, 35490 payload: a, 35491 private: this.private 35492 } 35493 ] 35494 }) 35495 }; 35496 try { 35497 const c = await this._fetchWithTimeout(this.broadcastEndpointURL, o, (i = t.timeout) !== null && i !== void 0 ? i : this.timeout); 35498 return await ((r = c.body) === null || r === void 0 ? void 0 : r.cancel()), c.ok ? "ok" : "error"; 35499 } catch (c) { 35500 return c instanceof Error && c.name === "AbortError" ? "timed out" : "error"; 35501 } 35502 } else 35503 return new Promise((s) => { 35504 var a, l, o; 35505 const c = this.channelAdapter.push(e.type, e, t.timeout || this.timeout); 35506 e.type === "broadcast" && !(!((o = (l = (a = this.params) === null || a === void 0 ? void 0 : a.config) === null || l === void 0 ? void 0 : l.broadcast) === null || o === void 0) && o.ack) && s("ok"), c.receive("ok", () => s("ok")), c.receive("error", () => s("error")), c.receive("timeout", () => s("timed out")); 35507 }); 35508 } 35509 /** 35510 * Updates the payload that will be sent the next time the channel joins (reconnects). 35511 * Useful for rotating access tokens or updating config without re-creating the channel. 35512 * 35513 * @category Realtime 35514 */ 35515 updateJoinPayload(e) { 35516 this.channelAdapter.updateJoinPayload(e); 35517 } 35518 /** 35519 * Leaves the channel. 35520 * 35521 * Unsubscribes from server events, and instructs channel to terminate on server. 35522 * Triggers onClose() hooks. 35523 * 35524 * To receive leave acknowledgements, use the a `receive` hook to bind to the server ack, ie: 35525 * channel.unsubscribe().receive("ok", () => alert("left!") ) 35526 * 35527 * @category Realtime 35528 */ 35529 async unsubscribe(e = this.timeout) { 35530 return new Promise((t) => { 35531 this.channelAdapter.unsubscribe(e).receive("ok", () => t("ok")).receive("timeout", () => t("timed out")).receive("error", () => t("error")); 35532 }); 35533 } 35534 /** 35535 * Destroys and stops related timers. 35536 * 35537 * @category Realtime 35538 */ 35539 teardown() { 35540 this.channelAdapter.teardown(); 35541 } 35542 /** @internal */ 35543 async _fetchWithTimeout(e, t, i) { 35544 const r = new AbortController(), s = setTimeout(() => r.abort(), i), a = await this.socket.fetch(e, Object.assign(Object.assign({}, t), { signal: r.signal })); 35545 return clearTimeout(s), a; 35546 } 35547 /** @internal */ 35548 _on(e, t, i) { 35549 const r = e.toLocaleLowerCase(), s = this.channelAdapter.on(e, i), a = { 35550 type: r, 35551 filter: t, 35552 callback: i, 35553 ref: s 35554 }; 35555 return this.bindings[r] ? this.bindings[r].push(a) : this.bindings[r] = [a], this._updateFilterMessage(), this; 35556 } 35557 /** 35558 * Registers a callback that will be executed when the channel closes. 35559 * 35560 * @internal 35561 */ 35562 _onClose(e) { 35563 this.channelAdapter.onClose(e); 35564 } 35565 /** 35566 * Registers a callback that will be executed when the channel encounteres an error. 35567 * 35568 * @internal 35569 */ 35570 _onError(e) { 35571 this.channelAdapter.onError(e); 35572 } 35573 /** @internal */ 35574 _updateFilterMessage() { 35575 this.channelAdapter.updateFilterBindings((e, t, i) => { 35576 var r, s, a, l, o, c, u; 35577 const h = e.event.toLocaleLowerCase(); 35578 if (this._notThisChannelEvent(h, i)) 35579 return !1; 35580 const d = (r = this.bindings[h]) === null || r === void 0 ? void 0 : r.find((f) => f.ref === e.ref); 35581 if (!d) 35582 return !0; 35583 if (["broadcast", "presence", "postgres_changes"].includes(h)) 35584 if ("id" in d) { 35585 const f = d.id, p = (s = d.filter) === null || s === void 0 ? void 0 : s.event; 35586 return f && ((a = t.ids) === null || a === void 0 ? void 0 : a.includes(f)) && (p === "*" || p?.toLocaleLowerCase() === ((l = t.data) === null || l === void 0 ? void 0 : l.type.toLocaleLowerCase())); 35587 } else { 35588 const f = (c = (o = d?.filter) === null || o === void 0 ? void 0 : o.event) === null || c === void 0 ? void 0 : c.toLocaleLowerCase(); 35589 return f === "*" || f === ((u = t?.event) === null || u === void 0 ? void 0 : u.toLocaleLowerCase()); 35590 } 35591 else 35592 return d.type.toLocaleLowerCase() === h; 35593 }); 35594 } 35595 /** @internal */ 35596 _notThisChannelEvent(e, t) { 35597 const { close: i, error: r, leave: s, join: a } = Sm; 35598 return t && [i, r, s, a].includes(e) && t !== this.joinPush.ref; 35599 } 35600 /** @internal */ 35601 _updateFilterTransform() { 35602 this.channelAdapter.updatePayloadTransform((e, t, i) => { 35603 if (typeof t == "object" && "ids" in t) { 35604 const r = t.data, { schema: s, table: a, commit_timestamp: l, type: o, errors: c } = r; 35605 return Object.assign(Object.assign({}, { 35606 schema: s, 35607 table: a, 35608 commit_timestamp: l, 35609 eventType: o, 35610 new: {}, 35611 old: {}, 35612 errors: c 35613 }), this._getPayloadRecords(r)); 35614 } 35615 return t; 35616 }); 35617 } 35618 copyBindings(e) { 35619 if (this.joinedOnce) 35620 throw new Error("cannot copy bindings into joined channel"); 35621 for (const t in e.bindings) 35622 for (const i of e.bindings[t]) 35623 this._on(i.type, i.filter, i.callback); 35624 } 35625 /** 35626 * Compares two optional filter values for equality. 35627 * Treats undefined, null, and empty string as equivalent empty values. 35628 * @internal 35629 */ 35630 static isFilterValueEqual(e, t) { 35631 return (e ?? void 0) === (t ?? void 0); 35632 } 35633 /** @internal */ 35634 _getPayloadRecords(e) { 35635 const t = { 35636 new: {}, 35637 old: {} 35638 }; 35639 return (e.type === "INSERT" || e.type === "UPDATE") && (t.new = sf(e.columns, e.record)), (e.type === "UPDATE" || e.type === "DELETE") && (t.old = sf(e.columns, e.old_record)), t; 35640 } 35641} 35642class QM { 35643 constructor(e, t) { 35644 this.socket = new jM(e, t); 35645 } 35646 get timeout() { 35647 return this.socket.timeout; 35648 } 35649 get endPoint() { 35650 return this.socket.endPoint; 35651 } 35652 get transport() { 35653 return this.socket.transport; 35654 } 35655 get heartbeatIntervalMs() { 35656 return this.socket.heartbeatIntervalMs; 35657 } 35658 get heartbeatCallback() { 35659 return this.socket.heartbeatCallback; 35660 } 35661 set heartbeatCallback(e) { 35662 this.socket.heartbeatCallback = e; 35663 } 35664 get heartbeatTimer() { 35665 return this.socket.heartbeatTimer; 35666 } 35667 get pendingHeartbeatRef() { 35668 return this.socket.pendingHeartbeatRef; 35669 } 35670 get reconnectTimer() { 35671 return this.socket.reconnectTimer; 35672 } 35673 get vsn() { 35674 return this.socket.vsn; 35675 } 35676 get encode() { 35677 return this.socket.encode; 35678 } 35679 get decode() { 35680 return this.socket.decode; 35681 } 35682 get reconnectAfterMs() { 35683 return this.socket.reconnectAfterMs; 35684 } 35685 get sendBuffer() { 35686 return this.socket.sendBuffer; 35687 } 35688 get stateChangeCallbacks() { 35689 return this.socket.stateChangeCallbacks; 35690 } 35691 connect() { 35692 this.socket.connect(); 35693 } 35694 disconnect(e, t, i, r = 1e4) { 35695 return new Promise((s) => { 35696 setTimeout(() => s("timeout"), r), this.socket.disconnect(() => { 35697 e(), s("ok"); 35698 }, t, i); 35699 }); 35700 } 35701 push(e) { 35702 this.socket.push(e); 35703 } 35704 log(e, t, i) { 35705 this.socket.log(e, t, i); 35706 } 35707 makeRef() { 35708 return this.socket.makeRef(); 35709 } 35710 onOpen(e) { 35711 this.socket.onOpen(e); 35712 } 35713 onClose(e) { 35714 this.socket.onClose(e); 35715 } 35716 onError(e) { 35717 this.socket.onError(e); 35718 } 35719 onMessage(e) { 35720 this.socket.onMessage(e); 35721 } 35722 isConnected() { 35723 return this.socket.isConnected(); 35724 } 35725 isConnecting() { 35726 return this.socket.connectionState() == ou.connecting; 35727 } 35728 isDisconnecting() { 35729 return this.socket.connectionState() == ou.closing; 35730 } 35731 connectionState() { 35732 return this.socket.connectionState(); 35733 } 35734 endPointURL() { 35735 return this.socket.endPointURL(); 35736 } 35737 sendHeartbeat() { 35738 this.socket.sendHeartbeat(); 35739 } 35740 /** 35741 * @internal 35742 */ 35743 getSocket() { 35744 return this.socket; 35745 } 35746} 35747const cf = { 35748 HEARTBEAT_INTERVAL: 25e3 35749}, eT = [1e3, 2e3, 5e3, 1e4], tT = 1e4; 35750function nT() { 35751 const n = /* @__PURE__ */ new Map(); 35752 return { 35753 get length() { 35754 return n.size; 35755 }, 35756 clear() { 35757 n.clear(); 35758 }, 35759 getItem(e) { 35760 return n.has(e) ? n.get(e) : null; 35761 }, 35762 key(e) { 35763 var t; 35764 return (t = Array.from(n.keys())[e]) !== null && t !== void 0 ? t : null; 35765 }, 35766 removeItem(e) { 35767 n.delete(e); 35768 }, 35769 setItem(e, t) {
35770 n.set(e, String(t)); 35771 } 35772 }; 35773} 35774function iT() { 35775 try { 35776 if (typeof globalThis < "u" && globalThis.sessionStorage) 35777 return globalThis.sessionStorage; 35778 } catch { 35779 } 35780 return nT(); 35781} 35782const rT = ` 35783 addEventListener("message", (e) => { 35784 if (e.data.event === "start") { 35785 setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); 35786 } 35787 });`; 35788class sT { 35789 get endPoint() { 35790 return this.socketAdapter.endPoint; 35791 } 35792 get timeout() { 35793 return this.socketAdapter.timeout; 35794 } 35795 get transport() { 35796 return this.socketAdapter.transport; 35797 } 35798 get heartbeatCallback() { 35799 return this.socketAdapter.heartbeatCallback; 35800 } 35801 get heartbeatIntervalMs() { 35802 return this.socketAdapter.heartbeatIntervalMs; 35803 } 35804 get heartbeatTimer() { 35805 return this.worker ? this._workerHeartbeatTimer : this.socketAdapter.heartbeatTimer; 35806 } 35807 get pendingHeartbeatRef() { 35808 return this.worker ? this._pendingWorkerHeartbeatRef : this.socketAdapter.pendingHeartbeatRef; 35809 } 35810 get reconnectTimer() { 35811 return this.socketAdapter.reconnectTimer; 35812 } 35813 get vsn() { 35814 return this.socketAdapter.vsn; 35815 } 35816 get encode() { 35817 return this.socketAdapter.encode; 35818 } 35819 get decode() { 35820 return this.socketAdapter.decode; 35821 } 35822 get reconnectAfterMs() { 35823 return this.socketAdapter.reconnectAfterMs; 35824 } 35825 get sendBuffer() { 35826 return this.socketAdapter.sendBuffer; 35827 } 35828 get stateChangeCallbacks() { 35829 return this.socketAdapter.stateChangeCallbacks; 35830 } 35831 /** 35832 * Initializes the Socket. 35833 * 35834 * @param endPoint The string WebSocket endpoint, ie, "ws://example.com/socket", "wss://example.com", "/socket" (inherited host & protocol) 35835 * @param httpEndpoint The string HTTP endpoint, ie, "https://example.com", "/" (inherited host & protocol) 35836 * @param options.transport The Websocket Transport, for example WebSocket. This can be a custom implementation 35837 * @param options.timeout The default timeout in milliseconds to trigger push timeouts. 35838 * @param options.params The optional params to pass when connecting. 35839 * @param options.headers Deprecated: headers cannot be set on websocket connections and this option will be removed in the future. 35840 * @param options.heartbeatIntervalMs The millisec interval to send a heartbeat message. 35841 * @param options.heartbeatCallback The optional function to handle heartbeat status and latency. 35842 * @param options.logger The optional function for specialized logging, ie: logger: (kind, msg, data) => { console.log(`${kind}: ${msg}`, data) } 35843 * @param options.logLevel Sets the log level for Realtime 35844 * @param options.encode The function to encode outgoing messages. Defaults to JSON: (payload, callback) => callback(JSON.stringify(payload)) 35845 * @param options.decode The function to decode incoming messages. Defaults to Serializer's decode. 35846 * @param options.reconnectAfterMs he optional function that returns the millsec reconnect interval. Defaults to stepped backoff off. 35847 * @param options.worker Use Web Worker to set a side flow. Defaults to false. 35848 * @param options.workerUrl The URL of the worker script. Defaults to https://realtime.supabase.com/worker.js that includes a heartbeat event call to keep the connection alive. 35849 * @param options.vsn The protocol version to use when connecting. Supported versions are "1.0.0" and "2.0.0". Defaults to "2.0.0". 35850 * 35851 * @category Realtime 35852 * 35853 * @example Using supabase-js (recommended) 35854 * ```ts 35855 * import { createClient } from '@supabase/supabase-js' 35856 * 35857 * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key') 35858 * const channel = supabase.channel('room1') 35859 * channel 35860 * .on('broadcast', { event: 'cursor-pos' }, (payload) => console.log(payload)) 35861 * .subscribe() 35862 * ``` 35863 * 35864 * @example Standalone import for bundle-sensitive environments 35865 * ```ts 35866 * import RealtimeClient from '@supabase/realtime-js' 35867 * 35868 * const client = new RealtimeClient('https://xyzcompany.supabase.co/realtime/v1', { 35869 * params: { apikey: 'your-publishable-key' }, 35870 * }) 35871 * client.connect() 35872 * ``` 35873 */ 35874 constructor(e, t) { 35875 var i; 35876 if (this.channels = new Array(), this.accessTokenValue = null, this.accessToken = null, this.apiKey = null, this.httpEndpoint = "", this.headers = {}, this.params = {}, this.ref = 0, this.serializer = new LM(), this._manuallySetToken = !1, this._authPromise = null, this._workerHeartbeatTimer = void 0, this._pendingWorkerHeartbeatRef = null, this._pendingDisconnectTimer = null, this._disconnectOnEmptyChannelsAfterMs
35876= 0, this._resolveFetch = (s) => s ? (...a) => s(...a) : (...a) => fetch(...a), !(!((i = t?.params) === null || i === void 0) && i.apikey)) 35877 throw new Error("API key is required to connect to Realtime"); 35878 this.apiKey = t.params.apikey; 35879 const r = this._initializeOptions(t); 35880 this.socketAdapter = new QM(e, r), this.httpEndpoint = Mm(e), this.fetch = this._resolveFetch(t?.fetch); 35881 } 35882 /** 35883 * Connects the socket, unless already connected. 35884 * 35885 * @category Realtime 35886 */ 35887 connect() { 35888 if (!(this.isConnecting() || this.isDisconnecting() || this.isConnected())) { 35889 this.accessToken && !this._authPromise && this._setAuthSafely("connect"), this._setupConnectionHandlers(); 35890 try { 35891 this.socketAdapter.connect(); 35892 } catch (e) { 35893 const t = e.message; 35894 throw t.includes("Node.js") ? new Error(`${t} 35895 35896To use Realtime in Node.js, you need to provide a WebSocket implementation: 35897 35898Option 1: Use Node.js 22+ which has native WebSocket support 35899Option 2: Install and provide the "ws" package: 35900 35901 npm install ws 35902 35903 import ws from "ws" 35904 const client = new RealtimeClient(url, { 35905 ...options, 35906 transport: ws 35907 })`) : new Error(`WebSocket not available: ${t}`); 35908 } 35909 this._handleNodeJsRaceCondition(); 35910 } 35911 } 35912 /** 35913 * Returns the URL of the websocket. 35914 * @returns string The URL of the websocket. 35915 * 35916 * @category Realtime 35917 */ 35918 endpointURL() { 35919 return this.socketAdapter.endPointURL(); 35920 } 35921 /** 35922 * Disconnects the socket. 35923 * 35924 * @param code A numeric status code to send on disconnect. 35925 * @param reason A custom reason for the disconnect. 35926 * 35927 * @category Realtime 35928 */ 35929 async disconnect(e, t) { 35930 return this._cancelPendingDisconnect(), this.isDisconnecting() ? "ok" : await this.socketAdapter.disconnect(() => { 35931 clearInterval(this._workerHeartbeatTimer), this._terminateWorker(); 35932 }, e, t); 35933 } 35934 /** 35935 * Returns all created channels 35936 * 35937 * @category Realtime 35938 */ 35939 getChannels() { 35940 return this.channels; 35941 } 35942 /** 35943 * Unsubscribes, removes and tears down a single channel 35944 * @param channel A RealtimeChannel instance 35945 * 35946 * @category Realtime 35947 */ 35948 async removeChannel(e) { 35949 const t = await e.unsubscribe(); 35950 return t === "ok" && e.teardown(), t; 35951 } 35952 /** 35953 * Unsubscribes, removes and tears down all channels 35954 * 35955 * @category Realtime 35956 */ 35957 async removeAllChannels() { 35958 const e = this.channels.map(async (i) => { 35959 const r = await i.unsubscribe(); 35960 return i.teardown(), r; 35961 }), t = await Promise.all(e); 35962 return await this.disconnect(), t; 35963 } 35964 /** 35965 * Logs the message. 35966 * 35967 * For customized logging, `this.logger` can be overridden in Client constructor. 35968 * 35969 * @category Realtime 35970 */ 35971 log(e, t, i) { 35972 this.socketAdapter.log(e, t, i); 35973 } 35974 /** 35975 * Returns the current state of the socket. 35976 * 35977 * @category Realtime 35978 */ 35979 connectionState() { 35980 return this.socketAdapter.connectionState() || ou.closed; 35981 } 35982 /** 35983 * Returns `true` is the connection is open. 35984 * 35985 * @category Realtime 35986 */ 35987 isConnected() { 35988 return this.socketAdapter.isConnected(); 35989 } 35990 /** 35991 * Returns `true` if the connection is currently connecting. 35992 * 35993 * @category Realtime 35994 */ 35995 isConnecting() { 35996 return this.socketAdapter.isConnecting(); 35997 } 35998 /** 35999 * Returns `true` if the connection is currently disconnecting. 36000 * 36001 * @category Realtime 36002 */ 36003 isDisconnecting() { 36004 return this.socketAdapter.isDisconnecting(); 36005 } 36006 /** 36007 * Creates (or reuses) a {@link RealtimeChannel} for the provided topic. 36008 * 36009 * Topics are automatically prefixed with `realtime:` to match the Realtime service. 36010 * If a channel with the same topic already exists it will be returned instead of creating 36011 * a duplicate connection. 36012 * 36013 * @category Realtime 36014 */ 36015 channel(e, t = { config: {} }) { 36016 const i = `realtime:${e}`, r = this.getChannels().find((s) => s.topic === i); 36017 if (r) 36018 return r; 36019 { 36020 const s = new ta(`realtime:${e}`, t, this); 36021 return this._cancelPendingDisconnect(), this.channels.push(s), s; 36022 } 36023 } 36024 /** 36025 * Push out a message if the socket is connected. 36026 *
36027 * If the socket is not connected, the message gets enqueued within a local buffer, and sent out when a connection is next established. 36028 * 36029 * @category Realtime 36030 */ 36031 push(e) { 36032 this.socketAdapter.push(e); 36033 } 36034 /** 36035 * Sets the JWT access token used for channel subscription authorization and Realtime RLS. 36036 * 36037 * If param is null it will use the `accessToken` callback function or the token set on the client. 36038 * 36039 * On callback used, it will set the value of the token internal to the client. 36040 * 36041 * When a token is explicitly provided, it will be preserved across channel operations 36042 * (including removeChannel and resubscribe). The `accessToken` callback will not be 36043 * invoked until `setAuth()` is called without arguments. 36044 * 36045 * @param token A JWT string to override the token set on the client. 36046 * 36047 * @example Setting the authorization header 36048 * // Use a manual token (preserved across resubscribes, ignores accessToken callback) 36049 * client.realtime.setAuth('my-custom-jwt') 36050 * 36051 * // Switch back to using the accessToken callback 36052 * client.realtime.setAuth() 36053 * 36054 * @category Realtime 36055 */ 36056 async setAuth(e = null) { 36057 this._authPromise = this._performAuth(e); 36058 try { 36059 await this._authPromise; 36060 } finally { 36061 this._authPromise = null; 36062 } 36063 } 36064 /** 36065 * Returns true if the current access token was explicitly set via setAuth(token), 36066 * false if it was obtained via the accessToken callback. 36067 * @internal 36068 */ 36069 _isManualToken() { 36070 return this._manuallySetToken; 36071 } 36072 /** 36073 * Sends a heartbeat message if the socket is connected. 36074 * 36075 * @category Realtime 36076 */ 36077 async sendHeartbeat() { 36078 this.socketAdapter.sendHeartbeat(); 36079 } 36080 /** 36081 * Sets a callback that receives lifecycle events for internal heartbeat messages. 36082 * Useful for instrumenting connection health (e.g. sent/ok/timeout/disconnected). 36083 * 36084 * @category Realtime 36085 */ 36086 onHeartbeat(e) { 36087 this.socketAdapter.heartbeatCallback = this._wrapHeartbeatCallback(e); 36088 } 36089 /** 36090 * Return the next message ref, accounting for overflows 36091 * 36092 * @internal 36093 */ 36094 _makeRef() { 36095 return this.socketAdapter.makeRef(); 36096 } 36097 /** 36098 * Removes a channel from RealtimeClient 36099 * 36100 * @param channel An open subscription. 36101 * 36102 * @internal 36103 */ 36104 _remove(e) { 36105 this.channels = this.channels.filter((t) => t.topic !== e.topic), this.channels.length === 0 && (this.log("transport", "no channels remaining, scheduling disconnect"), this._schedulePendingDisconnect()); 36106 } 36107 /** @internal */ 36108 _schedulePendingDisconnect() { 36109 if (this._cancelPendingDisconnect(), this._disconnectOnEmptyChannelsAfterMs === 0) { 36110 this.log("transport", "disconnecting immediately - no channels"), this.disconnect(); 36111 return; 36112 } 36113 this._pendingDisconnectTimer = setTimeout(() => { 36114 this._pendingDisconnectTimer = null, this.channels.length === 0 && (this.log("transport", "deferred disconnect fired - no channels, disconnecting"), this.disconnect()); 36115 }, this._disconnectOnEmptyChannelsAfterMs), this.log("transport", `deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`); 36116 } 36117 /** @internal */ 36118 _cancelPendingDisconnect() { 36119 this._pendingDisconnectTimer !== null && (this.log("transport", "pending disconnect cancelled - channel activity detected"), clearTimeout(this._pendingDisconnectTimer), this._pendingDisconnectTimer = null); 36120 } 36121 /** 36122 * Perform the actual auth operation 36123 * @internal 36124 */ 36125 async _performAuth(e = null) { 36126 let t, i = !1; 36127 if (e) 36128 t = e, i = !0; 36129 else if (this.accessToken) 36130 try { 36131 t = await this.accessToken(); 36132 } catch (r) { 36133 this.log("error", "Error fetching access token from callback", r), t = this.accessTokenValue; 36134 } 36135 else 36136 t = this.accessTokenValue; 36137 i ? this._manuallySetToken = !0 : this.accessToken && (this._manuallySetToken = !1), this.accessTokenValue != t && (this.accessTokenValue = t, this.channels.forEach((r) => { 36138 const s = { 36139 access_token: t, 36140 version: TM 36141 }; 36142 t && r.updateJoinPayload(s), r.joinedOnce && r.channelAdapter.isJoined() && r.channelAdapter.push(Sm.access_token, { 36143 access_token: t 36144 }); 36145 })); 36146 } 36147 /** 36148 * Wait for any in-flight auth operations to complete 36149 * @internal 36150 */ 36151 async _waitForAuthIfNeeded() { 36152 this._authPromise && await this._authPromise; 36153 } 36154 /** 36155 * Safely call setAuth with standardized error handling 36156 * @internal 36157 */ 36158 _setAuthSafely(e = "general") { 36159 this._isManualToken() || this.setAuth().catch((t) => { 36160 this.log("error", `Error setting auth in ${e}`, t); 36161 }); 36162 } 36163 /** @internal */ 36164 _setupConnectionHandlers() { 36165 this.socketAdapter.onOpen(() => { 36166 (this._authPromise || (this.accessToken && !this.accessTokenValue ? this.setAuth() : Promise.resolve())).c
36166atch((t) => { 36167 this.log("error", "error waiting for auth on connect", t); 36168 }), this.worker && !this.workerRef && this._startWorkerHeartbeat(); 36169 }), this.socketAdapter.onClose(() => { 36170 this.worker && this.workerRef && this._terminateWorker(); 36171 }), this.socketAdapter.onMessage((e) => { 36172 e.ref && e.ref === this._pendingWorkerHeartbeatRef && (this._pendingWorkerHeartbeatRef = null); 36173 }); 36174 } 36175 /** @internal */ 36176 _handleNodeJsRaceCondition() { 36177 this.socketAdapter.isConnected() && this.socketAdapter.getSocket().onConnOpen(); 36178 } 36179 /** @internal */ 36180 _wrapHeartbeatCallback(e) { 36181 return (t, i) => { 36182 t == "sent" && this._setAuthSafely(), e && e(t, i); 36183 }; 36184 } 36185 /** @internal */ 36186 _startWorkerHeartbeat() { 36187 this.workerUrl ? this.log("worker", `starting worker for from ${this.workerUrl}`) : this.log("worker", "starting default worker"); 36188 const e = this._workerObjectUrl(this.workerUrl); 36189 this.workerRef = new Worker(e), this.workerRef.onerror = (t) => { 36190 this.log("worker", "worker error", t.message), this._terminateWorker(), this.disconnect(); 36191 }, this.workerRef.onmessage = (t) => { 36192 t.data.event === "keepAlive" && this.sendHeartbeat(); 36193 }, this.workerRef.postMessage({ 36194 event: "start", 36195 interval: this.heartbeatIntervalMs 36196 }); 36197 } 36198 /** 36199 * Terminate the Web Worker and clear the reference 36200 * @internal 36201 */ 36202 _terminateWorker() { 36203 this.workerRef && (this.log("worker", "terminating worker"), this.workerRef.terminate(), this.workerRef = void 0); 36204 } 36205 /** @internal */ 36206 _workerObjectUrl(e) { 36207 let t; 36208 if (e) 36209 t = e; 36210 else { 36211 const i = new Blob([rT], { type: "application/javascript" }); 36212 t = URL.createObjectURL(i); 36213 } 36214 return t; 36215 } 36216 /** 36217 * Initialize socket options with defaults 36218 * @internal 36219 */ 36220 _initializeOptions(e) { 36221 var t, i, r, s, a, l, o, c, u, h, d, f; 36222 this.worker = (t = e?.worker) !== null && t !== void 0 ? t : !1, this.accessToken = (i = e?.accessToken) !== null && i !== void 0 ? i : null; 36223 const p = {}; 36224 p.timeout = (r = e?.timeout) !== null && r !== void 0 ? r : CM, p.heartbeatIntervalMs = (s = e?.heartbeatIntervalMs) !== null && s !== void 0 ? s : cf.HEARTBEAT_INTERVAL, this._disconnectOnEmptyChannelsAfterMs = (a = e?.disconnectOnEmptyChannelsAfterMs) !== null && a !== void 0 ? a : 2 * ((l = e?.heartbeatIntervalMs) !== null && l !== void 0 ? l : cf.HEARTBEAT_INTERVAL), p.transport = (o = e?.transport) !== null && o !== void 0 ? o : EM.getWebSocketConstructor(), p.params = e?.params, p.logger = e?.logger, p.heartbeatCallback = this._wrapHeartbeatCallback(e?.heartbeatCallback), p.sessionStorage = (c = e?.sessionStorage) !== null && c !== void 0 ? c : iT(), p.reconnectAfterMs = (u = e?.reconnectAfterMs) !== null && u !== void 0 ? u : ((_) => eT[_ - 1] || tT); 36225 let v, m; 36226 const g = (h = e?.vsn) !== null && h !== void 0 ? h : RM; 36227 switch (g) { 36228 case AM: 36229 v = (_, x) => x(JSON.stringify(_)), m = (_, x) => x(JSON.parse(_)); 36230 break; 36231 case wm: 36232 v = this.serializer.encode.bind(this.serializer), m = this.serializer.decode.bind(this.serializer); 36233 break; 36234 default: 36235 throw new Error(`Unsupported serializer version: ${p.vsn}`); 36236 } 36237 if (p.vsn = g, p.encode = (d = e?.encode) !== null && d !== void 0 ? d : v, p.decode = (f = e?.decode) !== null && f !== void 0 ? f : m, p.beforeReconnect = this._reconnectAuth.bind(this), (e?.logLevel || e?.log_level) && (this.logLevel = e.logLevel || e.log_level, p.params = Object.assign(Object.assign({}, p.params), { log_level: this.logLevel })), this.worker) { 36238 if (typeof window < "u" && !window.Worker) 36239 throw new Error("Web Worker is not supported"); 36240 this.workerUrl = e?.workerUrl, p.autoSendHeartbeat = !this.worker; 36241 } 36242 return p; 36243 } 36244 /** @internal */ 36245 async _reconnectAuth() { 36246 await this._waitForAuthIfNeeded(), this.isConnected() || this.connect(); 36247 } 36248} 36249var ha = class extends Error { 36250 constructor(n, e) { 36251 super(n), this.name = "IcebergError", this.status = e.status, this.icebergType = e.icebergType, this.icebergCode = e.icebergCode, this.details = e.details, this.isCommitStateUnknown = e.icebergType === "CommitStateUnknownException" || [500, 502, 504].includes(e.status) && e.icebergType?.includes("CommitState") === !0; 36252 } 36253 /** 36254 * Returns true if the error is a 404 Not Found error. 36255 */ 36256 isNotFound() { 36257 return this.status === 404; 36258 } 36259 /** 36260 * Returns true if the error is a 409 Conflict error. 36261 */ 36262 isConflict() { 36263 return this.status === 409; 36264 } 36265 /** 36266 * Returns true if the error is a 419 Authentication Timeout error. 36267 */ 36268 isAuthenticationTimeout() { 36269 return this.status === 419; 36270 } 36271}; 36272function aT(n, e, t) { 36273 const i = new URL(e, n); 36274 if (t) 36275 for (const [r, s] of Object.entries(t)) 36276 s !== void 0 && i.searchParams.set(r, s); 36277 return i.toString(); 36278} 36279async function oT(n) { 36280 return !n || n.type === "none" ? {} : n.type === "bearer" ? { Authorization: `Bearer ${n.token}` } : n.type === "header" ? { [n.name]: n.value } : n.type === "custom" ? await n.getHeaders() : {}; 36281} 36282function lT(n) { 36283 const e = n.fetchImpl ?? globalThis.fetch; 36284 return { 36285 async request({ 36286 method: t, 36287 path: i, 36288 query: r, 36289 body: s, 36290 headers: a 36291 }) { 36292 const l = aT(n.baseUrl, i, r), o = await oT(n.auth), c = await e(l, { 36293 method: t, 36294 headers: { 36295 ...s ? { "Content-Type": "application/json" } : {}, 36296 ...o, 36297 ...a 36298 }, 36299 body: s ? JSON.stringify(s) : void 0 36300 }), u = await c.text(), h = (c.headers.get("content-type") || "").includes("application/json"), d = h && u ? JSON.parse(u) : u; 36301 if (!c.ok) { 36302 const f = h ? d : void 0, p = f?.error; 36303 throw new ha( 36304 p?.message ?? `Request failed with status ${c.status}`, 36305 { 36306 status: c.status, 36307 icebergType: p?.type, 36308 icebergCode: p?.code, 36309 details: f 36310 } 36311 ); 36312 } 36313 return { status: c.status, headers: c.headers, data: d }; 36314 } 36315 }; 36316} 36317function ao(n) { 36318 return n.join("�"); 36319} 36320var cT = class { 36321 constructor(n, e = "") { 36322 this.client = n, this.prefix = e; 36323 } 36324 async listNamespaces(n) { 36325 const e = n ? { parent: ao(n.namespace) } : void 0; 36326 return (await this.client.request({ 36327 method: "GET", 36328 path: `${this.prefix}/namespaces`, 36329 query: e 36330 })).data.namespaces.map((i) => ({ namespace: i })); 36331 } 36332 async createNamespace(n, e) { 36333 const t = { 36334 namespace: n.namespace, 36335 properties: e?.properties 36336 }; 36337 return (await this.client.request({ 36338 method: "POST", 36339 path: `${this.prefix}/namespaces`, 36340 body: t 36341 })).data; 36342 } 36343 async dropNamespace(n) { 36344 await this.client.request({ 36345 method: "DELETE", 36346 path: `${this.prefix}/namespaces/${ao(n.namespace)}` 36347 }); 36348 } 36349 async loadNamespaceMetadata(n) { 36350 return { 36351 properties: (await this.client.request({ 36352 method: "GET", 36353 path: `${this.prefix}/namespaces/${ao(n.namespace)}` 36354 })).data.properties 36355 }; 36356 } 36357 async namespaceExists(n) { 36358 try { 36359 return await this.client.request({ 36360 method: "HEAD", 36361 path: `${this.prefix}/namespaces/${ao(n.namespace)}` 36362 }), !0; 36363 } catch (e) { 36364 if (e instanceof ha && e.status === 404) 36365 return !1; 36366 throw e; 36367 } 36368 } 36369 async createNamespaceIfNotExists(n, e) { 36370 try { 36371 return await this.createNamespace(n, e); 36372 } catch (t) { 36373 if (t instanceof ha && t.status === 409) 36374 return; 36375 throw t; 36376 } 36377 } 36378}; 36379function Qr(n) { 36380 return n.join("�"); 36381} 36382var uT = class { 36383 constructor(n, e = "", t) { 36384 this.client = n, this.prefix = e, this.accessDelegation = t; 36385 } 36386 async listTables(n) { 36387 return (await this.client.request({ 36388 method: "GET", 36389 path: `${this.prefix}/namespaces/${Qr(n.namespace)}/tables` 36390 })).data.identifiers; 36391 } 36392 async createTable(n, e) { 36393 const t = {}; 36394 return this.accessDelegation && (t["X-Iceberg-Access-Delegation"] = this.accessDelegation), (await this.client.request({ 36395 method: "POST", 36396 path: `${this.prefix}/namespaces/${Qr(n.namespace)}/tables`, 36397 body: e, 36398 headers: t 36399 })).data.metadata; 36400 } 36401 async updateTable(n, e) { 36402 const t = await this.client.request({ 36403 method: "POST", 36404 path: `${this.prefix}/namespaces/${Qr(n.namespace)}/tables/${n.name}`, 36405 body: e 36406 }); 36407 return { 36408 "metadata-location": t.data["metadata-location"], 36409 metadata: t.data.metadata 36410 }; 36411 } 36412 async dropTable(n, e) { 36413 await this.client.request({ 36414 method: "DELETE", 36415 path: `${this.prefix}/namespaces/${Qr(n.namespace)}/tables/${n.name}`, 36416 query: { purgeRequested: String(e?.purge ?? !1) } 36417 }); 36418 } 36419 async loadTable(n) { 36420 const e = {}; 36421 return this.accessDelegation && (e["X-Iceberg-Access-Delegation"] = this.accessDelegation), (await this.client.request({ 36422 method: "GET", 36423 path: `${this.prefix}/namespaces/${Qr(n.namespace)}/tables/${n.name}`, 36424 headers: e 36425 })).data.metadata; 36426 } 36427 async tableExists(n) { 36428 const e = {}; 36429 this.accessDelegation && (e["X-Iceberg-Access-Delegation"] = this.accessDelegation); 36430 try { 36431 return await this.client.request({ 36432 method: "HEAD", 36433 path: `${this.prefix}/namespaces/${Qr(n.namespace)}/tables/${n.name}`, 36434 headers: e 36435 }), !0; 36436 } catch (t) { 36437 if (t instanceof ha && t.status === 404) 36438 return !1; 36439 throw t; 36440 } 36441 } 36442 async createTableIfNotExists(n, e) { 36443 try { 36444 return await this.createTable(n, e); 36445 } catch (t) { 36446 if (t instanceof ha && t.status === 409) 36447 return await this.loadTable({ namespace: n.namespace, name: e.name }); 36448 throw t; 36449 } 36450 } 36451}, hT = class { 36452 /** 36453 * Creates a new Iceberg REST Catalog client. 36454 * 36455 * @param options - Configuration options for the catalog client 36456 */ 36457 constructor(n) { 36458 let e = "v1"; 36459 n.catalogName && (e += `/${n.catalogName}`); 36460 const t = n.baseUrl.endsWith("/") ? n.baseUrl : `${n.baseUrl}/`; 36461 this.client = lT({ 36462 baseUrl: t, 36463 auth: n.auth, 36464 fetchImpl: n.fetch 36465 }), this.accessDelegation = n.accessDelegation?.join(","), this.namespaceOps = new cT(this.client, e), this.tableOps = new uT(this.client, e, this.accessDelegation); 36466 } 36467 /** 36468 * Lists all namespaces in the catalog. 36469 * 36470 * @param parent - Optional parent namespace to list children under 36471 * @returns Array of namespace identifiers 36472 * 36473 * @example 36474 * ```typescript 36475 * // List all top-level namespaces 36476 * const namespaces = await catalog.listNamespaces(); 36477 * 36478 * // List namespaces under a parent 36479 * const children = await catalog.listNamespaces({ namespace: ['analytics'] }); 36480 * ``` 36481 */ 36482 async listNamespaces(n) { 36483 return this.namespaceOps.listNamespaces(n); 36484 } 36485 /** 36486 * Creates a new namespace in the catalog. 36487 * 36488 * @param id - Namespace identifier to create 36489 * @param metadata - Optional metadata properties for the namespace 36490 * @returns Response containing the created namespace and its properties 36491 * 36492 * @example 36493 * ```typescript 36494 * const response = await catalog.createNamespace( 36495 * { namespace: ['analytics'] }, 36496 * { properties: { owner: 'data-team' } } 36497 * ); 36498 * console.log(response.namespace); // ['analytics'] 36499 * console.log(response.properties); // { owner: 'data-team', ... } 36500 * ``` 36501 */ 36502 async createNamespace(n, e) { 36503 return this.namespaceOps.createNamespace(n, e); 36504 } 36505 /** 36506 * Drops a namespace from the catalog. 36507 * 36508 * The namespace must be empty (contain no tables) before it can be dropped. 36509 * 36510 * @param id - Namespace identifier to drop 36511 * 36512 * @example 36513 * ```typescript 36514 * await catalog.dropNamespace({ namespace: ['analytics'] }); 36515 * ``` 36516 */ 36517 async dropNamespace(n) { 36518 await this.namespaceOps.dropNamespace(n); 36519 } 36520 /** 36521 * Loads metadata for a namespace. 36522 * 36523 * @param id - Namespace identifier to load 36524 * @returns Namespace metadata including properties 36525 * 36526 * @example 36527 * ```typescript 36528 * const metadata = await catalog.loadNamespaceMetadata({ namespace: ['analytics'] }); 36529 * console.log(metadata.properties); 36530 * ``` 36531 */ 36532 async loadNamespaceMetadata(n) { 36533 return this.namespaceOps.loadNamespaceMetadata(n); 36534 } 36535 /** 36536 * Lists all tables in a namespace. 36537 * 36538 * @param namespace - Namespace identifier to list tables from 36539 * @returns Array of table identifiers 36540 * 36541 * @example 36542 * ```typescript 36543 * const tables = await catalog.listTables({ namespace: ['analytics'] }); 36544 * console.log(tables); // [{ namespace: ['analytics'], name: 'events' }, ...] 36545 * ``` 36546 */ 36547 async listTables(n) { 36548 return this.tableOps.listTables(n); 36549 } 36550 /** 36551 * Creates a new table in the catalog. 36552 * 36553 * @param namespace - Namespace to create the table in 36554 * @param request - Table creation request including name, schema, partition spec, etc. 36555 * @returns Table metadata for the created table 36556 * 36557 * @example 36558 * ```typescript 36559 * const metadata = await catalog.createTable( 36560 * { namespace: ['analytics'] }, 36561 * { 36562 * name: 'events', 36563 * schema: { 36564 * type: 'struct', 36565 * fields: [ 36566 * { id: 1, name: 'id', type: 'long', required: true }, 36567 * { id: 2, name: 'timestamp', type: 'timestamp', required: true } 36568 * ], 36569 * 'schema-id': 0 36570 * }, 36571 * 'partition-spec': { 36572 * 'spec-id': 0, 36573 * fields: [ 36574 * { source_id: 2, field_id: 1000, name: 'ts_day', transform: 'day' } 36575 * ] 36576 * } 36577 * } 36578 * ); 36579 * ``` 36580 */ 36581 async createTable(n, e) {
36582 return this.tableOps.createTable(n, e); 36583 } 36584 /** 36585 * Updates an existing table's metadata. 36586 * 36587 * Can update the schema, partition spec, or properties of a table. 36588 * 36589 * @param id - Table identifier to update 36590 * @param request - Update request with fields to modify 36591 * @returns Response containing the metadata location and updated table metadata 36592 * 36593 * @example 36594 * ```typescript 36595 * const response = await catalog.updateTable( 36596 * { namespace: ['analytics'], name: 'events' }, 36597 * { 36598 * properties: { 'read.split.target-size': '134217728' } 36599 * } 36600 * ); 36601 * console.log(response['metadata-location']); // s3://... 36602 * console.log(response.metadata); // TableMetadata object 36603 * ``` 36604 */ 36605 async updateTable(n, e) { 36606 return this.tableOps.updateTable(n, e); 36607 } 36608 /** 36609 * Drops a table from the catalog. 36610 * 36611 * @param id - Table identifier to drop 36612 * 36613 * @example 36614 * ```typescript 36615 * await catalog.dropTable({ namespace: ['analytics'], name: 'events' }); 36616 * ``` 36617 */ 36618 async dropTable(n, e) { 36619 await this.tableOps.dropTable(n, e); 36620 } 36621 /** 36622 * Loads metadata for a table. 36623 * 36624 * @param id - Table identifier to load 36625 * @returns Table metadata including schema, partition spec, location, etc. 36626 * 36627 * @example 36628 * ```typescript 36629 * const metadata = await catalog.loadTable({ namespace: ['analytics'], name: 'events' }); 36630 * console.log(metadata.schema); 36631 * console.log(metadata.location); 36632 * ``` 36633 */ 36634 async loadTable(n) { 36635 return this.tableOps.loadTable(n); 36636 } 36637 /** 36638 * Checks if a namespace exists in the catalog. 36639 * 36640 * @param id - Namespace identifier to check 36641 * @returns True if the namespace exists, false otherwise 36642 * 36643 * @example 36644 * ```typescript 36645 * const exists = await catalog.namespaceExists({ namespace: ['analytics'] }); 36646 * console.log(exists); // true or false 36647 * ``` 36648 */ 36649 async namespaceExists(n) { 36650 return this.namespaceOps.namespaceExists(n); 36651 } 36652 /** 36653 * Checks if a table exists in the catalog. 36654 * 36655 * @param id - Table identifier to check 36656 * @returns True if the table exists, false otherwise 36657 * 36658 * @example 36659 * ```typescript 36660 * const exists = await catalog.tableExists({ namespace: ['analytics'], name: 'events' }); 36661 * console.log(exists); // true or false 36662 * ``` 36663 */ 36664 async tableExists(n) { 36665 return this.tableOps.tableExists(n); 36666 } 36667 /** 36668 * Creates a namespace if it does not exist. 36669 * 36670 * If the namespace already exists, returns void. If created, returns the response. 36671 * 36672 * @param id - Namespace identifier to create 36673 * @param metadata - Optional metadata properties for the namespace 36674 * @returns Response containing the created namespace and its properties, or void if it already exists 36675 * 36676 * @example 36677 * ```typescript 36678 * const response = await catalog.createNamespaceIfNotExists( 36679 * { namespace: ['analytics'] }, 36680 * { properties: { owner: 'data-team' } } 36681 * ); 36682 * if (response) { 36683 * console.log('Created:', response.namespace); 36684 * } else { 36685 * console.log('Already exists'); 36686 * } 36687 * ``` 36688 */ 36689 async createNamespaceIfNotExists(n, e) { 36690 return this.namespaceOps.createNamespaceIfNotExists(n, e); 36691 } 36692 /** 36693 * Creates a table if it does not exist. 36694 * 36695 * If the table already exists, returns its metadata instead. 36696 * 36697 * @param namespace - Namespace to create the table in 36698 * @param request - Table creation request including name, schema, partition spec, etc. 36699 * @returns Table metadata for the created or existing table 36700 * 36701 * @example 36702 * ```typescript 36703 * const metadata = await catalog.createTableIfNotExists( 36704 * { namespace: ['analytics'] }, 36705 * { 36706 * name: 'events', 36707 * schema: { 36708 * type: 'struct', 36709 * fields: [ 36710 * { id: 1, name: 'id', type: 'long', required: true }, 36711 * { id: 2, name: 'timestamp', type: 'timestamp', required: true } 36712 * ], 36713 * 'schema-id': 0 36714 * } 36715 * } 36716 * ); 36717 * ``` 36718 */ 36719 async createTableIfNotExists(n, e) { 36720 return this.tableOps.createTableIfNotExists(n, e); 36721 } 36722}; 36723function da(n) { 36724 "@babel/helpers - typeof"; 36725 return da = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(e) { 36726 return typeof e; 36727 }
36727 : function(e) { 36728 return e && typeof Symbol == "function" && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e; 36729 }, da(n); 36730} 36731function dT(n, e) { 36732 if (da(n) != "object" || !n) return n; 36733 var t = n[Symbol.toPrimitive]; 36734 if (t !== void 0) { 36735 var i = t.call(n, e); 36736 if (da(i) != "object") return i; 36737 throw new TypeError("@@toPrimitive must return a primitive value."); 36738 } 36739 return (e === "string" ? String : Number)(n); 36740} 36741function fT(n) { 36742 var e = dT(n, "string"); 36743 return da(e) == "symbol" ? e : e + ""; 36744} 36745function pT(n, e, t) { 36746 return (e = fT(e)) in n ? Object.defineProperty(n, e, { 36747 value: t, 36748 enumerable: !0, 36749 configurable: !0, 36750 writable: !0 36751 }) : n[e] = t, n; 36752} 36753function uf(n, e) { 36754 var t = Object.keys(n); 36755 if (Object.getOwnPropertySymbols) { 36756 var i = Object.getOwnPropertySymbols(n); 36757 e && (i = i.filter(function(r) { 36758 return Object.getOwnPropertyDescriptor(n, r).enumerable; 36759 })), t.push.apply(t, i); 36760 } 36761 return t; 36762} 36763function Ze(n) { 36764 for (var e = 1; e < arguments.length; e++) { 36765 var t = arguments[e] != null ? arguments[e] : {}; 36766 e % 2 ? uf(Object(t), !0).forEach(function(i) { 36767 pT(n, i, t[i]); 36768 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(n, Object.getOwnPropertyDescriptors(t)) : uf(Object(t)).forEach(function(i) { 36769 Object.defineProperty(n, i, Object.getOwnPropertyDescriptor(t, i)); 36770 }); 36771 } 36772 return n; 36773} 36774var el = class extends Error { 36775 constructor(n, e = "storage", t, i) { 36776 super(n), this.__isStorageError = !0, this.namespace = e, this.name = e === "vectors" ? "StorageVectorsError" : "StorageError", this.status = t, this.statusCode = i; 36777 } 36778 toJSON() { 36779 return { 36780 name: this.name, 36781 message: this.message, 36782 status: this.status, 36783 statusCode: this.statusCode 36784 }; 36785 } 36786}; 36787function tl(n) { 36788 return typeof n == "object" && n !== null && "__isStorageError" in n; 36789} 36790var hu = class extends el { 36791 constructor(n, e, t, i = "storage") { 36792 super(n, i, e, t), this.name = i === "vectors" ? "StorageVectorsApiError" : "StorageApiError", this.status = e, this.statusCode = t; 36793 } 36794 toJSON() { 36795 return Ze({}, super.toJSON()); 36796 } 36797}, Am = class extends el { 36798 constructor(n, e, t = "storage") { 36799 super(n, t), this.name = t === "vectors" ? "StorageVectorsUnknownError" : "StorageUnknownError", this.originalError = e; 36800 } 36801}; 36802function Uo(n, e, t) { 36803 const i = Ze({}, n), r = e.toLowerCase(); 36804 for (const s of Object.keys(i)) s.toLowerCase() === r && delete i[s]; 36805 return i[r] = t, i; 36806} 36807function mT(n) { 36808 const e = {}; 36809 for (const [t, i] of Object.entries(n)) e[t.toLowerCase()] = i; 36810 return e; 36811} 36812const gT = (n) => n ? (...e) => n(...e) : (...e) => fetch(...e), vT = (n) => { 36813 if (typeof n != "object" || n === null) return !1; 36814 const e = Object.getPrototypeOf(n); 36815 return (e === null || e === Object.prototype || Object.getPrototypeOf(e) === null) && !(Symbol.toStringTag in n) && !(Symbol.iterator in n); 36816}, du = (n) => { 36817 if (Array.isArray(n)) return n.map((t) => du(t)); 36818 if (typeof n == "function" || n !== Object(n)) return n; 36819 const e = {}; 36820 return Object.entries(n).forEach(([t, i]) => { 36821 const r = t.replace(/([-_][a-z])/gi, (s) => s.toUpperCase().replace(/[-_]/g, "")); 36822 e[r] = du(i); 36823 }), e; 36824}, _T = (n) => !n || typeof n != "string" || n.length === 0 || n.length > 100 || n.trim() !== n || n.includes("/") || n.includes("\\") ? !1 : /^[\w!.\*'() &$@=;:+,?-]+$/.test(n), hf = (n) => { 36825 if (typeof n == "object" && n !== null) { 36826 const e = n; 36827 if (typeof e.msg == "string") return e.msg; 36828 if (typeof e.message == "string") return e.message; 36829 if (typeof e.error_description == "string") return e.error_description; 36830 if (typeof e.error == "string") return e.error; 36831 if (typeof e.error == "object" && e.error !== null) { 36832 const t = e.error; 36833 if (typeof t.message == "string") return t.message; 36834 } 36835 } 36836 return JSON.stringify(n); 36837}, yT = async (n, e, t, i) => { 36838 if (n !== null && typeof n == "object" && "json" in n && typeof n.json == "function") { 36839 const r = n; 36840 let s = parseInt(String(r.status), 10); 36841 Number.isFinite(s) || (s = 500), r.json().then((a) => { 36842 const l = a?.statusCode || a?.code || s + ""; 36843 e(new hu(hf(a), s, l, i)); 36844 }).catch(() => { 36845 const a = s + ""; 36846 e(new hu(r.statusText || `HTTP ${s} error`, s, a, i)); 36847 }); 36848 } else e(new Am(hf(n), n, i)); 36849}, xT = (n, e, t, i) => { 36850 const r = { 36851 method: n, 36852 headers: e?.headers || {} 36853 }; 36854 if (n === "GET" || n === "HEAD" || !i) return Ze(Ze({}, r), t); 36855 if (vT(i)) { 36856 var s; 36857 const a = e?.headers || {}; 36858 let l; 36859 for (const [o, c] of Object.entries(a)) o.toLowerCase() === "content-type" && (l = c); 36860 r.headers = Uo(a, "Content-Type", (s = l) !== null && s !== void 0 ? s : "application/json"), r.body = JSON.stringify(i); 36861 } else r.body = i; 36862 return e?.duplex && (r.duplex = e.duplex), Ze(Ze({}, r), t); 36863}; 36864async function Gs(n, e, t, i, r, s, a) { 36865 return new Promise((l, o) => { 36866 n(t, xT(e, i, r, s)).then((c) => { 36867 if (!c.ok) throw c; 36868 if (i?.noResolveJson) return c; 36869 if (a === "vectors") { 36870 const u = c.headers.get("content-type"); 36871 if (c.headers.get("content-length") === "0" || c.status === 204) return {}; 36872 if (!u || !u.includes("application/json")) return {}; 36873 } 36874 return c.json(); 36875 }).then((c) => l(c)).catch((c) => yT(c, o, i, a)); 36876 }); 36877} 36878function Rm(n = "storage") { 36879 return { 36880 get: async (e, t, i, r) => Gs(e, "GET", t, i, r, void 0, n), 36881 post: async (e, t, i, r, s) => Gs(e, "POST", t, r, s, i, n), 36882 put: async (e, t, i, r, s) => Gs(e, "PUT", t, r, s, i, n), 36883 head: async (e, t, i, r) => Gs(e, "HEAD", t, Ze(Ze({}, i), {}, { noResolveJson: !0 }), r, void 0, n), 36884 remove: async (e, t, i, r, s) => Gs(e, "DELETE", t, r, s, i, n) 36885 }; 36886} 36887const bT = Rm("storage"), { get: fa, post: Jn, put: fu, head: wT, remove: nh } = bT, Ln = Rm("vectors"); 36888var Rs = class { 36889 /** 36890 * Creates a new BaseApiClient instance 36891 * @param url - Base URL for API requests 36892 * @param headers - Default headers for API requests 36893 * @param fetch - Optional custom fetch implementation 36894 * @param namespace - Error namespace ('storage' or 'vectors') 36895 */ 36896 constructor(n, e = {}, t, i = "storage") { 36897 this.shouldThrowOnError = !1, this.url = n, this.headers = mT(e), this.fetch = gT(t), this.namespace = i; 36898 } 36899 /** 36900 * Enable throwing errors instead of returning them. 36901 * When enabled, errors are thrown instead of returned in { data, error } format. 36902 * 36903 * @returns this - For method chaining 36904 */ 36905 throwOnError() { 36906 return this.shouldThrowOnError = !0, this; 36907 } 36908 /** 36909 * Set an HTTP header for the request. 36910 * Creates a shallow copy of headers to avoid mutating shared state. 36911 * 36912 * @param name - Header name 36913 * @param value - Header value 36914 * @returns this - For method chaining 36915 */ 36916 setHeader(n, e) { 36917 return this.headers = Uo(this.headers, n, e), this; 36918 } 36919 /** 36920 * Handles API operation with standardized error handling 36921 * Eliminates repetitive try-catch blocks across all API methods 36922 * 36923 * This wrapper: 36924 * 1. Executes the operation 36925 * 2. Returns { data, error: null } on success 36926 * 3. Returns { data: null, error } on failure (if shouldThrowOnError is false) 36927 * 4. Throws error on failure (if shouldThrowOnError is true) 36928 * 36929 * @typeParam T - The expected data type from the operation 36930 * @param operation - Async function that performs the API call 36931 * @returns Promise with { data, error } tuple 36932 * 36933 * @example Handling an operation 36934 * ```typescript 36935 * async listBuckets() { 36936 * return this.handleOperation(async () => { 36937 * return await get(this.fetch, `${this.url}/bucket`, { 36938 * headers: this.headers, 36939 * }) 36940 * }) 36941 * } 36942 * ``` 36943 */ 36944 async handleOperation(n) { 36945 var e = this; 36946 try { 36947 return { 36948 data: await n(), 36949 error: null 36950 }; 36951 } catch (t) { 36952 if (e.shouldThrowOnError) throw t; 36953 if (tl(t)) return { 36954 data: null, 36955 error: t 36956 }; 36957 throw t; 36958 } 36959 } 36960}; 36961let Cm; 36962Cm = Symbol.toStringTag; 36963var ST = class { 36964 constructor(n, e) { 36965 this.downloadFn = n, this.shouldThrowOnError = e, this[Cm] = "StreamDownloadBuilder", this.promise = null; 36966 } 36967 then(n, e) { 36968 return this.getPromise().then(n, e); 36969 }
36970 catch(n) { 36971 return this.getPromise().catch(n); 36972 } 36973 finally(n) { 36974 return this.getPromise().finally(n); 36975 } 36976 getPromise() { 36977 return this.promise || (this.promise = this.execute()), this.promise; 36978 } 36979 async execute() { 36980 var n = this; 36981 try { 36982 return { 36983 data: (await n.downloadFn()).body, 36984 error: null 36985 }; 36986 } catch (e) { 36987 if (n.shouldThrowOnError) throw e; 36988 if (tl(e)) return { 36989 data: null, 36990 error: e 36991 }; 36992 throw e; 36993 } 36994 } 36995}; 36996let Pm; 36997Pm = Symbol.toStringTag; 36998var ET = class { 36999 constructor(n, e) { 37000 this.downloadFn = n, this.shouldThrowOnError = e, this[Pm] = "BlobDownloadBuilder", this.promise = null; 37001 } 37002 asStream() { 37003 return new ST(this.downloadFn, this.shouldThrowOnError); 37004 } 37005 then(n, e) { 37006 return this.getPromise().then(n, e); 37007 } 37008 catch(n) { 37009 return this.getPromise().catch(n); 37010 } 37011 finally(n) { 37012 return this.getPromise().finally(n); 37013 } 37014 getPromise() { 37015 return this.promise || (this.promise = this.execute()), this.promise; 37016 } 37017 async execute() { 37018 var n = this; 37019 try { 37020 return { 37021 data: await (await n.downloadFn()).blob(), 37022 error: null 37023 }; 37024 } catch (e) { 37025 if (n.shouldThrowOnError) throw e; 37026 if (tl(e)) return { 37027 data: null, 37028 error: e 37029 }; 37030 throw e; 37031 } 37032 } 37033}; 37034const MT = { 37035 limit: 100, 37036 offset: 0, 37037 sortBy: { 37038 column: "name", 37039 order: "asc" 37040 } 37041}, df = { 37042 cacheControl: "3600", 37043 contentType: "text/plain;charset=UTF-8", 37044 upsert: !1 37045}; 37046var TT = class extends Rs { 37047 constructor(n, e = {}, t, i) { 37048 super(n, e, i, "storage"), this.bucketId = t; 37049 } 37050 /** 37051 * Uploads a file to an existing bucket or replaces an existing file at the specified path with a new one. 37052 * 37053 * @param method HTTP method. 37054 * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. 37055 * @param fileBody The body of the file to be stored in the bucket. 37056 */ 37057 async uploadOrUpdate(n, e, t, i) { 37058 var r = this; 37059 return r.handleOperation(async () => { 37060 let s; 37061 const a = Ze(Ze({}, df), i); 37062 let l = Ze(Ze({}, r.headers), n === "POST" && { "x-upsert": String(a.upsert) }); 37063 const o = a.metadata; 37064 if (typeof Blob < "u" && t instanceof Blob ? (s = new FormData(), s.append("cacheControl", a.cacheControl), o && s.append("metadata", r.encodeMetadata(o)), s.append("", t)) : typeof FormData < "u" && t instanceof FormData ? (s = t, s.has("cacheControl") || s.append("cacheControl", a.cacheControl), o && !s.has("metadata") && s.append("metadata", r.encodeMetadata(o))) : (s = t, l["cache-control"] = `max-age=${a.cacheControl}`, l["content-type"] = a.contentType, o && (l["x-metadata"] = r.toBase64(r.encodeMetadata(o))), (typeof ReadableStream < "u" && s instanceof ReadableStream || s && typeof s == "object" && "pipe" in s && typeof s.pipe == "function") && !a.duplex && (a.duplex = "half")), i?.headers) for (const [d, f] of Object.entries(i.headers)) l = Uo(l, d, f); 37065 const c = r._removeEmptyFolders(e), u = r._getFinalPath(c), h = await (n == "PUT" ? fu : Jn)(r.fetch, `${r.url}/object/${u}`, s, Ze({ headers: l }, a?.duplex ? { duplex: a.duplex } : {})); 37066 return { 37067 path: c, 37068 id: h.Id, 37069 fullPath: h.Key 37070 }; 37071 }); 37072 } 37073 /** 37074 * Uploads a file to an existing bucket. 37075 * 37076 * @category Storage 37077 * @subcategory File Buckets 37078 * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. 37079 * @param fileBody The body of the file to be stored in the bucket. 37080 * @param fileOptions Optional file upload options including cacheControl, contentType, upsert, and metadata. 37081 * @returns Promise with response containing file path, id, and fullPath or error 37082 * 37083 * @example Upload file 37084 * ```js 37085 * const avatarFile = event.target.files[0] 37086 * const { data, error } = await supabase 37087 * .storage 37088 * .from('avatars') 37089 * .upload('public/avatar1.png', avatarFile, { 37090 * cacheControl: '3600', 37091 * upsert: false 37092 * }) 37093 * ``` 37094 * 37095 * Response: 37096 * ```json 37097 * { 37098 * "data": { 37099 * "path": "public/avatar1.png", 37100 * "fullPath": "avatars/public/avatar1.png" 37101 * }, 37102 * "error": null 37103 * } 37104 * ``` 37105 * 37106 * @example Upload file using `ArrayBuffer` from base64 file data 37107 * ```js 37108 * import { decode } from 'base64-arraybuffer' 37109 * 37110 * const { data, error } = await supabase 37111 * .storage 37112 * .from('avatars') 37113 * .upload('public/avatar1.png', decode('base64FileData'), { 37114 * contentType: 'image/png' 37115 * }) 37116 * ``` 37117 * 37118 * @example Handling errors 37119 * ```js 37120 * const { data, error } = await supabase 37121 * .storage 37122 * .from('avatars') 37123 * .upload('public/avatar1.png', avatarFile) 37124 * 37125 * if (error) { 37126 * // Log the full error so fields like `statusCode` and `error` (the 37127 * // Storage error name, e.g. "Duplicate") aren't hidden behind `error.message`. 37128 * console.error(error) 37129 * return 37130 * } 37131 * ``` 37132 * 37133 * @remarks 37134 * - RLS policy permissions required: 37135 * - `buckets` table permissions: none 37136 * - `objects` table permissions: only `insert` when you are uploading new files and `select`, `insert` and `update` when you are upserting files 37137 * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works 37138 * - For React Native, using either `Blob`, `File` or `FormData` does not work as intended. Upload file using `ArrayBuffer` from base64 file data instead, see example below.
37139 */ 37140 async upload(n, e, t) { 37141 return this.uploadOrUpdate("POST", n, e, t); 37142 } 37143 /** 37144 * Upload a file with a token generated from `createSignedUploadUrl`. 37145 * 37146 * @category Storage 37147 * @subcategory File Buckets 37148 * @param path The file path, including the file name. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to upload. 37149 * @param token The token generated from `createSignedUploadUrl` 37150 * @param fileBody The body of the file to be stored in the bucket. 37151 * @param fileOptions HTTP headers (cacheControl, contentType, etc.). 37152 * **Note:** The `upsert` option has no effect here. To enable upsert behavior, 37153 * pass `{ upsert: true }` when calling `createSignedUploadUrl()` instead. 37154 * @returns Promise with response containing file path and fullPath or error 37155 * 37156 * @example Upload to a signed URL 37157 * ```js 37158 * const { data, error } = await supabase 37159 * .storage 37160 * .from('avatars') 37161 * .uploadToSignedUrl('folder/cat.jpg', 'token-from-createSignedUploadUrl', file) 37162 * ``` 37163 * 37164 * Response: 37165 * ```json 37166 * { 37167 * "data": { 37168 * "path": "folder/cat.jpg", 37169 * "fullPath": "avatars/folder/cat.jpg" 37170 * }, 37171 * "error": null 37172 * } 37173 * ``` 37174 * 37175 * @remarks 37176 * - RLS policy permissions required: 37177 * - `buckets` table permissions: none 37178 * - `objects` table permissions: none 37179 * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works 37180 */ 37181 async uploadToSignedUrl(n, e, t, i) { 37182 var r = this; 37183 const s = r._removeEmptyFolders(n), a = r._getFinalPath(s), l = new URL(r.url + `/object/upload/sign/${a}`); 37184 return l.searchParams.set("token", e), r.handleOperation(async () => { 37185 let o; 37186 const c = Ze(Ze({}, df), i); 37187 let u = Ze(Ze({}, r.headers), { "x-upsert": String(c.upsert) }); 37188 const h = c.metadata; 37189 if (typeof Blob < "u" && t instanceof Blob ? (o = new FormData(), o.append("cacheControl", c.cacheControl), h && o.append("metadata", r.encodeMetadata(h)), o.append("", t)) : typeof FormData < "u" && t instanceof FormData ? (o = t, o.has("cacheControl") || o.append("cacheControl", c.cacheControl), h && !o.has("metadata") && o.append("metadata", r.encodeMetadata(h))) : (o = t, u["cache-control"] = `max-age=${c.cacheControl}`, u["content-type"] = c.contentType, h && (u["x-metadata"] = r.toBase64(r.encodeMetadata(h))), (typeof ReadableStream < "u" && o instanceof ReadableStream || o && typeof o == "object" && "pipe" in o && typeof o.pipe == "function") && !c.duplex && (c.duplex = "half")), i?.headers) for (const [d, f] of Object.entries(i.headers)) u = Uo(u, d, f); 37190 return { 37191 path: s, 37192 fullPath: (await fu(r.fetch, l.toString(), o, Ze({ headers: u }, c?.duplex ? { duplex: c.duplex } : {}))).Key 37193 }; 37194 }); 37195 } 37196 /** 37197 * Creates a signed upload URL. 37198 * Signed upload URLs can be used to upload files to the bucket without further authentication. 37199 * They are valid for 2 hours. 37200 * 37201 * @category Storage 37202 * @subcategory File Buckets 37203 * @param path The file path, including the current file name. For example `folder/image.png`. 37204 * @param options.upsert If set to true, allows the file to be overwritten if it already exists. 37205 * @returns Promise with response containing signed upload URL, token, and path or error 37206 * 37207 * @example Create Signed Upload URL 37208 * ```js 37209 * const { data, error } = await supabase 37210 * .storage 37211 * .from('avatars') 37212 * .createSignedUploadUrl('folder/cat.jpg') 37213 * ``` 37214 * 37215 * Response: 37216 * ```json 37217 * { 37218 * "data": { 37219 * "signedUrl": "https://example.supabase.co/storage/v1/object/upload/sign/avatars/folder/cat.jpg?token=<TOKEN>", 37220 * "path": "folder/cat.jpg", 37221 * "token": "<TOKEN>" 37222 * }, 37223 * "error": null 37224 * } 37225 * ``` 37226 * 37227 * @remarks 37228 * - RLS policy permissions required: 37229 * - `buckets` table permissions: none 37230 * - `objects` table permissions: `insert` 37231 * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works 37232 */ 37233 async createSignedUploadUrl(n, e) { 37234 var t = this; 37235 return t.handleOperation(async () => { 37236 let i = t._getFinalPath(n); 37237 const r = Ze({}, t.headers); 37238 e?.upsert && (r["x-upsert"] = "true"); 37239 const s = await Jn(t.fetch, `${t.url}/object/upload/sign/${i}`, {}, { headers: r }), a = new URL(t.url + s.url), l = a.searchParams.get("token"); 37240 if (!l) throw new el("No token returned by API"); 37241 return { 37242 signedUrl: a.toString(), 37243 path: n, 37244 token: l 37245 }; 37246 }); 37247 } 37248 /** 37249 * Replaces an existing file at the specified path with a new one. 37250 * 37251 * @category Storage 37252 * @subcategory File Buckets 37253 * @param path The relative file path. Should be of the format `folder/subfolder/filename.png`. The bucket must already exist before attempting to update. 37254 * @param fileBody The body of the file to be stored in the bucket. 37255 * @param fileOptions Optional file upload options including cacheControl, contentType, and metadata. 37256 * **Note:** The `upsert` option has no effect here. `update()` always replaces the 37257 * file at the given path, so the `x-upsert` header is not sent. To control upsert 37258 * behavior, use `upload()` instead. 37259 * @returns Promise with response containing file path, id, and fullPath or error 37260 * 37261 * @example Update file 37262 * ```js 37263 * const avatarFile = event.target.files[0] 37264 * const { data, error } = await supabase 37265 * .storage 37266 * .from('avatars') 37267 * .update('public/avatar1.png', avatarFile, { 37268 * cacheControl: '3600' 37269 * }) 37270 * ``` 37271 * 37272 * Response: 37273 * ```json 37274 * { 37275 * "data": { 37276 * "path": "public/avatar1.png", 37277 * "fullPath": "avatars/public/avatar1.png" 37278 * }, 37279 * "error": null 37280 * } 37281 * ``` 37282 * 37283 * @example Update file using `ArrayBuffer` from base64 file data 37284 * ```js 37285 * import {decode} from 'base64-arraybuffer' 37286 * 37287 * const { data, error } = await supabase 37288 * .storage 37289 * .from('avatars') 37290 * .update('public/avatar1.png', decode('base64FileData'), { 37291 * contentType: 'image/png' 37292 * }) 37293 * ``` 37294 * 37295 * @remarks 37296 * - RLS policy permissions required: 37297 * - `buckets` table permissions: none 37298 * - `objects` table permissions: `update` and `select` 37299 * - `update()` always replaces the file at the given path regardless of the `upsert` option. 37300 * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works 37301 * - For React Native, using either `Blob`, `File` or `FormData` does not work as intended. Update file using `ArrayBuffer` from base64 file data instead, see example below.
37302 */ 37303 async update(n, e, t) { 37304 return this.uploadOrUpdate("PUT", n, e, t); 37305 } 37306 /** 37307 * Moves an existing file to a new path in the same bucket. 37308 * 37309 * @category Storage 37310 * @subcategory File Buckets 37311 * @param fromPath The original file path, including the current file name. For example `folder/image.png`. 37312 * @param toPath The new file path, including the new file name. For example `folder/image-new.png`. 37313 * @param options The destination options. 37314 * @returns Promise with response containing success message or error 37315 * 37316 * @example Move file 37317 * ```js 37318 * const { data, error } = await supabase 37319 * .storage 37320 * .from('avatars') 37321 * .move('public/avatar1.png', 'private/avatar2.png') 37322 * ``` 37323 * 37324 * Response: 37325 * ```json 37326 * { 37327 * "data": { 37328 * "message": "Successfully moved" 37329 * }, 37330 * "error": null 37331 * } 37332 * ``` 37333 * 37334 * @remarks 37335 * - RLS policy permissions required: 37336 * - `buckets` table permissions: none 37337 * - `objects` table permissions: `update` and `select` 37338 * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works 37339 */ 37340 async move(n, e, t) { 37341 var i = this; 37342 return i.handleOperation(async () => await Jn(i.fetch, `${i.url}/object/move`, { 37343 bucketId: i.bucketId, 37344 sourceKey: n, 37345 destinationKey: e, 37346 destinationBucket: t?.destinationBucket 37347 }, { headers: i.headers })); 37348 } 37349 /** 37350 * Copies an existing file to a new path in the same bucket. 37351 * 37352 * @category Storage 37353 * @subcategory File Buckets 37354 * @param fromPath The original file path, including the current file name. For example `folder/image.png`. 37355 * @param toPath The new file path, including the new file name. For example `folder/image-copy.png`. 37356 * @param options The destination options. 37357 * @returns Promise with response containing copied file path or error 37358 * 37359 * @example Copy file 37360 * ```js 37361 * const { data, error } = await supabase 37362 * .storage 37363 * .from('avatars') 37364 * .copy('public/avatar1.png', 'private/avatar2.png') 37365 * ``` 37366 * 37367 * Response: 37368 * ```json 37369 * { 37370 * "data": { 37371 * "path": "avatars/private/avatar2.png" 37372 * }, 37373 * "error": null 37374 * } 37375 * ``` 37376 * 37377 * @remarks 37378 * - RLS policy permissions required: 37379 * - `buckets` table permissions: none 37380 * - `objects` table permissions: `insert` and `select` 37381 * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works 37382 */ 37383 async copy(n, e, t) { 37384 var i = this; 37385 return i.handleOperation(async () => ({ path: (await Jn(i.fetch, `${i.url}/object/copy`, { 37386 bucketId: i.bucketId, 37387 sourceKey: n, 37388 destinationKey: e, 37389 destinationBucket: t?.destinationBucket 37390 }, { headers: i.headers })).Key })); 37391 } 37392 /** 37393 * Creates a signed URL. Use a signed URL to share a file for a fixed amount of time. 37394 * 37395 * @category Storage 37396 * @subcategory File Buckets 37397 * @param path The file path, including the current file name. For example `folder/image.png`. 37398 * @param expiresIn The number of seconds until the signed URL expires. For example, `60` for a URL which is valid for one minute. 37399 * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. 37400 * @param options.transform Transform the asset before serving it to the client. 37401 * @param options.cacheNonce Append a cache nonce parameter to the URL to invalidate the cache. 37402 * @returns Promise with response containing signed URL or error 37403 * 37404 * @example Create Signed URL 37405 * ```js 37406 * const { data, error } = await supabase 37407 * .storage 37408 * .from('avatars') 37409 * .createSignedUrl('folder/avatar1.png', 60) 37410 * ``` 37411 * 37412 * Response: 37413 * ```json 37414 * { 37415 * "data": { 37416 * "signedUrl": "https://example.supabase.co/storage/v1/object/sign/avatars/folder/avatar1.png?token=<TOKEN>" 37417 * }, 37418 * "error": null 37419 * } 37420 * ``` 37421 * 37422 * @example Create a signed URL for an asset with transformations 37423 * ```js 37424 * const { data } = await supabase 37425 * .storage 37426 * .from('avatars') 37427 * .createSignedUrl('folder/avatar1.png', 60, { 37428 * transform: { 37429 * width: 100, 37430 * height: 100, 37431 * } 37432 * }) 37433 * ``` 37434 * 37435 * @example Create a signed URL which triggers the download of the asset 37436 * ```js 37437 * const { data } = await supabase 37438 * .storage 37439 * .from('avatars') 37440 * .createSignedUrl('folder/avatar1.png', 60, { 37441 * download: true, 37442 * }) 37443 * ``` 37444 * 37445 * @remarks 37446 * - RLS policy permissions required: 37447 * - `buckets` table permissions: none 37448 * - `objects` table permissions: `select` 37449 * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works 37450 */ 37451 async createSignedUrl(n, e, t) { 37452 var i = this; 37453 return i.handleOperation(async () => { 37454 let r = i._getFinalPath(n); 37455 const s = typeof t?.transform == "object" && t.transform !== null && Object.keys(t.transform).length > 0; 37456 let a = await Jn(i.fetch, `${i.url}/object/sign/${r}`, Ze({ expiresIn: e }, s ? { transform: t.transform } : {}), { headers: i.headers }); 37457 const l = new URLSearchParams(); 37458 t?.download && l.set("download", t.download === !0 ? "" : t.download), t?.cacheNonce != null && l.set("cacheNonce", String(t.cacheNonce)); 37459 const o = l.toString(); 37460 return { signedUrl: encodeURI(`${i.url}${a.signedURL}${o ? `&${o}` : ""}`) }; 37461 }); 37462 } 37463 /** 37464 * Creates multiple signed URLs. Use a signed URL to share a file for a fixed amount of time. 37465 * 37466 * @category Storage 37467 * @subcategory File Buckets 37468 * @param paths The file paths to be downloaded, including the current file names. For example `['folder/image.png', 'folder2/image2.png']`. 37469 * @param expiresIn The number of seconds until the signed URLs expire. For example, `60` for URLs which are valid for one minute. 37470 * @param options.download triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. 37471 * @param options.cacheNonce Append a cache nonce parameter to the URL to invali
37471date the cache. 37472 * @returns Promise with response containing array of objects with signedUrl, path, and error or error 37473 * 37474 * @example Create Signed URLs 37475 * ```js 37476 * const { data, error } = await supabase 37477 * .storage 37478 * .from('avatars') 37479 * .createSignedUrls(['folder/avatar1.png', 'folder/avatar2.png'], 60) 37480 * ``` 37481 * 37482 * Response: 37483 * ```json 37484 * { 37485 * "data": [ 37486 * { 37487 * "error": null, 37488 * "path": "folder/avatar1.png", 37489 * "signedURL": "/object/sign/avatars/folder/avatar1.png?token=<TOKEN>", 37490 * "signedUrl": "https://example.supabase.co/storage/v1/object/sign/avatars/folder/avatar1.png?token=<TOKEN>" 37491 * }, 37492 * { 37493 * "error": null, 37494 * "path": "folder/avatar2.png", 37495 * "signedURL": "/object/sign/avatars/folder/avatar2.png?token=<TOKEN>", 37496 * "signedUrl": "https://example.supabase.co/storage/v1/object/sign/avatars/folder/avatar2.png?token=<TOKEN>" 37497 * } 37498 * ], 37499 * "error": null 37500 * } 37501 * ``` 37502 * 37503 * @remarks 37504 * - RLS policy permissions required: 37505 * - `buckets` table permissions: none 37506 * - `objects` table permissions: `select` 37507 * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works 37508 */ 37509 async createSignedUrls(n, e, t) { 37510 var i = this; 37511 return i.handleOperation(async () => { 37512 const r = await Jn(i.fetch, `${i.url}/object/sign/${i.bucketId}`, { 37513 expiresIn: e, 37514 paths: n 37515 }, { headers: i.headers }), s = new URLSearchParams(); 37516 t?.download && s.set("download", t.download === !0 ? "" : t.download), t?.cacheNonce != null && s.set("cacheNonce", String(t.cacheNonce)); 37517 const a = s.toString(); 37518 return r.map((l) => Ze(Ze({}, l), {}, { signedUrl: l.signedURL ? encodeURI(`${i.url}${l.signedURL}${a ? `&${a}` : ""}`) : null })); 37519 }); 37520 } 37521 /** 37522 * Downloads a file from a private bucket. For public buckets, make a request to the URL returned from `getPublicUrl` instead. 37523 * 37524 * @category Storage 37525 * @subcategory File Buckets 37526 * @param path The full path and file name of the file to be downloaded. For example `folder/image.png`. 37527 * @param options.transform Transform the asset before serving it to the client. 37528 * @param options.cacheNonce Append a cache nonce parameter to the URL to invalidate the cache. 37529 * @param parameters Additional fetch parameters like signal for cancellation. Supports standard fetch options including cache control. 37530 * @returns BlobDownloadBuilder instance for downloading the file 37531 * 37532 * @example Download file 37533 * ```js 37534 * const { data, error } = await supabase 37535 * .storage 37536 * .from('avatars') 37537 * .download('folder/avatar1.png') 37538 * ``` 37539 * 37540 * Response: 37541 * ```json 37542 * { 37543 * "data": <BLOB>, 37544 * "error": null 37545 * } 37546 * ``` 37547 * 37548 * @example Download file with transformations 37549 * ```js 37550 * const { data, error } = await supabase 37551 * .storage 37552 * .from('avatars') 37553 * .download('folder/avatar1.png', { 37554 * transform: { 37555 * width: 100, 37556 * height: 100, 37557 * quality: 80 37558 * } 37559 * }) 37560 * ``` 37561 * 37562 * @example Download with cache control (useful in Edge Functions) 37563 * ```js 37564 * const { data, error } = await supabase 37565 * .storage 37566 * .from('avatars') 37567 * .download('folder/avatar1.png', {}, { cache: 'no-store' }) 37568 * ``` 37569 * 37570 * @example Download with abort signal 37571 * ```js 37572 * const controller = new AbortController() 37573 * setTimeout(() => controller.abort(), 5000) 37574 * 37575 * const { data, error } = await supabase 37576 * .storage 37577 * .from('avatars') 37578 * .download('folder/avatar1.png', {}, { signal: controller.signal }) 37579 * ``` 37580 * 37581 * @remarks 37582 * - RLS policy permissions required: 37583 * - `buckets` table permissions: none 37584 * - `objects` table permissions: `select` 37585 * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works 37586 */ 37587 download(n, e, t) { 37588 const i = typeof e?.transform == "object" && e.transform !== null && Object.keys(e.transform).length > 0 ? "render/image/authenticated" : "object", r = new URLSearchParams(); 37589 e?.transform && this.applyTransformOptsToQuery(r, e.transform), e?.cacheNonce != null && r.set("cacheNonce", String(e.cacheNonce)); 37590 const s = r.toString(), a = this._getFinalPath(n), l = () => fa(this.fetch, `${this.url}/${i}/${a}${s ? `?${s}` : ""}`, { 37591 headers: this.headers, 37592 noResolveJson: !0 37593 }, t); 37594 return new ET(l, this.shouldThrowOnError); 37595 } 37596 /** 37597 * Retrieves the details of an existing file. 37598 * 37599 * Returns detailed file metadata including size, content type, and timestamps. 37600 * Note: The API returns `last_modified` field, not `updated_at`. 37601 * 37602 * @category Storage 37603 * @subcategory File Buckets 37604 * @param path The file path, including the file name. For example `folder/image.png`. 37605 * @returns Promise with response containing file metadata or error 37606 * 37607 * @example Get file info 37608 * ```js 37609 * const { data, error } = await supabase 37610 * .storage 37611 * .from('avatars') 37612 * .info('folder/avatar1.png') 37613 * 37614 * if (data) { 37615 * console.log('Last modified:', data.lastModified)
37616 * console.log('Size:', data.size) 37617 * } 37618 * ``` 37619 */ 37620 async info(n) { 37621 var e = this; 37622 const t = e._getFinalPath(n); 37623 return e.handleOperation(async () => du(await fa(e.fetch, `${e.url}/object/info/${t}`, { headers: e.headers }))); 37624 } 37625 /** 37626 * Checks the existence of a file. 37627 * 37628 * @category Storage 37629 * @subcategory File Buckets 37630 * @param path The file path, including the file name. For example `folder/image.png`. 37631 * @returns Promise with response containing boolean indicating file existence or error 37632 * 37633 * @example Check file existence 37634 * ```js 37635 * const { data, error } = await supabase 37636 * .storage 37637 * .from('avatars') 37638 * .exists('folder/avatar1.png') 37639 * ``` 37640 */ 37641 async exists(n) { 37642 var e = this; 37643 const t = e._getFinalPath(n); 37644 try { 37645 return await wT(e.fetch, `${e.url}/object/${t}`, { headers: e.headers }), { 37646 data: !0, 37647 error: null 37648 }; 37649 } catch (r) { 37650 if (e.shouldThrowOnError) throw r; 37651 if (tl(r)) { 37652 var i; 37653 const s = r instanceof hu ? r.status : r instanceof Am ? (i = r.originalError) === null || i === void 0 ? void 0 : i.status : void 0; 37654 if (s !== void 0 && [400, 404].includes(s)) return { 37655 data: !1, 37656 error: r 37657 }; 37658 } 37659 throw r; 37660 } 37661 } 37662 /** 37663 * A simple convenience function to get the URL for an asset in a public bucket. If you do not want to use this function, you can construct the public URL by concatenating the bucket URL with the path to the asset. 37664 * This function does not verify if the bucket is public. If a public URL is created for a bucket which is not public, you will not be able to download the asset. 37665 * 37666 * @category Storage 37667 * @subcategory File Buckets 37668 * @param path The path and name of the file to generate the public URL for. For example `folder/image.png`. 37669 * @param options.download Triggers the file as a download if set to true. Set this parameter as the name of the file if you want to trigger the download with a different filename. 37670 * @param options.transform Transform the asset before serving it to the client. 37671 * @param options.cacheNonce Append a cache nonce parameter to the URL to invalidate the cache. 37672 * @returns Object with public URL 37673 * 37674 * @example Returns the URL for an asset in a public bucket 37675 * ```js 37676 * const { data } = supabase 37677 * .storage 37678 * .from('public-bucket') 37679 * .getPublicUrl('folder/avatar1.png') 37680 * ``` 37681 * 37682 * Response: 37683 * ```json 37684 * { 37685 * "data": { 37686 * "publicUrl": "https://example.supabase.co/storage/v1/object/public/public-bucket/folder/avatar1.png" 37687 * } 37688 * } 37689 * ``` 37690 * 37691 * @example Returns the URL for an asset in a public bucket with transformations 37692 * ```js 37693 * const { data } = supabase 37694 * .storage 37695 * .from('public-bucket') 37696 * .getPublicUrl('folder/avatar1.png', { 37697 * transform: { 37698 * width: 100, 37699 * height: 100, 37700 * } 37701 * }) 37702 * ``` 37703 * 37704 * @example Returns the URL which triggers the download of an asset in a public bucket 37705 * ```js 37706 * const { data } = supabase 37707 * .storage 37708 * .from('public-bucket') 37709 * .getPublicUrl('folder/avatar1.png', { 37710 * download: true, 37711 * }) 37712 * ``` 37713 * 37714 * @remarks 37715 * - The bucket needs to be set to public, either via [updateBucket()](/docs/reference/javascript/storage-updatebucket) or by going to Storage on [supabase.com/dashboard](https://supabase.com/dashboard), clicking the overflow menu on a bucket and choosing "Make public" 37716 * - RLS policy permissions required: 37717 * - `buckets` table permissions: none 37718 * - `objects` table permissions: none 37719 * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works 37720 */ 37721 getPublicUrl(n, e) { 37722 const t = this._getFinalPath(n), i = new URLSearchParams(); 37723 e?.download && i.set("download", e.download === !0 ? "" : e.download), e?.transform && this.applyTransformOptsToQuery(i, e.transform), e?.cacheNonce != null && i.set("cacheNonce", String(e.cacheNonce)); 37724 const r = i.toString(), s = typeof e?.transform == "object" && e.transform !== null && Object.keys(e.transform).length > 0 ? "render/image" : "object"; 37725 return { data: { publicUrl: encodeURI(`${this.url}/${s}/public/${t}`) + (r ? `?${r}` : "") } }; 37726 } 37727 /** 37728 * Deletes files within the same bucket 37729 * 37730 * Returns an array of FileObject entries for the deleted files. Note that deprecated 37731 * fields like `bucket_id` may or may not be present in the response - do not rely on them. 37732 * 37733 * @category Storage 37734 * @subcategory File Buckets 37735 * @param paths An array of files to delete, including the path and file name. For example [`'folder/image.png'`].
37736 * @returns Promise with response containing array of deleted file objects or error 37737 * 37738 * @example Delete file 37739 * ```js 37740 * const { data, error } = await supabase 37741 * .storage 37742 * .from('avatars') 37743 * .remove(['folder/avatar1.png']) 37744 * ``` 37745 * 37746 * Response: 37747 * ```json 37748 * { 37749 * "data": [], 37750 * "error": null 37751 * } 37752 * ``` 37753 * 37754 * @remarks 37755 * - RLS policy permissions required: 37756 * - `buckets` table permissions: none 37757 * - `objects` table permissions: `delete` and `select` 37758 * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works 37759 */ 37760 async remove(n) { 37761 var e = this; 37762 return e.handleOperation(async () => await nh(e.fetch, `${e.url}/object/${e.bucketId}`, { prefixes: n }, { headers: e.headers })); 37763 } 37764 /** 37765 * Get file metadata 37766 * @param id the file id to retrieve metadata 37767 */ 37768 /** 37769 * Update file metadata 37770 * @param id the file id to update metadata 37771 * @param meta the new file metadata 37772 */ 37773 /** 37774 * Lists all the files and folders within a path of the bucket. 37775 * 37776 * **Important:** For folder entries, fields like `id`, `updated_at`, `created_at`, 37777 * `last_accessed_at`, and `metadata` will be `null`. Only files have these fields populated. 37778 * Additionally, deprecated fields like `bucket_id`, `owner`, and `buckets` are NOT returned 37779 * by this method. 37780 * 37781 * @category Storage 37782 * @subcategory File Buckets 37783 * @param path The folder path. 37784 * @param options Search options including limit (defaults to 100), offset, sortBy, and search 37785 * @param parameters Optional fetch parameters including signal for cancellation 37786 * @returns Promise with response containing array of files/folders or error 37787 * 37788 * @example List files in a bucket 37789 * ```js 37790 * const { data, error } = await supabase 37791 * .storage 37792 * .from('avatars') 37793 * .list('folder', { 37794 * limit: 100, 37795 * offset: 0, 37796 * sortBy: { column: 'name', order: 'asc' }, 37797 * }) 37798 * 37799 * // Handle files vs folders 37800 * data?.forEach(item => { 37801 * if (item.id !== null) { 37802 * // It's a file 37803 * console.log('File:', item.name, 'Size:', item.metadata?.size) 37804 * } else { 37805 * // It's a folder 37806 * console.log('Folder:', item.name) 37807 * } 37808 * }) 37809 * ``` 37810 * 37811 * Response: 37812 * ```json 37813 * { 37814 * "data": [ 37815 * { 37816 * "name": "avatar1.png", 37817 * "id": "e668cf7f-821b-4a2f-9dce-7dfa5dd1cfd2", 37818 * "updated_at": "2024-05-22T23:06:05.580Z", 37819 * "created_at": "2024-05-22T23:04:34.443Z", 37820 * "last_accessed_at": "2024-05-22T23:04:34.443Z", 37821 * "metadata": { 37822 * "eTag": "\"c5e8c553235d9af30ef4f6e280790b92\"", 37823 * "size": 32175, 37824 * "mimetype": "image/png", 37825 * "cacheControl": "max-age=3600", 37826 * "lastModified": "2024-05-22T23:06:05.574Z", 37827 * "contentLength": 32175, 37828 * "httpStatusCode": 200 37829 * } 37830 * } 37831 * ], 37832 * "error": null 37833 * } 37834 * ``` 37835 * 37836 * @example Search files in a bucket 37837 * ```js 37838 * const { data, error } = await supabase 37839 * .storage 37840 * .from('avatars') 37841 * .list('folder', { 37842 * limit: 100, 37843 * offset: 0, 37844 * sortBy: { column: 'name', order: 'asc' }, 37845 * search: 'jon' 37846 * }) 37847 * ``` 37848 * 37849 * @remarks 37850 * - RLS policy permissions required: 37851 * - `buckets` table permissions: none 37852 * - `objects` table permissions: `select` 37853 * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works 37854 */ 37855 async list(n, e, t) { 37856 var i = this; 37857 return i.handleOperation(async () => { 37858 const r = Ze(Ze(Ze({}, MT), e), {}, { prefix: n || "" }); 37859 return await Jn(i.fetch, `${i.url}/object/list/${i.bucketId}`, r, { headers: i.headers }, t); 37860 }); 37861 } 37862 /** 37863 * Lists all the files and folders within a bucket using the V2 API with pagination support. 37864 * 37865 * **Important:** Folder entries in the `folders` array only contain `name` and optionally `key` â 37866 * they have no `id`, timestamps, or `metadata` fields. Full file metadata is only available 37867 * on entries in the `objects` array. 37868 * 37869 * @experimental this method signature might change in the future 37870 * 37871 * @category Storage 37872 * @subcategory File Buckets 37873 * @param options Search options including prefix, cursor for pagination, limit, with_delimiter 37874 * @param parameters Optional fetch parameters including signal for cancellation 37875 * @returns Promise with response containing folders/objects arrays with pagination info or error 37876 * 37877 * @example List files with pagination 37878 * ```js 37879 * const { data, error } = await supabase 37880 * .storage 37881 * .from('avatars') 37882 * .listV2({ 37883 * prefix: 'folder/', 37884 * limit: 100, 37885 * }) 37886 * 37887 * // Handle pagination 37888 * if (data?.hasNext) { 37889 * const nextPage = await supabase 37890 * .storage 37891 * .from('avatars') 37892 * .listV2({ 37893 * prefix: 'folder/', 37894 * cursor: data.nextCursor, 37895 * }) 37896 * } 37897 * 37898 * // Handle files vs folders
37899 * data?.objects.forEach(file => { 37900 * if (file.id !== null) { 37901 * console.log('File:', file.name, 'Size:', file.metadata?.size) 37902 * } 37903 * }) 37904 * data?.folders.forEach(folder => { 37905 * console.log('Folder:', folder.name) 37906 * }) 37907 * ``` 37908 */ 37909 async listV2(n, e) { 37910 var t = this; 37911 return t.handleOperation(async () => { 37912 const i = Ze({}, n); 37913 return await Jn(t.fetch, `${t.url}/object/list-v2/${t.bucketId}`, i, { headers: t.headers }, e); 37914 }); 37915 } 37916 encodeMetadata(n) { 37917 return JSON.stringify(n); 37918 } 37919 toBase64(n) { 37920 return typeof Buffer < "u" ? Buffer.from(n).toString("base64") : btoa(n); 37921 } 37922 _getFinalPath(n) { 37923 return `${this.bucketId}/${n.replace(/^\/+/, "")}`; 37924 } 37925 _removeEmptyFolders(n) { 37926 return n.replace(/^\/|\/$/g, "").replace(/\/+/g, "/"); 37927 } 37928 /** Modifies the `query`, appending values the from `transform` */ 37929 applyTransformOptsToQuery(n, e) { 37930 return e.width && n.set("width", e.width.toString()), e.height && n.set("height", e.height.toString()), e.resize && n.set("resize", e.resize), e.format && n.set("format", e.format), e.quality && n.set("quality", e.quality.toString()), n; 37931 } 37932}; 37933const AT = "2.108.1", Ma = { "X-Client-Info": `storage-js/${AT}` }; 37934var RT = class extends Rs { 37935 constructor(n, e = {}, t, i) { 37936 const r = new URL(n); 37937 i?.useNewHostname && /supabase\.(co|in|red)$/.test(r.hostname) && !r.hostname.includes("storage.supabase.") && (r.hostname = r.hostname.replace("supabase.", "storage.supabase.")); 37938 const s = r.href.replace(/\/$/, ""), a = Ze(Ze({}, Ma), e); 37939 super(s, a, t, "storage"); 37940 } 37941 /** 37942 * Retrieves the details of all Storage buckets within an existing project. 37943 * 37944 * @category Storage 37945 * @subcategory File Buckets 37946 * @param options Query parameters for listing buckets 37947 * @param options.limit Maximum number of buckets to return 37948 * @param options.offset Number of buckets to skip 37949 * @param options.sortColumn Column to sort by ('id', 'name', 'created_at', 'updated_at') 37950 * @param options.sortOrder Sort order ('asc' or 'desc') 37951 * @param options.search Search term to filter bucket names 37952 * @returns Promise with response containing array of buckets or error 37953 * 37954 * @example List buckets 37955 * ```js 37956 * const { data, error } = await supabase 37957 * .storage 37958 * .listBuckets() 37959 * ``` 37960 * 37961 * @example List buckets with options 37962 * ```js 37963 * const { data, error } = await supabase 37964 * .storage 37965 * .listBuckets({ 37966 * limit: 10, 37967 * offset: 0, 37968 * sortColumn: 'created_at', 37969 * sortOrder: 'desc', 37970 * search: 'prod' 37971 * }) 37972 * ``` 37973 * 37974 * @remarks 37975 * - RLS policy permissions required: 37976 * - `buckets` table permissions: `select` 37977 * - `objects` table permissions: none 37978 * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works 37979 */ 37980 async listBuckets(n) { 37981 var e = this; 37982 return e.handleOperation(async () => { 37983 const t = e.listBucketOptionsToQueryString(n); 37984 return await fa(e.fetch, `${e.url}/bucket${t}`, { headers: e.headers }); 37985 }); 37986 } 37987 /** 37988 * Retrieves the details of an existing Storage bucket. 37989 * 37990 * @category Storage 37991 * @subcategory File Buckets 37992 * @param id The unique identifier of the bucket you would like to retrieve. 37993 * @returns Promise with response containing bucket details or error 37994 * 37995 * @example Get bucket 37996 * ```js 37997 * const { data, error } = await supabase 37998 * .storage 37999 * .getBucket('avatars') 38000 * ``` 38001 * 38002 * Response: 38003 * ```json 38004 * { 38005 * "data": { 38006 * "id": "avatars", 38007 * "name": "avatars", 38008 * "owner": "", 38009 * "public": false, 38010 * "file_size_limit": 1024, 38011 * "allowed_mime_types": [ 38012 * "image/png" 38013 * ], 38014 * "created_at": "2024-05-22T22:26:05.100Z", 38015 * "updated_at": "2024-05-22T22:26:05.100Z" 38016 * }, 38017 * "error": null 38018 * } 38019 * ``` 38020 * 38021 * @remarks 38022 * - RLS policy permissions required: 38023 * - `buckets` table permissions: `select` 38024 * - `objects` table permissions: none 38025 * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works 38026 */ 38027 async getBucket(n) { 38028 var e = this; 38029 return e.handleOperation(async () => await fa(e.fetch, `${e.url}/bucket/${n}`, { headers: e.headers })); 38030 } 38031 /** 38032 * Creates a new Storage bucket 38033 * 38034 * @category Storage 38035 * @subcategory File Buckets 38036 * @param id A unique identifier for the bucket you are creating. 38037 * @param options.public The visibility of the bucket. Public bu
38037ckets don't require an authorization token to download objects, but still require a valid token for all other operations. By default, buckets are private. 38038 * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. 38039 * The global file size limit takes precedence over this value. 38040 * The default value is null, which doesn't set a per bucket file size limit. 38041 * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. 38042 * The default value is null, which allows files with all mime types to be uploaded. 38043 * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. 38044 * @param options.type (private-beta) specifies the bucket type. see `BucketType` for more details. 38045 * - default bucket type is `STANDARD` 38046 * @returns Promise with response containing newly created bucket name or error 38047 * 38048 * @example Create bucket 38049 * ```js 38050 * const { data, error } = await supabase 38051 * .storage 38052 * .createBucket('avatars', { 38053 * public: false, 38054 * allowedMimeTypes: ['image/png'], 38055 * fileSizeLimit: 1024 38056 * }) 38057 * ``` 38058 * 38059 * Response: 38060 * ```json 38061 * { 38062 * "data": { 38063 * "name": "avatars" 38064 * }, 38065 * "error": null 38066 * } 38067 * ``` 38068 * 38069 * @remarks 38070 * - RLS policy permissions required: 38071 * - `buckets` table permissions: `insert` 38072 * - `objects` table permissions: none 38073 * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works 38074 */ 38075 async createBucket(n, e = { public: !1 }) { 38076 var t = this; 38077 return t.handleOperation(async () => await Jn(t.fetch, `${t.url}/bucket`, { 38078 id: n, 38079 name: n, 38080 type: e.type, 38081 public: e.public, 38082 file_size_limit: e.fileSizeLimit, 38083 allowed_mime_types: e.allowedMimeTypes 38084 }, { headers: t.headers })); 38085 } 38086 /** 38087 * Updates a Storage bucket 38088 * 38089 * @category Storage 38090 * @subcategory File Buckets 38091 * @param id A unique identifier for the bucket you are updating. 38092 * @param options.public The visibility of the bucket. Public buckets don't require an authorization token to download objects, but still require a valid token for all other operations. 38093 * @param options.fileSizeLimit specifies the max file size in bytes that can be uploaded to this bucket. 38094 * The global file size limit takes precedence over this value. 38095 * The default value is null, which doesn't set a per bucket file size limit. 38096 * @param options.allowedMimeTypes specifies the allowed mime types that this bucket can accept during upload. 38097 * The default value is null, which allows files with all mime types to be uploaded. 38098 * Each mime type specified can be a wildcard, e.g. image/*, or a specific mime type, e.g. image/png. 38099 * @returns Promise with response containing success message or error 38100 * 38101 * @example Update bucket 38102 * ```js 38103 * const { data, error } = await supabase 38104 * .storage 38105 * .updateBucket('avatars', { 38106 * public: false, 38107 * allowedMimeTypes: ['image/png'], 38108 * fileSizeLimit: 1024 38109 * }) 38110 * ``` 38111 * 38112 * Response: 38113 * ```json 38114 * { 38115 * "data": { 38116 * "message": "Successfully updated" 38117 * }, 38118 * "error": null 38119 * } 38120 * ``` 38121 * 38122 * @remarks 38123 * - RLS policy permissions required: 38124 * - `buckets` table permissions: `select` and `update` 38125 * - `objects` table permissions: none 38126 * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works 38127 */ 38128 async updateBucket(n, e) { 38129 var t = this; 38130 return t.handleOperation(async () => await fu(t.fetch, `${t.url}/bucket/${n}`, { 38131 id: n, 38132 name: n, 38133 public: e.public, 38134 file_size_limit: e.fileSizeLimit, 38135 allowed_mime_types: e.allowedMimeTypes 38136 }, { headers: t.headers })); 38137 } 38138 /** 38139 * Removes all objects inside a single bucket. 38140 * 38141 * @category Storage 38142 * @subcategory File Buckets 38143 * @param id The unique identifier of the bucket you would like to empty. 38144 * @returns Promise with success message or error 38145 * 38146 * @example Empty bucket 38147 * ```js 38148 * const { data, error } = await supabase 38149 * .storage 38150 * .emptyBucket('avatars') 38151 * ``` 38152 * 38153 * Response: 38154 * ```json 38155 * { 38156 * "data": { 38157 * "message": "Successfully emptied" 38158 * }, 38159 * "error": null 38160 * } 38161 * ``` 38162 * 38163 * @remarks 38164 * - RLS policy permissions required: 38165 * - `buckets` table permissions: `select` 38166 * - `objects` table permissions: `select` and `delete` 38167 * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works 38168 */ 38169 async emptyBucket(n) { 38170 var e = this; 38171 return e.handleOperation(async () => await Jn(e.fetch, `${e.url}/bucket/${n}/empty`, {}, { headers: e.headers })); 38172 } 38173 /** 38174 * Deletes an existing bucket. A bucket can't be deleted with existing objects inside it. 38175 * You must first `empty()` the bucket. 38176 * 38177 * @category Storage 38178 * @subcategory File Buckets 38179 * @param id The unique identifier of the bucket you would like to delete. 38180 * @returns Promise with success message or error 38181 * 38182 * @example Delete bucket 38183 * ```js 38184 * const { data, error } = await supabase 38185 * .storage 38186 * .deleteBucket('avatars') 38187 * ``` 38188 * 38189 * Response: 38190 * ```json 38191 * { 38192 * "data": { 38193 * "message": "Successfully deleted" 38194 * }, 38195 * "error": null 38196 * } 38197 * ``` 38198 * 38199 * @remarks 38200 * - RLS policy permissions required: 38201 * - `buckets` table permissions: `select` and `delete` 38202 * - `objects` table permissions: none 38203 * - Refer to the [Storage guide](/docs/guides/storage/security/access-control) on how access control works 38204 */ 38205 async deleteBucket(n) { 38206 var e = this; 38207 return e.handleOperation(async () => await nh(e.fetch, `${e.url}/bucket/${n}`, {}, { headers: e.headers })); 38208 } 38209 listBucketOptionsToQueryString(n) { 38210 const e = {}; 38211 return n && ("limit" in n && (e.limit = String(n.limit)), "offset" in n && (e.offset = String(n.offset)), n.search && (e.search = n.search), n.sortColumn && (e.sortColumn = n.sortColumn), n.sortOrder && (e.sortOrder = n.sortOrder)), Object.keys(e).length > 0 ? "?" + new URLSearchParams(e).toString() : ""; 38212 } 38213}, CT = class extends Rs { 38214 /** 38215 * @alpha 38216 * 38217 * Creates a new StorageAnalyticsClient instance 38218 * 38219 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38220 * 38221 * @category Storage 38222 * @subcategory Analytics Buckets 38223 * @param url - The base URL for the storage API 38224 * @param headers - HTTP headers to include in requests 38225 * @param fetch - Optional custom fetch implementation 38226 * 38227 * @example Using supabase-js (recommended) 38228 * ```typescript 38229 * import { createClient } from '@supabase/supabase-js' 38230 * 38231 * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key') 38232 * const { data, error } = await supabase.storage.analytics.listBuckets() 38233 * ``` 38234 * 38235 * @example Standalone import for bundle-sensitive environments 38236 * ```typescript 38237 * import { StorageAnalyticsClient } from '@supabase/storage-js' 38238 * 38239 * const client = new StorageAnalyticsClient(url, headers) 38240 * ``` 38241 */ 38242 constructor(n, e = {}, t) { 38243 const i = n.replace(/\/$/, ""), r = Ze(Ze({}, Ma), e); 38244 super(i, r, t, "storage"); 38245 } 38246 /** 38247 * @alpha 38248 *
38249 * Creates a new analytics bucket using Iceberg tables 38250 * Analytics buckets are optimized for analytical queries and data processing 38251 * 38252 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38253 * 38254 * @category Storage 38255 * @subcategory Analytics Buckets 38256 * @param name A unique name for the bucket you are creating 38257 * @returns Promise with response containing newly created analytics bucket or error 38258 * 38259 * @example Create analytics bucket 38260 * ```js 38261 * const { data, error } = await supabase 38262 * .storage 38263 * .analytics 38264 * .createBucket('analytics-data') 38265 * ``` 38266 * 38267 * Response: 38268 * ```json 38269 * { 38270 * "data": { 38271 * "name": "analytics-data", 38272 * "type": "ANALYTICS", 38273 * "format": "iceberg", 38274 * "created_at": "2024-05-22T22:26:05.100Z", 38275 * "updated_at": "2024-05-22T22:26:05.100Z" 38276 * }, 38277 * "error": null 38278 * } 38279 * ``` 38280 * 38281 * @remarks 38282 * - Creates a new analytics bucket using Iceberg tables 38283 * - Analytics buckets are optimized for analytical queries and data processing 38284 */ 38285 async createBucket(n) { 38286 var e = this; 38287 return e.handleOperation(async () => await Jn(e.fetch, `${e.url}/bucket`, { name: n }, { headers: e.headers })); 38288 } 38289 /** 38290 * @alpha 38291 * 38292 * Retrieves the details of all Analytics Storage buckets within an existing project 38293 * Only returns buckets of type 'ANALYTICS' 38294 * 38295 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38296 * 38297 * @category Storage 38298 * @subcategory Analytics Buckets 38299 * @param options Query parameters for listing buckets 38300 * @param options.limit Maximum number of buckets to return 38301 * @param options.offset Number of buckets to skip 38302 * @param options.sortColumn Column to sort by ('name', 'created_at', 'updated_at') 38303 * @param options.sortOrder Sort order ('asc' or 'desc') 38304 * @param options.search Search term to filter bucket names 38305 * @returns Promise with response containing array of analytics buckets or error 38306 * 38307 * @example List analytics buckets 38308 * ```js 38309 * const { data, error } = await supabase 38310 * .storage 38311 * .analytics 38312 * .listBuckets({ 38313 * limit: 10, 38314 * offset: 0, 38315 * sortColumn: 'created_at', 38316 * sortOrder: 'desc' 38317 * }) 38318 * ``` 38319 * 38320 * Response: 38321 * ```json 38322 * { 38323 * "data": [ 38324 * { 38325 * "name": "analytics-data", 38326 * "type": "ANALYTICS", 38327 * "format": "iceberg", 38328 * "created_at": "2024-05-22T22:26:05.100Z", 38329 * "updated_at": "2024-05-22T22:26:05.100Z" 38330 * } 38331 * ], 38332 * "error": null 38333 * } 38334 * ``` 38335 * 38336 * @remarks 38337 * - Retrieves the details of all Analytics Storage buckets within an existing project 38338 * - Only returns buckets of type 'ANALYTICS' 38339 */ 38340 async listBuckets(n) { 38341 var e = this; 38342 return e.handleOperation(async () => { 38343 const t = new URLSearchParams(); 38344 n?.limit !== void 0 && t.set("limit", n.limit.toString()), n?.offset !== void 0 && t.set("offset", n.offset.toString()), n?.sortColumn && t.set("sortColumn", n.sortColumn), n?.sortOrder && t.set("sortOrder", n.sortOrder), n?.search && t.set("search", n.search); 38345 const i = t.toString(), r = i ? `${e.url}/bucket?${i}` : `${e.url}/bucket`; 38346 return await fa(e.fetch, r, { headers: e.headers }); 38347 }); 38348 } 38349 /** 38350 * @alpha 38351 * 38352 * Deletes an existing analytics bucket 38353 * A bucket can't be deleted with existing objects inside it 38354 * You must first empty the bucket before deletion 38355 * 38356 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38357 * 38358 * @category Storage 38359 * @subcategory Analytics Buckets 38360 * @param bucketName The unique identifier of the bucket you would like to delete 38361 * @returns Promise with response containing success message or error 38362 * 38363 * @example Delete analytics bucket 38364 * ```js 38365 * const { data, error } = await supabase 38366 * .storage 38367 * .analytics 38368 * .deleteBucket('analytics-data') 38369 * ``` 38370 * 38371 * Response: 38372 * ```json 38373 * { 38374 * "data": { 38375 * "message": "Successfully deleted" 38376 * }, 38377 * "error": null 38378 * } 38379 * ``` 38380 * 38381 * @remarks 38382 * - Deletes an analytics bucket 38383 */ 38384 async deleteBucket(n) { 38385 var e = this; 38386 return e.handleOperation(async () => await nh(e.fetch, `${e.url}/bucket/${n}`, {}, { headers: e.headers })); 38387 } 38388 /** 38389 * @alpha 38390 * 38391 * Get an Iceberg REST Catalog client configured for a specific analytics bucket 38392 * Use this to perform advanced table and namespace operations within the bucket 38393 * The returned client provides full access to the Apache Iceberg REST Catalog API 38394 * with the Supabase `{ data, error }` pattern for consistent error handling on all operations. 38395 * 38396 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38397 * 38398 * @category Storage 38399 * @subcategory Analytics Buckets
38400 * @param bucketName - The name of the analytics bucket (warehouse) to connect to 38401 * @returns The wrapped Iceberg catalog client 38402 * @throws {StorageError} If the bucket name is invalid 38403 * 38404 * @example Get catalog and create table 38405 * ```js 38406 * // First, create an analytics bucket 38407 * const { data: bucket, error: bucketError } = await supabase 38408 * .storage 38409 * .analytics 38410 * .createBucket('analytics-data') 38411 * 38412 * // Get the Iceberg catalog for that bucket 38413 * const catalog = supabase.storage.analytics.from('analytics-data') 38414 * 38415 * // Create a namespace 38416 * const { error: nsError } = await catalog.createNamespace({ namespace: ['default'] }) 38417 * 38418 * // Create a table with schema 38419 * const { data: tableMetadata, error: tableError } = await catalog.createTable( 38420 * { namespace: ['default'] }, 38421 * { 38422 * name: 'events', 38423 * schema: { 38424 * type: 'struct', 38425 * fields: [ 38426 * { id: 1, name: 'id', type: 'long', required: true }, 38427 * { id: 2, name: 'timestamp', type: 'timestamp', required: true }, 38428 * { id: 3, name: 'user_id', type: 'string', required: false } 38429 * ], 38430 * 'schema-id': 0, 38431 * 'identifier-field-ids': [1] 38432 * }, 38433 * 'partition-spec': { 38434 * 'spec-id': 0, 38435 * fields: [] 38436 * }, 38437 * 'write-order': { 38438 * 'order-id': 0, 38439 * fields: [] 38440 * }, 38441 * properties: { 38442 * 'write.format.default': 'parquet' 38443 * } 38444 * } 38445 * ) 38446 * ``` 38447 * 38448 * @example List tables in namespace 38449 * ```js 38450 * const catalog = supabase.storage.analytics.from('analytics-data') 38451 * 38452 * // List all tables in the default namespace 38453 * const { data: tables, error: listError } = await catalog.listTables({ namespace: ['default'] }) 38454 * if (listError) { 38455 * if (listError.isNotFound()) { 38456 * console.log('Namespace not found') 38457 * } 38458 * return 38459 * } 38460 * console.log(tables) // [{ namespace: ['default'], name: 'events' }] 38461 * ``` 38462 * 38463 * @example Working with namespaces 38464 * ```js 38465 * const catalog = supabase.storage.analytics.from('analytics-data') 38466 * 38467 * // List all namespaces 38468 * const { data: namespaces } = await catalog.listNamespaces() 38469 * 38470 * // Create namespace with properties 38471 * await catalog.createNamespace( 38472 * { namespace: ['production'] }, 38473 * { properties: { owner: 'data-team', env: 'prod' } } 38474 * ) 38475 * ``` 38476 * 38477 * @example Cleanup operations 38478 * ```js 38479 * const catalog = supabase.storage.analytics.from('analytics-data') 38480 * 38481 * // Drop table with purge option (removes all data) 38482 * const { error: dropError } = await catalog.dropTable( 38483 * { namespace: ['default'], name: 'events' }, 38484 * { purge: true } 38485 * ) 38486 * 38487 * if (dropError?.isNotFound()) { 38488 * console.log('Table does not exist') 38489 * } 38490 * 38491 * // Drop namespace (must be empty) 38492 * await catalog.dropNamespace({ namespace: ['default'] }) 38493 * ``` 38494 * 38495 * @remarks 38496 * This method provides a bridge between Supabase's bucket management and the standard 38497 * Apache Iceberg REST Catalog API. The bucket name maps to the Iceberg warehouse parameter. 38498 * All authentication and configuration is handled automatically using your Supabase credentials. 38499 * 38500 * **Error Handling**: Invalid bucket names throw immediately. All catalog 38501 * operations return `{ data, error }` where errors are `IcebergError` instances from iceberg-js. 38502 * Use helper methods like `error.isNotFound()` or check `error.status` for specific error handling. 38503 * Use `.throwOnError()` on the analytics client if you prefer exceptions for catalog operations. 38504 * 38505 * **Cleanup Operations**: When using `dropTable`, the `purge: true` option permanently 38506 * deletes all table data. Without it, the table is marked as deleted but data remains. 38507 * 38508 * **Library Dependency**: The returned catalog wraps `IcebergRestCatalog` from iceberg-js. 38509 * For complete API documentation and advanced usage, refer to the 38510 * [iceberg-js documentation](https://supabase.github.io/iceberg-js/). 38511 */ 38512 from(n) { 38513 var e = this; 38514 if (!_T(n)) throw new el("Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters."); 38515 const t = new hT({ 38516 baseUrl: this.url, 38517 catalogName: n, 38518 auth: { 38519 type: "custom", 38520 getHeaders: async () => e.headers 38521 }, 38522 fetch: this.fetch 38523 }), i = this.shouldThrowOnError; 38524 return new Proxy(t, { get(r, s) { 38525 const a = r[s]; 38526 return typeof a != "function" ? a : async (...l) => { 38527 try { 38528 return { 38529 data: await a.apply(r, l), 38530 error: null 38531 }; 38532 } catch (o) { 38533 if (i) throw o; 38534 return { 38535 data: null, 38536 error: o 38537 }; 38538 } 38539 }; 38540 } }); 38541 } 38542}, PT = class extends Rs { 38543 /** Creates a new VectorIndexApi instance */ 38544 constructor(n, e = {}, t) { 38545 const i = n.replace(/\/$/, ""), r = Ze(Ze({}, Ma), {}, { "Content-Type": "application/json" }, e); 38546 super(i, r, t, "vectors"); 38547 } 38548 /** Creates a new vector index within a bucket */ 38549 async createIndex(n) { 38550 var e = this; 38551 return e.handleOperation(async () => await Ln.post(e.fetch, `${e.url}/CreateIndex`, n, { headers: e.headers }) || {}); 38552 } 38553 /** Retrieves metadata for a specific vector index */ 38554 async getIndex(n, e) { 38555 var t = this; 38556 return t.handleOperation(async () => await Ln.post(t.fetch, `${t.url}/GetIndex`, { 38557 vectorBucketName: n, 38558 indexName: e 38559 }, { headers: t.headers })); 38560 } 38561 /** Lists vector indexes within a bucket with optional filtering and pagination */ 38562 async listIndexes(n) { 38563 var e = this; 38564 return e.handleOperation(async () => await Ln.post(e.fetch, `${e.url}/ListIndexes`, n, { headers: e.headers })); 38565 } 38566 /** Deletes a vector index and all its data */ 38567 async deleteIndex(n, e) { 38568 var t = this; 38569 return t.handleOperation(async () => await Ln.post(t.fetch, `${t.url}/DeleteIndex`, { 38570 vectorBucketName: n, 38571 indexName: e 38572 }, { headers: t.headers }) || {}); 38573 } 38574}, LT = class extends Rs { 38575 /** Creates a new VectorDataApi instance */ 38576 constructor(n, e = {}, t) { 38577 const i = n.replace(/\/$/, ""), r = Ze(Ze({}, Ma), {}, { "Content-Type": "application/json" }, e); 38578 super(i, r, t, "vectors"); 38579 } 38580 /** Inserts or updates vectors in batch (1-500 per request) */ 38581 async putVectors(n) { 38582 var e = this; 38583 if (n.vectors.length < 1 || n.vectors.length > 500) throw new Error("Vector batch size must be between 1 and 500 items"); 38584 return e.handleOperation(async () => await Ln.post(e.fetch, `${e.url}/PutVectors`, n, { headers: e.headers }) || {}); 38585 } 38586 /** Retrieves vectors by their keys in batch */ 38587 async getVectors(n) { 38588 var e = this; 38589 return e.handleOperation(async () => await Ln.post(e.fetch, `${e.url}/GetVectors`, n, { headers: e.headers })); 38590 } 38591 /** Lists vectors in an index with pagination */ 38592 async listVectors(n) { 38593 var e = this; 38594 if (n.segmentCount !== void 0) { 38595 if (n.segmentCount < 1 || n.segmentCount > 16) throw new Error("segmentCount must be between 1 and 16"); 38596 if (n.segmentIndex !== void 0 && (n.segmentIndex < 0 || n.segmentIndex >= n.segmentCount)) 38597 throw new Error(`segmentIndex must be between 0 and ${n.segmentCount - 1}`); 38598 } 38599 return e.handleOperation(async () => await Ln.post(e.fetch, `${e.url}/ListVectors`, n, { headers: e.headers })); 38600 } 38601 /** Queries for similar vectors using approximate nearest neighbor search */ 38602 async queryVectors(n) { 38603 var e = this; 38604 return e.handleOperation(async () => await Ln.post(e.fetch, `${e.url}/QueryVectors`, n, { headers: e.headers })); 38605 } 38606 /** Deletes vectors by their keys in batch (1-500 per request) */ 38607 async deleteVectors(n) { 38608 var e = this; 38609 if (n.keys.length < 1 || n.keys.length >
38609 500) throw new Error("Keys batch size must be between 1 and 500 items"); 38610 return e.handleOperation(async () => await Ln.post(e.fetch, `${e.url}/DeleteVectors`, n, { headers: e.headers }) || {}); 38611 } 38612}, NT = class extends Rs { 38613 /** Creates a new VectorBucketApi instance */ 38614 constructor(n, e = {}, t) { 38615 const i = n.replace(/\/$/, ""), r = Ze(Ze({}, Ma), {}, { "Content-Type": "application/json" }, e); 38616 super(i, r, t, "vectors"); 38617 } 38618 /** Creates a new vector bucket */ 38619 async createBucket(n) { 38620 var e = this; 38621 return e.handleOperation(async () => await Ln.post(e.fetch, `${e.url}/CreateVectorBucket`, { vectorBucketName: n }, { headers: e.headers }) || {}); 38622 } 38623 /** Retrieves metadata for a specific vector bucket */ 38624 async getBucket(n) { 38625 var e = this; 38626 return e.handleOperation(async () => await Ln.post(e.fetch, `${e.url}/GetVectorBucket`, { vectorBucketName: n }, { headers: e.headers })); 38627 } 38628 /** Lists vector buckets with optional filtering and pagination */ 38629 async listBuckets(n = {}) { 38630 var e = this; 38631 return e.handleOperation(async () => await Ln.post(e.fetch, `${e.url}/ListVectorBuckets`, n, { headers: e.headers })); 38632 } 38633 /** Deletes a vector bucket (must be empty first) */ 38634 async deleteBucket(n) { 38635 var e = this; 38636 return e.handleOperation(async () => await Ln.post(e.fetch, `${e.url}/DeleteVectorBucket`, { vectorBucketName: n }, { headers: e.headers }) || {}); 38637 } 38638}, IT = class extends NT { 38639 /** 38640 * @alpha 38641 * 38642 * Creates a StorageVectorsClient that can manage buckets, indexes, and vectors. 38643 * 38644 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38645 * 38646 * @category Storage 38647 * @subcategory Vector Buckets 38648 * @param url - Base URL of the Storage Vectors REST API. 38649 * @param options.headers - Optional headers (for example `Authorization`) applied to every request. 38650 * @param options.fetch - Optional custom `fetch` implementation for non-browser runtimes. 38651 * 38652 * @example Using supabase-js (recommended) 38653 * ```typescript 38654 * import { createClient } from '@supabase/supabase-js' 38655 * 38656 * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key') 38657 * const bucket = supabase.storage.vectors.from('embeddings-prod') 38658 * ``` 38659 * 38660 * @example Standalone import for bundle-sensitive environments 38661 * ```typescript 38662 * import { StorageVectorsClient } from '@supabase/storage-js' 38663 * 38664 * const client = new StorageVectorsClient(url, options) 38665 * ``` 38666 */ 38667 constructor(n, e = {}) { 38668 super(n, e.headers || {}, e.fetch); 38669 } 38670 /** 38671 * 38672 * @alpha 38673 * 38674 * Access operations for a specific vector bucket 38675 * Returns a scoped client for index and vector operations within the bucket 38676 * 38677 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38678 * 38679 * @category Storage 38680 * @subcategory Vector Buckets 38681 * @param vectorBucketName - Name of the vector bucket 38682 * @returns Bucket-scoped client with index and vector operations 38683 * 38684 * @example Accessing a vector bucket 38685 * ```typescript 38686 * const bucket = supabase.storage.vectors.from('embeddings-prod') 38687 * ``` 38688 */ 38689 from(n) { 38690 return new DT(this.url, this.headers, n, this.fetch); 38691 } 38692 /** 38693 * 38694 * @alpha 38695 * 38696 * Creates a new vector bucket 38697 * Vector buckets are containers for vector indexes and their data 38698 * 38699 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38700 * 38701 * @category Storage 38702 * @subcategory Vector Buckets 38703 * @param vectorBucketName - Unique name for the vector bucket 38704 * @returns Promise with empty response on success or error 38705 * 38706 * @example Creating a vector bucket 38707 * ```typescript 38708 * const { data, error } = await supabase 38709 * .storage 38710 * .vectors 38711 * .createBucket('embeddings-prod') 38712 * ``` 38713 */ 38714 async createBucket(n) { 38715 var e = () => super.createBucket, t = this; 38716 return e().call(t, n); 38717 } 38718 /** 38719 * 38720 * @alpha 38721 * 38722 * Retrieves metadata for a specific vector bucket 38723 * 38724 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38725 * 38726 * @category Storage 38727 * @subcategory Vector Buckets 38728 * @param vectorBucketName - Name of the vector bucket 38729 * @returns Promise with bucket metadata or error 38730 * 38731 * @example Get bucket metadata 38732 * ```typescript 38733 * const { data, error } = await supabase 38734 * .storage 38735 * .vectors 38736 * .getBucket('embeddings-prod') 38737 * 38738 * console.log('Bucket created:', data?.vectorBucket.creationTime) 38739 * ``` 38740 */ 38741 async getBucket(n) { 38742 var e = () => super.getBucket, t = this; 38743 return e().call(t, n); 38744 } 38745 /** 38746 * 38747 * @alpha 38748 * 38749 * Lists all vector buckets with optional filtering and pagination 38750 * 38751 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38752 * 38753 * @category Storage 38754 * @subcategory Vector Buckets 38755 * @param options - Optional filters (prefix, maxResults, nextToken) 38756 * @returns Promise with list of buckets or error 38757 * 38758 * @example List vector buckets 38759 * ```typescript 38760 * const { data, error } = await supabase 38761 * .storage 38762 * .vectors 38763 * .listBuckets({ prefix: 'embeddings-' }) 38764 *
38765 * data?.vectorBuckets.forEach(bucket => { 38766 * console.log(bucket.vectorBucketName) 38767 * }) 38768 * ``` 38769 */ 38770 async listBuckets(n = {}) { 38771 var e = () => super.listBuckets, t = this; 38772 return e().call(t, n); 38773 } 38774 /** 38775 * 38776 * @alpha 38777 * 38778 * Deletes a vector bucket (bucket must be empty) 38779 * All indexes must be deleted before deleting the bucket 38780 * 38781 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38782 * 38783 * @category Storage 38784 * @subcategory Vector Buckets 38785 * @param vectorBucketName - Name of the vector bucket to delete 38786 * @returns Promise with empty response on success or error 38787 * 38788 * @example Delete a vector bucket 38789 * ```typescript 38790 * const { data, error } = await supabase 38791 * .storage 38792 * .vectors 38793 * .deleteBucket('embeddings-old') 38794 * ``` 38795 */ 38796 async deleteBucket(n) { 38797 var e = () => super.deleteBucket, t = this; 38798 return e().call(t, n); 38799 } 38800}, DT = class extends PT { 38801 /** 38802 * @alpha 38803 * 38804 * Creates a helper that automatically scopes all index operations to the provided bucket. 38805 * 38806 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38807 * 38808 * @category Storage 38809 * @subcategory Vector Buckets 38810 * @example Creating a vector bucket scope 38811 * ```typescript 38812 * const bucket = supabase.storage.vectors.from('embeddings-prod') 38813 * ``` 38814 */ 38815 constructor(n, e, t, i) { 38816 super(n, e, i), this.vectorBucketName = t; 38817 } 38818 /** 38819 * 38820 * @alpha 38821 * 38822 * Creates a new vector index in this bucket 38823 * Convenience method that automatically includes the bucket name 38824 * 38825 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38826 * 38827 * @category Storage 38828 * @subcategory Vector Buckets 38829 * @param options - Index configuration (vectorBucketName is automatically set) 38830 * @returns Promise with empty response on success or error 38831 * 38832 * @example Creating a vector index 38833 * ```typescript 38834 * const bucket = supabase.storage.vectors.from('embeddings-prod') 38835 * await bucket.createIndex({ 38836 * indexName: 'documents-openai', 38837 * dataType: 'float32', 38838 * dimension: 1536, 38839 * distanceMetric: 'cosine', 38840 * metadataConfiguration: { 38841 * nonFilterableMetadataKeys: ['raw_text'] 38842 * } 38843 * }) 38844 * ``` 38845 */ 38846 async createIndex(n) { 38847 var e = () => super.createIndex, t = this; 38848 return e().call(t, Ze(Ze({}, n), {}, { vectorBucketName: t.vectorBucketName })); 38849 } 38850 /** 38851 * 38852 * @alpha 38853 * 38854 * Lists indexes in this bucket 38855 * Convenience method that automatically includes the bucket name 38856 * 38857 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38858 * 38859 * @category Storage 38860 * @subcategory Vector Buckets 38861 * @param options - Listing options (vectorBucketName is automatically set) 38862 * @returns Promise with response containing indexes array and pagination token or error 38863 * 38864 * @example List indexes 38865 * ```typescript 38866 * const bucket = supabase.storage.vectors.from('embeddings-prod') 38867 * const { data } = await bucket.listIndexes({ prefix: 'documents-' }) 38868 * ``` 38869 */ 38870 async listIndexes(n = {}) { 38871 var e = () => super.listIndexes, t = this; 38872 return e().call(t, Ze(Ze({}, n), {}, { vectorBucketName: t.vectorBucketName })); 38873 } 38874 /** 38875 * 38876 * @alpha 38877 * 38878 * Retrieves metadata for a specific index in this bucket 38879 * Convenience method that automatically includes the bucket name 38880 * 38881 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38882 * 38883 * @category Storage 38884 * @subcategory Vector Buckets 38885 * @param indexName - Name of the index to retrieve 38886 * @returns Promise with index metadata or error 38887 * 38888 * @example Get index metadata 38889 * ```typescript 38890 * const bucket = supabase.storage.vectors.from('embeddings-prod') 38891 * const { data } = await bucket.getIndex('documents-openai') 38892 * console.log('Dimension:', data?.index.dimension) 38893 * ``` 38894 */ 38895 async getIndex(n) { 38896 var e = () => super.getIndex, t = this; 38897 return e().call(t, t.vectorBucketName, n); 38898 } 38899 /** 38900 * 38901 * @alpha 38902 * 38903 * Deletes an index from this bucket 38904 * Convenience method that automatically includes the bucket name 38905 * 38906 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38907 * 38908 * @category Storage 38909 * @subcategory Vector Buckets 38910 * @param indexName - Name of the index to delete
38911 * @returns Promise with empty response on success or error 38912 * 38913 * @example Delete an index 38914 * ```typescript 38915 * const bucket = supabase.storage.vectors.from('embeddings-prod') 38916 * await bucket.deleteIndex('old-index') 38917 * ``` 38918 */ 38919 async deleteIndex(n) { 38920 var e = () => super.deleteIndex, t = this; 38921 return e().call(t, t.vectorBucketName, n); 38922 } 38923 /** 38924 * 38925 * @alpha 38926 * 38927 * Access operations for a specific index within this bucket 38928 * Returns a scoped client for vector data operations 38929 * 38930 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38931 * 38932 * @category Storage 38933 * @subcategory Vector Buckets 38934 * @param indexName - Name of the index 38935 * @returns Index-scoped client with vector data operations 38936 * 38937 * @example Accessing an index 38938 * ```typescript 38939 * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') 38940 * 38941 * // Insert vectors 38942 * await index.putVectors({ 38943 * vectors: [ 38944 * { key: 'doc-1', data: { float32: [...] }, metadata: { title: 'Intro' } } 38945 * ] 38946 * }) 38947 * 38948 * // Query similar vectors 38949 * const { data } = await index.queryVectors({ 38950 * queryVector: { float32: [...] }, 38951 * topK: 5 38952 * }) 38953 * ``` 38954 */ 38955 index(n) { 38956 return new UT(this.url, this.headers, this.vectorBucketName, n, this.fetch); 38957 } 38958}, UT = class extends LT { 38959 /** 38960 * 38961 * @alpha 38962 * 38963 * Creates a helper that automatically scopes all vector operations to the provided bucket/index names. 38964 * 38965 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38966 * 38967 * @category Storage 38968 * @subcategory Vector Buckets 38969 * @example Creating a vector index scope 38970 * ```typescript 38971 * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') 38972 * ``` 38973 */ 38974 constructor(n, e, t, i, r) { 38975 super(n, e, r), this.vectorBucketName = t, this.indexName = i; 38976 } 38977 /** 38978 * 38979 * @alpha 38980 * 38981 * Inserts or updates vectors in this index 38982 * Convenience method that automatically includes bucket and index names 38983 * 38984 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 38985 * 38986 * @category Storage 38987 * @subcategory Vector Buckets 38988 * @param options - Vector insertion options (bucket and index names automatically set) 38989 * @returns Promise with empty response on success or error 38990 * 38991 * @example Insert vectors into an index 38992 * ```typescript 38993 * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') 38994 * await index.putVectors({ 38995 * vectors: [ 38996 * { 38997 * key: 'doc-1', 38998 * data: { float32: [0.1, 0.2, ...] }, 38999 * metadata: { title: 'Introduction', page: 1 } 39000 * } 39001 * ] 39002 * }) 39003 * ``` 39004 */ 39005 async putVectors(n) { 39006 var e = () => super.putVectors, t = this; 39007 return e().call(t, Ze(Ze({}, n), {}, { 39008 vectorBucketName: t.vectorBucketName, 39009 indexName: t.indexName 39010 })); 39011 } 39012 /** 39013 * 39014 * @alpha 39015 * 39016 * Retrieves vectors by keys from this index 39017 * Convenience method that automatically includes bucket and index names 39018 * 39019 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 39020 * 39021 * @category Storage 39022 * @subcategory Vector Buckets 39023 * @param options - Vector retrieval options (bucket and index names automatically set) 39024 * @returns Promise with response containing vectors array or error 39025 * 39026 * @example Get vectors by keys 39027 * ```typescript 39028 * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') 39029 * const { data } = await index.getVectors({ 39030 * keys: ['doc-1', 'doc-2'], 39031 * returnMetadata: true 39032 * }) 39033 * ``` 39034 */ 39035 async getVectors(n) { 39036 var e = () => super.getVectors, t = this; 39037 return e().call(t, Ze(Ze({}, n), {}, { 39038 vectorBucketName: t.vectorBucketName, 39039 indexName: t.indexName 39040 })); 39041 } 39042 /** 39043 * 39044 * @alpha 39045 * 39046 * Lists vectors in this index with pagination 39047 * Convenience method that automatically includes bucket and index names 39048 * 39049 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 39050 * 39051 * @category Storage 39052 * @subcategory Vector Buckets
39053 * @param options - Listing options (bucket and index names automatically set) 39054 * @returns Promise with response containing vectors array and pagination token or error 39055 * 39056 * @example List vectors with pagination 39057 * ```typescript 39058 * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') 39059 * const { data } = await index.listVectors({ 39060 * maxResults: 500, 39061 * returnMetadata: true 39062 * }) 39063 * ``` 39064 */ 39065 async listVectors(n = {}) { 39066 var e = () => super.listVectors, t = this; 39067 return e().call(t, Ze(Ze({}, n), {}, { 39068 vectorBucketName: t.vectorBucketName, 39069 indexName: t.indexName 39070 })); 39071 } 39072 /** 39073 * 39074 * @alpha 39075 * 39076 * Queries for similar vectors in this index 39077 * Convenience method that automatically includes bucket and index names 39078 * 39079 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 39080 * 39081 * @category Storage 39082 * @subcategory Vector Buckets 39083 * @param options - Query options (bucket and index names automatically set) 39084 * @returns Promise with response containing matches array of similar vectors ordered by distance or error 39085 * 39086 * @example Query similar vectors 39087 * ```typescript 39088 * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') 39089 * const { data } = await index.queryVectors({ 39090 * queryVector: { float32: [0.1, 0.2, ...] }, 39091 * topK: 5, 39092 * filter: { category: 'technical' }, 39093 * returnDistance: true, 39094 * returnMetadata: true 39095 * }) 39096 * ``` 39097 */ 39098 async queryVectors(n) { 39099 var e = () => super.queryVectors, t = this; 39100 return e().call(t, Ze(Ze({}, n), {}, { 39101 vectorBucketName: t.vectorBucketName, 39102 indexName: t.indexName 39103 })); 39104 } 39105 /** 39106 * 39107 * @alpha 39108 * 39109 * Deletes vectors by keys from this index 39110 * Convenience method that automatically includes bucket and index names 39111 * 39112 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 39113 * 39114 * @category Storage 39115 * @subcategory Vector Buckets 39116 * @param options - Deletion options (bucket and index names automatically set) 39117 * @returns Promise with empty response on success or error 39118 * 39119 * @example Delete vectors by keys 39120 * ```typescript 39121 * const index = supabase.storage.vectors.from('embeddings-prod').index('documents-openai') 39122 * await index.deleteVectors({ 39123 * keys: ['doc-1', 'doc-2', 'doc-3'] 39124 * }) 39125 * ``` 39126 */ 39127 async deleteVectors(n) { 39128 var e = () => super.deleteVectors, t = this; 39129 return e().call(t, Ze(Ze({}, n), {}, { 39130 vectorBucketName: t.vectorBucketName, 39131 indexName: t.indexName 39132 })); 39133 } 39134}, OT = class extends RT { 39135 /** 39136 * Creates a client for Storage buckets, files, analytics, and vectors. 39137 * 39138 * @category Storage 39139 * @subcategory File Buckets 39140 * 39141 * @example Using supabase-js (recommended) 39142 * ```ts 39143 * import { createClient } from '@supabase/supabase-js' 39144 * 39145 * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key') 39146 * const avatars = supabase.storage.from('avatars') 39147 * ``` 39148 * 39149 * @example Standalone import for bundle-sensitive environments 39150 * ```ts 39151 * import { StorageClient } from '@supabase/storage-js' 39152 * 39153 * const storage = new StorageClient('https://xyzcompany.supabase.co/storage/v1', { 39154 * apikey: 'your-publishable-key', 39155 * }) 39156 * const avatars = storage.from('avatars') 39157 * ``` 39158 */ 39159 constructor(n, e = {}, t, i) { 39160 super(n, e, t, i); 39161 } 39162 /** 39163 * Perform file operation in a bucket. 39164 * 39165 * @category Storage 39166 * @subcategory File Buckets 39167 * 39168 * @param id The bucket id to operate on. 39169 * 39170 * @example Accessing a bucket 39171 * ```typescript 39172 * const avatars = supabase.storage.from('avatars') 39173 * ``` 39174 */ 39175 from(n) { 39176 return new TT(this.url, this.headers, n, this.fetch); 39177 } 39178 /** 39179 * 39180 * @alpha 39181 * 39182 * Access vector storage operations. 39183 * 39184 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 39185 * 39186 * @category Storage 39187 * @subcategory Vector Buckets 39188 * 39189 * @returns A StorageVectorsClient instance configured with the current storage settings. 39190 */ 39191 get vectors() { 39192 return new IT(this.url + "/vector", { 39193 headers: this.headers, 39194 fetch: this.fetch 39195 }); 39196 } 39197 /** 39198 * 39199 * @alpha 39200 * 39201 * Access analytics storage operations using Iceberg tables. 39202 * 39203 * **Public alpha:** This API is part of a public alpha release and may not be available to your account type. 39204 * 39205 * @category Storage 39206 * @subcategory Analytics Buckets 39207 * 39208 * @returns A StorageAnalyticsClient instance configured with the current storage settings. 39209 */ 39210 get analytics() { 39211 return new CT(this.url + "/iceberg", this.headers, this.fetch); 39212 } 39213}; 39214const Lm = "2.108.1", qi = 30 * 1e3, Ys = 3, jl = Ys * qi, kT = "http://localhost:9999", FT = "supabase.auth.token", BT = { "X-Client-Info": `gotrue-js/${Lm}` }, pu = "X-Supabase-Api-Version", Nm = { 39215 "2024-01-01": { 39216 timestamp: Date.parse("2024-01-01T00:00:00.0Z"), 39217 name: "2024-01-01" 39218 } 39219}, zT = /^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i, HT = 600 * 1e3;
39220class pa extends Error { 39221 constructor(e, t, i) { 39222 super(e), this.__isAuthError = !0, this.name = "AuthError", this.status = t, this.code = i; 39223 } 39224 toJSON() { 39225 return { 39226 name: this.name, 39227 message: this.message, 39228 status: this.status, 39229 code: this.code 39230 }; 39231 } 39232} 39233function Re(n) { 39234 return typeof n == "object" && n !== null && "__isAuthError" in n; 39235} 39236class GT extends pa { 39237 constructor(e, t, i) { 39238 super(e, t, i), this.name = "AuthApiError", this.status = t, this.code = i; 39239 } 39240} 39241function VT(n) { 39242 return Re(n) && n.name === "AuthApiError"; 39243} 39244class ei extends pa { 39245 constructor(e, t) { 39246 super(e), this.name = "AuthUnknownError", this.originalError = t; 39247 } 39248} 39249class yi extends pa { 39250 constructor(e, t, i, r) { 39251 super(e, i, r), this.name = t, this.status = i; 39252 } 39253} 39254class nn extends yi { 39255 constructor() { 39256 super("Auth session missing!", "AuthSessionMissingError", 400, void 0); 39257 } 39258} 39259function oo(n) { 39260 return Re(n) && n.name === "AuthSessionMissingError"; 39261} 39262class es extends yi { 39263 constructor() {
39264 super("Auth session or user missing", "AuthInvalidTokenResponseError", 500, void 0); 39265 } 39266} 39267class lo extends yi { 39268 constructor(e) { 39269 super(e, "AuthInvalidCredentialsError", 400, void 0); 39270 } 39271} 39272class co extends yi { 39273 constructor(e, t = null) { 39274 super(e, "AuthImplicitGrantRedirectError", 500, void 0), this.details = null, this.details = t; 39275 } 39276 toJSON() { 39277 return Object.assign(Object.assign({}, super.toJSON()), { details: this.details }); 39278 } 39279} 39280function WT(n) { 39281 return Re(n) && n.name === "AuthImplicitGrantRedirectError"; 39282} 39283class ff extends yi { 39284 constructor(e, t = null) { 39285 super(e, "AuthPKCEGrantCodeExchangeError", 500, void 0), this.details = null, this.details = t; 39286 } 39287 toJSON() { 39288 return Object.assign(Object.assign({}, super.toJSON()), { details: this.details }); 39289 } 39290} 39291class $T extends yi { 39292 constructor() { 39293 super("PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.", "AuthPKCECodeVerifierMissingError", 400, "pkce_code_verifier_not_found"); 39294 } 39295} 39296class mu extends yi { 39297 constructor(e, t) { 39298 super(e, "AuthRetryableFetchError", t, void 0); 39299 } 39300} 39301function Xl(n) { 39302 return Re(n) && n.name === "AuthRetryableFetchError"; 39303} 39304class pf extends yi { 39305 constructor(e = "Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)") { 39306 super(e, "AuthRefreshDiscardedError", 409, void 0); 39307 } 39308} 39309function jT(n) { 39310 return Re(n) && n.name === "AuthRefreshDiscardedError"; 39311} 39312class mf extends yi { 39313 constructor(e, t, i) { 39314 super(e, "AuthWeakPasswordError", t, "weak_password"), this.reasons = i; 39315 } 39316 toJSON() { 39317 return Object.assign(Object.assign({}, super.toJSON()), { reasons: this.reasons }); 39318 } 39319} 39320class Oo extends yi { 39321 constructor(e) { 39322 super(e, "AuthInvalidJwtError", 400, "invalid_jwt"); 39323 } 39324} 39325const ko = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""), gf = ` 39326\r=`.split(""), XT = (() => { 39327 const n = new Array(128); 39328 for (let e = 0; e < n.length; e += 1) 39329 n[e] = -1; 39330 for (let e = 0; e < gf.length; e += 1) 39331 n[gf[e].charCodeAt(0)] = -2; 39332 for (let e = 0; e < ko.length; e += 1) 39333 n[ko[e].charCodeAt(0)] = e; 39334 return n; 39335})(); 39336function vf(n, e, t) { 39337 if (n !== null) 39338 for (e.queue = e.queue << 8 | n, e.queuedBits += 8; e.queuedBits >= 6; ) { 39339 const i = e.queue >> e.queuedBits - 6 & 63; 39340 t(ko[i]), e.queuedBits -= 6; 39341 } 39342 else if (e.queuedBits > 0) 39343 for (e.queue = e.queue << 6 - e.queuedBits, e.queuedBits = 6; e.queuedBits >= 6; ) { 39344 const i = e.queue >> e.queuedBits - 6 & 63; 39345 t(ko[i]), e.queuedBits -= 6; 39346 } 39347} 39348function Im(n, e, t) { 39349 const i = XT[n]; 39350 if (i > -1) 39351 for (e.queue = e.queue << 6 | i, e.queuedBits += 6; e.queuedBits >= 8; ) 39352 t(e.queue >> e.queuedBits - 8 & 255), e.queuedBits -= 8; 39353 else { 39354 if (i === -2) 39355 return; 39356 throw new Error(`Invalid Base64-URL character "${String.fromCharCode(n)}"`); 39357 } 39358} 39359function _f(n) { 39360 const e = [], t = (a) => { 39361 e.push(String.fromCodePoint(a)); 39362 }, i = { 39363 utf8seq: 0, 39364 codepoint: 0 39365 }, r = { queue: 0, queuedBits: 0 }, s = (a) => { 39366 KT(a, i, t); 39367 }; 39368 for (let a = 0; a < n.length; a += 1) 39369 Im(n.charCodeAt(a), r, s); 39370 return e.join(""); 39371} 39372function qT(n, e) { 39373 if (n <= 127) { 39374 e(n); 39375 return; 39376 } else if (n <= 2047) { 39377 e(192 | n >> 6), e(128 | n & 63); 39378 return; 39379 } else if (n <= 65535) { 39380 e(224 | n >> 12), e(128 | n >> 6 & 63), e(128 | n & 63); 39381 return; 39382 } else if (n <= 1114111) { 39383 e(240 | n >> 18), e(128 | n >> 12 & 63), e(128 | n >> 6 & 63), e(128 | n & 63); 39384 return; 39385 } 39386 throw new Error(`Unrecognized Unicode codepoint: ${n.toString(16)}`); 39387} 39388function YT(n, e) { 39389 for (let t = 0; t < n.length; t += 1) { 39390 let i = n.charCodeAt(t); 39391 if (i > 55295 && i <= 56319) { 39392 const r = (i - 55296) * 1024 & 65535; 39393 i = (n.charCodeAt(t + 1) - 56320 & 65535 | r) + 65536, t += 1; 39394 } 39395 qT(i, e); 39396 } 39397} 39398function KT(n, e, t) { 39399 if (e.utf8seq === 0) { 39400 if (n <= 127) { 39401 t(n); 39402 return; 39403 } 39404 for (let i = 1; i < 6; i += 1) 39405 if ((n >> 7 - i & 1) === 0) { 39406 e.utf8seq = i; 39407 break; 39408 } 39409 if (e.utf8seq === 2) 39410 e.codepoint = n & 31; 39411 else if (e.utf8seq === 3) 39412 e.codepoint = n & 15; 39413 else if (e.utf8seq === 4) 39414 e.codepoint = n & 7; 39415 else 39416 throw new Error("Invalid UTF-8 sequence"); 39417 e.utf8seq -= 1; 39418 } else if (e.utf8seq > 0) { 39419 if (n <= 127) 39420 throw new Error("Invalid UTF-8 sequence"); 39421 e.codepoint = e.codepoint << 6 | n & 63, e.utf8seq -= 1, e.utf8seq === 0 && t(e.codepoint); 39422 } 39423} 39424function fs(n) { 39425 const e = [], t = { queue: 0, queuedBits: 0 }, i = (r) => { 39426 e.push(r); 39427 }; 39428 for (let r = 0; r < n.length; r += 1) 39429 Im(n.charCodeAt(r), t, i); 39430 return new Uint8Array(e); 39431} 39432function JT(n) { 39433 const e = []; 39434 return YT(n, (t) => e.push(t)), new Uint8Array(e); 39435} 39436function Rr(n) { 39437 const e = [], t = { queue: 0, queuedBits: 0 }, i = (r) => { 39438 e.push(r); 39439 };
39440 return n.forEach((r) => vf(r, t, i)), vf(null, t, i), e.join(""); 39441} 39442function ZT(n) { 39443 return Math.round(Date.now() / 1e3) + n; 39444} 39445function QT() { 39446 return Symbol("auth-callback"); 39447} 39448const hn = () => typeof window < "u" && typeof document < "u", vr = { 39449 tested: !1, 39450 writable: !1 39451}, Dm = () => { 39452 if (!hn()) 39453 return !1; 39454 try { 39455 if (typeof globalThis.localStorage != "object") 39456 return !1; 39457 } catch { 39458 return !1; 39459 } 39460 if (vr.tested) 39461 return vr.writable; 39462 const n = `lswt-${Math.random()}${Math.random()}`; 39463 try { 39464 globalThis.localStorage.setItem(n, n), globalThis.localStorage.removeItem(n), vr.tested = !0, vr.writable = !0; 39465 } catch { 39466 vr.tested = !0, vr.writable = !1; 39467 } 39468 return vr.writable; 39469}; 39470function e1(n) { 39471 const e = {}, t = new URL(n); 39472 if (t.hash && t.hash[0] === "#") 39473 try { 39474 new URLSearchParams(t.hash.substring(1)).forEach((r, s) => { 39475 e[s] = r; 39476 }); 39477 } catch { 39478 } 39479 return t.searchParams.forEach((i, r) => { 39480 e[r] = i; 39481 }), e; 39482} 39483const Um = (n) => n ? (...e) => n(...e) : (...e) => fetch(...e), t1 = (n) => typeof n == "object" && n !== null && "status" in n && "ok" in n && "json" in n && typeof n.json == "function", as = async (n, e, t) => { 39484 await n.setItem(e, JSON.stringify(t)); 39485}, Ai = async (n, e) => { 39486 const t = await n.getItem(e); 39487 if (!t) 39488 return null; 39489 try { 39490 return JSON.parse(t); 39491 } catch { 39492 return null; 39493 } 39494}, $t = async (n, e) => { 39495 await n.removeItem(e); 39496}; 39497class nl { 39498 constructor() { 39499 this.promise = new nl.promiseConstructor((e, t) => { 39500 this.resolve = e, this.reject = t; 39501 }); 39502 } 39503} 39504nl.promiseConstructor = Promise; 39505function uo(n) { 39506 const e = n.split("."); 39507 if (e.length !== 3) 39508 throw new Oo("Invalid JWT structure"); 39509 for (let i = 0; i < e.length; i++) 39510 if (!zT.test(e[i])) 39511 throw new Oo("JWT not in base64url format"); 39512 return { 39513 // using base64url lib 39514 header: JSON.parse(_f(e[0])), 39515 payload: JSON.parse(_f(e[1])), 39516 signature: fs(e[2]), 39517 raw: { 39518 header: e[0], 39519 payload: e[1] 39520 } 39521 }; 39522} 39523async function n1(n) { 39524 return await new Promise((e) => { 39525 setTimeout(() => e(null), n); 39526 }); 39527} 39528function i1(n, e) { 39529 return new Promise((i, r) => { 39530 (async () => { 39531 for (let s = 0; s < 1 / 0; s++) 39532 try { 39533 const a = await n(s); 39534 if (!e(s, null, a)) { 39535 i(a); 39536 return; 39537 } 39538 } catch (a) { 39539 if (!e(s, a)) { 39540 r(a); 39541 return; 39542 } 39543 } 39544 })(); 39545 }); 39546} 39547function r1(n) { 39548 return ("0" + n.toString(16)).substr(-2); 39549} 39550function s1() { 39551 const e = new Uint32Array(56); 39552 if (typeof crypto > "u") { 39553 const t = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~", i = t.length; 39554 let r = ""; 39555 for (let s = 0; s < 56; s++) 39556 r += t.charAt(Math.floor(Math.random() * i)); 39557 return r; 39558 } 39559 return crypto.getRandomValues(e), Array.from(e, r1).join(""); 39560} 39561async function a1(n) { 39562 const t = new TextEncoder().encode(n), i = await crypto.subtle.digest("SHA-256", t), r = new Uint8Array(i); 39563 return Array.from(r).map((s) => String.fromCharCode(s)).join(""); 39564} 39565async function o1(n) { 39566 if (!(typeof crypto < "u" && typeof crypto.subtle < "u" && typeof TextEncoder < "u")) 39567 return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."), n; 39568 const t = await a1(n); 39569 return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); 39570} 39571async function _r(n, e, t = !1) { 39572 const i = s1(); 39573 let r = i; 39574 t && (r += "/recovery"), await as(n, `${e}-code-verifier`, r); 39575 const s = await o1(i); 39576 return [s, i === s ? "plain" : "s256"]; 39577} 39578const l1 = /^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i; 39579function c1(n) { 39580 const e = n.headers.get(pu); 39581 if (!e || !e.match(l1)) 39582 return null; 39583 try { 39584 return /* @__PURE__ */ new Date(`${e}T00:00:00.0Z`); 39585 } catch { 39586 return null; 39587 } 39588} 39589function u1(n) { 39590 if (!n) 39591 throw new Error("Missing exp claim"); 39592 const e = Math.floor(Date.now() / 1e3); 39593 if (n <= e) 39594 throw new Error("JWT has expired"); 39595} 39596function h1(n) { 39597 switch (n) { 39598 case "RS256": 39599 return { 39600 name: "RSASSA-PKCS1-v1_5", 39601 hash: { name: "SHA-256" } 39602 }; 39603 case "ES256": 39604 return { 39605 name: "ECDSA", 39606 namedCurve: "P-256", 39607 hash: { name: "SHA-256" } 39608 }; 39609 default: 39610 throw new Error("Invalid alg claim"); 39611 } 39612} 39613const d1 = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; 39614function Ri(n) { 39615 if (!d1.test(n)) 39616 throw new Error("@supabase/auth-js: Expected parameter to be UUID but is not"); 39617} 39618function Kn(n) { 39619 if (!n.passkey) 39620 throw new Error("@supabase/auth-js: the passkey API is experimental and disabled by default. Enable it by passing `auth: { experimental: { passkey: true } }` to createClient (or to the GoTrueClient constructor)."); 39621} 39622function ql() { 39623 const n = {}; 39624 return new Proxy(n, { 39625 get: (e, t) => { 39626 if (t === "__isUserNotAvailableProxy") 39627 return !0; 39628 if (typeof t == "symbol") { 39629 const i = t.toString(); 39630 if (i === "Symbol(Symbol.toPrimitive)" || i === "Symbol(Symbol.toStringTag)" || i === "Symbol(util.inspect.custom)") 39631 return; 39632 } 39633 throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`); 39634 }, 39635 set: (e, t) => { 39636 throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`); 39637 }, 39638 deleteProperty: (e, t) => { 39639 throw new Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`); 39640 } 39641 }); 39642} 39643function f1(n, e) { 39644 return new Proxy(n, { 39645 get: (t, i, r) => { 39646 if (i === "__isInsecureUserWarningProxy") 39647 return !0; 39648 if (typeof i == "symbol") { 39649 const s = i.toString(); 39650 if (s === "Symbol(Symbol.toPrimitive)" || s === "Symbol(Symbol.toStringTag)" || s === "Symbol(util.inspect.custom)" || s === "Symbol(nodejs.util.inspect.custom)") 39651 return Reflect.get(t, i, r); 39652 } 39653 return !e.value && typeof i == "string" && (console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."), e.value = !0), Reflect.get(t, i, r); 39654 } 39655 }); 39656} 39657function yf(n) { 39658 return JSON.parse(JSON.stringify(n)); 39659} 39660const br = (n) => { 39661 if (typeof n == "object" && n !== null) { 39662 const e = n; 39663 if (typeof e.msg == "string") 39664 return e.msg; 39665 if (typeof e.message == "string") 39666 return e.message; 39667 if (typeof e.error_description == "string") 39668 return e.error_description; 39669 if (typeof e.error == "string") 39670 return e.error; 39671 } 39672 return JSON.stringify(n); 39673}, p1 = [502, 503, 504, 520, 521, 522, 523, 524, 530]; 39674async function xf(n) { 39675 var e; 39676 if (!t1(n)) 39677 throw new mu(br(n), 0); 39678 if (p1.includes(n.status)) 39679 throw new mu(br(n), n.status); 39680 let t; 39681 try { 39682 t = await n.json(); 39683 } catch (s) { 39684 throw new ei(br(s), s); 39685 } 39686 let i; 39687 const r = c1(n); 39688 if (r && r.getTime() >= Nm["2024-01-01"].timestamp && typeof t == "object" && t && typeof t.code == "string" ? i = t.code : typeof t == "object" && t && typeof t.error_code == "string" && (i = t.error_code), i) { 39689 if (i === "weak_password") 39690 throw new mf(br(t), n.status, ((e = t.weak_password) === null || e === void 0 ? void 0 : e.reasons) || []); 39691 if (i === "session_not_found") 39692 throw new nn(); 39693 } else if (typeof t == "object" && t && typeof t.weak_password == "object" && t.weak_password && Array.isArray(t.weak_password.reasons) && t.weak_password.reasons.length && t.weak_password.reasons.reduce((s, a) => s && typeof a == "string", !0)) 39694 throw new mf(br(t), n.status, t.weak_password.reasons); 39695 throw new GT(br(t), n.status || 500, i); 39696} 39697const m1 = (n, e, t, i) => { 39698 const r = { method: n, headers: e?.headers || {} }; 39699 return n === "GET" ? r : (r.headers = Object.assign({ "Content-Type": "application/json;charset=UTF-8" }, e?.headers), r.body = JSON.stringify(i), Object.assign(Object.assign({}, r), t)); 39700}; 39701async function He(n, e, t, i) { 39702 var r; 39703 const s = Object.assign({}, i?.headers); 39704 s[pu] || (s[pu] = Nm["2024-01-01"].name), i?.jwt && (s.Authorization = `Bearer ${i.jwt}`); 39705 const a = (r = i?.query) !== null && r !== void 0 ? r : {}; 39706 i?.redirectTo && (a.redirect_to = i.redirectTo); 39707 const l = Object.keys(a).length ? "?" + new URLSearchParams(a).toString() : "", o = await g1(n, e, t + l, { 39708 headers: s, 39709 noResolveJson: i?.noResolveJson 39710 }, {}, i?.body); 39711 return i?.xform ? i?.xform(o) : { data: Object.assign({}, o), error: null }; 39712} 39713async function g1(n, e, t, i, r, s) { 39714 const a = m1(e, i, r, s); 39715 let l; 39716 try { 39717 l = await n(t, Object.assign({}, a)); 39718 } catch (o) {
39719 throw console.error(o), new mu(br(o), 0); 39720 } 39721 if (l.ok || await xf(l), i?.noResolveJson) 39722 return l; 39723 try { 39724 return await l.json(); 39725 } catch (o) { 39726 await xf(o); 39727 } 39728} 39729function Bn(n) { 39730 var e; 39731 let t = null; 39732 y1(n) && (t = Object.assign({}, n), n.expires_at || (t.expires_at = ZT(n.expires_in))); 39733 const i = (e = n.user) !== null && e !== void 0 ? e : typeof n?.id == "string" ? n : null; 39734 return { data: { session: t, user: i }, error: null }; 39735} 39736function bf(n) { 39737 const e = Bn(n); 39738 return !e.error && n.weak_password && typeof n.weak_password == "object" && Array.isArray(n.weak_password.reasons) && n.weak_password.reasons.length && n.weak_password.message && typeof n.weak_password.message == "string" && n.weak_password.reasons.reduce((t, i) => t && typeof i == "string", !0) && (e.data.weak_password = n.weak_password), e; 39739} 39740function Qi(n) { 39741 var e; 39742 return { data: { user: (e = n.user) !== null && e !== void 0 ? e : n }, error: null }; 39743} 39744function v1(n) { 39745 return { data: n, error: null }; 39746} 39747function _1(n) { 39748 const { action_link: e, email_otp: t, hashed_token: i, redirect_to: r, verification_type: s } = n, a = Qo(n, ["action_link", "email_otp", "hashed_token", "redirect_to", "verification_type"]), l = { 39749 action_link: e, 39750 email_otp: t, 39751 hashed_token: i, 39752 redirect_to: r, 39753 verification_type: s 39754 }, o = Object.assign({}, a); 39755 return { 39756 data: { 39757 properties: l, 39758 user: o 39759 }, 39760 error: null 39761 }; 39762} 39763function wf(n) { 39764 return n; 39765} 39766function y1(n) { 39767 return !!n.access_token && !!n.refresh_token && !!n.expires_in; 39768} 39769const Yl = ["global", "local", "others"]; 39770class x1 { 39771 /** 39772 * Creates an admin API client that can be used to manage users and OAuth clients. 39773 * 39774 * @example Using supabase-js (recommended) 39775 * ```ts 39776 * import { createClient } from '@supabase/supabase-js' 39777 * 39778 * const supabase = createClient('https://xyzcompany.supabase.co', 'your-secret-key') 39779 * const { data, error } = await supabase.auth.admin.listUsers() 39780 * ``` 39781 * 39782 * @example Standalone import for bundle-sensitive environments 39783 * ```ts 39784 * import { GoTrueAdminApi } from '@supabase/auth-js' 39785 * 39786 * const admin = new GoTrueAdminApi({ 39787 * url: 'https://xyzcompany.supabase.co/auth/v1', 39788 * headers: { Authorization: `Bearer ${process.env.SUPABASE_SECRET_KEY}` }, 39789 * }) 39790 * ``` 39791 */ 39792 constructor({ url: e = "", headers: t = {}, fetch: i, experimental: r }) { 39793 this.url = e, this.headers = t, this.fetch = Um(i), this.experimental = r ?? {}, this.mfa = { 39794 listFactors: this._listFactors.bind(this), 39795 deleteFactor: this._deleteFactor.bind(this) 39796 }, this.oauth = { 39797 listClients: this._listOAuthClients.bind(this), 39798 createClient: this._createOAuthClient.bind(this), 39799 getClient: this._getOAuthClient.bind(this), 39800 updateClient: this._updateOAuthClient.bind(this), 39801 deleteClient: this._deleteOAuthClient.bind(this), 39802 regenerateClientSecret: this._regenerateOAuthClientSecret.bind(this) 39803 }, this.customProviders = { 39804 listProviders: this._listCustomProviders.bind(this), 39805 createProvider: this._createCustomProvider.bind(this), 39806 getProvider: this._getCustomProvider.bind(this), 39807 updateProvider: this._updateCustomProvider.bind(this), 39808 deleteProvider: this._deleteCustomProvider.bind(this) 39809 }, this.passkey = { 39810 listPasskeys: this._adminListPasskeys.bind(this), 39811 deletePasskey: this._adminDeletePasskey.bind(this) 39812 }; 39813 } 39814 /** 39815 * Removes a logged-in session. 39816 * @param jwt A valid, logged-in JWT. 39817 * @param scope The logout sope. 39818 * 39819 * @category Auth 39820 * @subcategory Auth Admin 39821 */ 39822 async signOut(e, t = Yl[0]) { 39823 if (Yl.indexOf(t) < 0) 39824 throw new Error(`@supabase/auth-js: Parameter scope must be one of ${Yl.join(", ")}`); 39825 try { 39826 return await He(this.fetch, "POST", `${this.url}/logout?scope=${t}`, { 39827 headers: this.headers, 39828 jwt: e, 39829 noResolveJson: !0 39830 }), { data: null, error: null }; 39831 } catch (i) { 39832 if (Re(i)) 39833 return { data: null, error: i }; 39834 throw i; 39835 } 39836 } 39837 /** 39838 * Sends an invite link to an email address. 39839 * @param email The email address of the user. 39840 * @param options Additional options to be included when inviting. 39841 * 39842 * @category Auth 39843 * @subcategory Auth Admin 39844 * 39845 * @remarks 39846 * - Sends an invite link to the user's email address. 39847 * - The `inviteUserByEmail()` method is typically used by administrators to invite users to join the application. 39848 * - Note that PKCE is not supported when using `inviteUserByEmail`. This is because the browser initiating the invite is often different from the browser accepting the invite which makes it difficult to provide the security guarantees required of the PKCE flow. 39849 * 39850 * @example Invite a user 39851 * ```js 39852 * const { data, error } = await supabase.auth.admin.inviteUserByEmail('[email protected]') 39853 * ``` 39854 * 39855 * @exampleResponse Invite a user 39856 * ```json 39857 * { 39858 * "data": { 39859 * "user": { 39860 * "id": "11111111-1111-1111-1111-111111111111", 39861 * "aud": "authenticated", 39862 * "role": "authenticated", 39863 * "email": "[email protected]", 39864 * "invited_at": "2024-01-01T00:00:00Z", 39865 * "phone": "", 39866 * "confirmation_sent_at": "2024-01-01T00:00:00Z", 39867 * "app_metadata": { 39868 * "provider": "email", 39869 * "providers": [ 39870 * "email" 39871 * ] 39872 * }, 39873 * "user_metadata": {}, 39874 * "identities": [ 39875 * { 39876 * "identity_id": "22222222-2222-2222-2222-222222222222", 39877 * "id": "11111111-1111-1111-1111-111111111111", 39878 * "user_id": "11111111-1111-1111-1111-111111111111", 39879 * "identity_data": { 39880 * "email": "[email protected]", 39881 * "email_verified": false, 39882 * "phone_verified": false, 39883 * "sub": "11111111-1111-1111-1111-111111111111" 39884 * }, 39885 * "provider": "email", 39886 * "last_sign_in_at": "2024-01-01T00:00:00Z", 39887 * "created_at": "2024-01-01T00:00:00Z", 39888 * "updated_at": "2024-01-01T00:00:00Z", 39889 * "email": "[email protected]" 39890 * } 39891 * ], 39892 * "created_at": "2024-01-01T00:00:00Z", 39893 * "updated_at": "2024-01-01T00:00:00Z", 39894 * "is_anonymous": false 39895 * } 39896 * }, 39897 * "error": null 39898 * } 39899 * ``` 39900 */
39901 async inviteUserByEmail(e, t = {}) { 39902 try { 39903 return await He(this.fetch, "POST", `${this.url}/invite`, { 39904 body: { email: e, data: t.data }, 39905 headers: this.headers, 39906 redirectTo: t.redirectTo, 39907 xform: Qi 39908 }); 39909 } catch (i) { 39910 if (Re(i)) 39911 return { data: { user: null }, error: i }; 39912 throw i; 39913 } 39914 } 39915 /** 39916 * Generates email links and OTPs to be sent via a custom email provider. 39917 * @param email The user's email. 39918 * @param options.password User password. For signup only. 39919 * @param options.data Optional user metadata. For signup only. 39920 * @param options.redirectTo The redirect url which should be appended to the generated link 39921 * 39922 * @category Auth 39923 * @subcategory Auth Admin 39924 * 39925 * @remarks 39926 * - The following types can be passed into `generateLink()`: `signup`, `magiclink`, `invite`, `recovery`, `email_change_current`, `email_change_new`, `phone_change`. 39927 * - `generateLink()` only generates the email link for `email_change_email` if the **Secure email change** is enabled in your project's [email auth provider settings](/dashboard/project/_/auth/providers). 39928 * - `generateLink()` handles the creation of the user for `signup`, `invite` and `magiclink`. 39929 * 39930 * @example Generate a signup link 39931 * ```js 39932 * const { data, error } = await supabase.auth.admin.generateLink({ 39933 * type: 'signup', 39934 * email: '[email protected]', 39935 * password: 'secret' 39936 * }) 39937 * ``` 39938 * 39939 * @exampleResponse Generate a signup link 39940 * ```json 39941 * { 39942 * "data": { 39943 * "properties": { 39944 * "action_link": "<LINK_TO_SEND_TO_USER>", 39945 * "email_otp": "999999", 39946 * "hashed_token": "<HASHED_TOKEN", 39947 * "redirect_to": "<REDIRECT_URL>", 39948 * "verification_type": "signup" 39949 * }, 39950 * "user": { 39951 * "id": "11111111-1111-1111-1111-111111111111", 39952 * "aud": "authenticated", 39953 * "role": "authenticated", 39954 * "email": "[email protected]", 39955 * "phone": "", 39956 * "confirmation_sent_at": "2024-01-01T00:00:00Z", 39957 * "app_metadata": { 39958 * "provider": "email", 39959 * "providers": [ 39960 * "email" 39961 * ] 39962 * }, 39963 * "user_metadata": {}, 39964 * "identities": [ 39965 * { 39966 * "identity_id": "22222222-2222-2222-2222-222222222222", 39967 * "id": "11111111-1111-1111-1111-111111111111", 39968 * "user_id": "11111111-1111-1111-1111-111111111111", 39969 * "identity_data": { 39970 * "email": "[email protected]", 39971 * "email_verified": false, 39972 * "phone_verified": false, 39973 * "sub": "11111111-1111-1111-1111-111111111111" 39974 * }, 39975 * "provider": "email", 39976 * "last_sign_in_at": "2024-01-01T00:00:00Z", 39977 * "created_at": "2024-01-01T00:00:00Z", 39978 * "updated_at": "2024-01-01T00:00:00Z", 39979 * "email": "[email protected]" 39980 * } 39981 * ], 39982 * "created_at": "2024-01-01T00:00:00Z", 39983 * "updated_at": "2024-01-01T00:00:00Z", 39984 * "is_anonymous": false 39985 * } 39986 * }, 39987 * "error": null 39988 * } 39989 * ``` 39990 * 39991 * @example Generate an invite link 39992 * ```js 39993 * const { data, error } = await supabase.auth.admin.generateLink({ 39994 * type: 'invite', 39995 * email: '[email protected]' 39996 * }) 39997 * ``` 39998 * 39999 * @example Generate a magic link 40000 * ```js 40001 * const { data, error } = await supabase.auth.admin.generateLink({ 40002 * type: 'magiclink', 40003 * email: '[email protected]' 40004 * }) 40005 * ``` 40006 * 40007 * @example Generate a recovery link 40008 * ```js 40009 * const { data, error } = await supabase.auth.admin.generateLink({ 40010 * type: 'recovery', 40011 * email: '[email protected]' 40012 * }) 40013 * ``` 40014 * 40015 * @example Generate links to change current email address 40016 * ```js 40017 * // generate an email change link to be sent to the current email address 40018 * const { data, error } = await supabase.auth.admin.generateLink({ 40019 * type: 'email_change_current', 40020 * email: '[email protected]', 40021 * newEmail: '[email protected]' 40022 * }) 40023 * 40024 * // generate an email change link to be sent to the new email address 40025 * const { data, error } = await supabase.auth.admin.generateLink({ 40026 * type: 'email_change_new', 40027 * email: '[email protected]', 40028 * newEmail: '[email protected]' 40029 * }) 40030 * ``` 40031 */ 40032 async generateLink(e) { 40033 try { 40034 const { options: t }
40034 = e, i = Qo(e, ["options"]), r = Object.assign(Object.assign({}, i), t); 40035 return "newEmail" in i && (r.new_email = i?.newEmail, delete r.newEmail), await He(this.fetch, "POST", `${this.url}/admin/generate_link`, { 40036 body: r, 40037 headers: this.headers, 40038 xform: _1, 40039 redirectTo: t?.redirectTo 40040 }); 40041 } catch (t) { 40042 if (Re(t)) 40043 return { 40044 data: { 40045 properties: null, 40046 user: null 40047 }, 40048 error: t 40049 }; 40050 throw t; 40051 } 40052 } 40053 // User Admin API 40054 /** 40055 * Creates a new user. 40056 * This function should only be called on a server. Never expose your `service_role` key in the browser. 40057 * 40058 * @category Auth 40059 * @subcategory Auth Admin 40060 * 40061 * @remarks 40062 * - To confirm the user's email address or phone number, set `email_confirm` or `phone_confirm` to true. Both arguments default to false. 40063 * - `createUser()` will not send a confirmation email to the user. You can use [`inviteUserByEmail()`](/docs/reference/javascript/auth-admin-inviteuserbyemail) if you want to send them an email invite instead. 40064 * - If you are sure that the created user's email or phone number is legitimate and verified, you can set the `email_confirm` or `phone_confirm` param to `true`. 40065 * 40066 * @example With custom user metadata 40067 * ```js 40068 * const { data, error } = await supabase.auth.admin.createUser({ 40069 * email: '[email protected]', 40070 * password: 'password', 40071 * user_metadata: { name: 'Yoda' } 40072 * }) 40073 * ``` 40074 * 40075 * @exampleResponse With custom user metadata 40076 * ```json 40077 * { 40078 * data: { 40079 * user: { 40080 * id: '1', 40081 * aud: 'authenticated', 40082 * role: 'authenticated', 40083 * email: '[email protected]', 40084 * email_confirmed_at: '2024-01-01T00:00:00Z', 40085 * phone: '', 40086 * confirmation_sent_at: '2024-01-01T00:00:00Z', 40087 * confirmed_at: '2024-01-01T00:00:00Z', 40088 * last_sign_in_at: '2024-01-01T00:00:00Z', 40089 * app_metadata: {}, 40090 * user_metadata: {}, 40091 * identities: [ 40092 * { 40093 * "identity_id": "22222222-2222-2222-2222-222222222222", 40094 * "id": "1", 40095 * "user_id": "1", 40096 * "identity_data": { 40097 * "email": "[email protected]", 40098 * "email_verified": true, 40099 * "phone_verified": false, 40100 * "sub": "1" 40101 * }, 40102 * "provider": "email", 40103 * "last_sign_in_at": "2024-01-01T00:00:00Z", 40104 * "created_at": "2024-01-01T00:00:00Z", 40105 * "updated_at": "2024-01-01T00:00:00Z", 40106 * "email": "[email protected]" 40107 * }, 40108 * ], 40109 * created_at: '2024-01-01T00:00:00Z', 40110 * updated_at: '2024-01-01T00:00:00Z', 40111 * is_anonymous: false, 40112 * } 40113 * } 40114 * error: null 40115 * } 40116 * ``` 40117 * 40118 * @example Auto-confirm the user's email 40119 * ```js 40120 * const { data, error } = await supabase.auth.admin.createUser({ 40121 * email: '[email protected]', 40122 * email_confirm: true 40123 * }) 40124 * ``` 40125 * 40126 * @example Auto-confirm the user's phone number 40127 * ```js 40128 * const { data, error } = await supabase.auth.admin.createUser({ 40129 * phone: '1234567890', 40130 * phone_confirm: true 40131 * }) 40132 * ``` 40133 */ 40134 async createUser(e) { 40135 try { 40136 return await He(this.fetch, "POST", `${this.url}/admin/users`, { 40137 body: e, 40138 headers: this.headers, 40139 xform: Qi 40140 }); 40141 } catch (t) { 40142 if (Re(t)) 40143 return { data: { user: null }, error: t }; 40144 throw t; 40145 } 40146 } 40147 /** 40148 * Get a list of users. 40149 * 40150 * This function should only be called on a server. Never expose your `service_role` key in the browser. 40151 * @param params An object which supports `page` and `perPage` as numbers, to alter the paginated results. 40152 * 40153 * @category Auth 40154 * @subcategory Auth Admin 40155 * 40156 * @remarks 40157 * - Defaults to return 50 users per page. 40158 * 40159 * @example Get a page of users 40160 * ```js 40161 * const { data: { users }, error } = await supabase.auth.admin.listUsers() 40162 * ``` 40163 * 40164 * @example Paginated list of users 40165 * ```js 40166 * const { data: { users }, error } = await supabase.auth.admin.listUsers({ 40167 * page: 1, 40168 * perPage: 1000 40169 * }) 40170 * ``` 40171 */ 40172 async listUsers(e) { 40173 var t, i, r, s, a, l, o; 40174 try { 40175 const c = { nextPage: null, lastPage: 0, total: 0 }, u = await He(this.fetch, "GET", `${this.url}/admin/users`, { 40176 headers: this.headers, 40177 noResolveJson: !0, 40178 query: { 40179 page: (i = (t = e?.page) === null || t === void 0 ? void 0 : t.toString()) !== null && i !== void 0 ? i : "", 40180 per_page: (s = (r = e?.perPage) === null || r === void 0 ? void 0 : r.toString()) !== null && s !== void 0 ? s : "" 40181 }, 40182 xform: wf 40183 }); 40184 if (u.error) 40185 throw u.error; 40186 const h = await u.json(), d = (a = u.headers.get("x-total-count")) !== null && a !== void 0 ? a : 0, f = (o = (l = u.headers.get("link")) === null || l === void 0 ? void 0 : l.split(",")) !== null && o !== void 0 ? o : []; 40187 return f.length > 0 && (f.forEach((p) => { 40188 const v = parseInt(p.split(";")[0].split("=")[1].substring(0, 1)), m = JSON.parse(p.split(";")[1].split("=")[1]); 40189 c[`${m}
40189Page`] = v; 40190 }), c.total = parseInt(d)), { data: Object.assign(Object.assign({}, h), c), error: null }; 40191 } catch (c) { 40192 if (Re(c)) 40193 return { data: { users: [] }, error: c }; 40194 throw c; 40195 } 40196 } 40197 /** 40198 * Get user by id. 40199 * 40200 * @param uid The user's unique identifier 40201 * 40202 * This function should only be called on a server. Never expose your `service_role` key in the browser. 40203 * 40204 * @category Auth 40205 * @subcategory Auth Admin 40206 * 40207 * @remarks 40208 * - Fetches the user object from the database based on the user's id. 40209 * - The `getUserById()` method requires the user's id which maps to the `auth.users.id` column. 40210 * 40211 * @example Fetch the user object using the access_token jwt 40212 * ```js 40213 * const { data, error } = await supabase.auth.admin.getUserById(1) 40214 * ``` 40215 * 40216 * @exampleResponse Fetch the user object using the access_token jwt 40217 * ```json 40218 * { 40219 * data: { 40220 * user: { 40221 * id: '1', 40222 * aud: 'authenticated', 40223 * role: 'authenticated', 40224 * email: '[email protected]', 40225 * email_confirmed_at: '2024-01-01T00:00:00Z', 40226 * phone: '', 40227 * confirmation_sent_at: '2024-01-01T00:00:00Z', 40228 * confirmed_at: '2024-01-01T00:00:00Z', 40229 * last_sign_in_at: '2024-01-01T00:00:00Z', 40230 * app_metadata: {}, 40231 * user_metadata: {}, 40232 * identities: [ 40233 * { 40234 * "identity_id": "22222222-2222-2222-2222-222222222222", 40235 * "id": "1", 40236 * "user_id": "1", 40237 * "identity_data": { 40238 * "email": "[email protected]", 40239 * "email_verified": true, 40240 * "phone_verified": false, 40241 * "sub": "1" 40242 * }, 40243 * "provider": "email", 40244 * "last_sign_in_at": "2024-01-01T00:00:00Z", 40245 * "created_at": "2024-01-01T00:00:00Z", 40246 * "updated_at": "2024-01-01T00:00:00Z", 40247 * "email": "[email protected]" 40248 * }, 40249 * ], 40250 * created_at: '2024-01-01T00:00:00Z', 40251 * updated_at: '2024-01-01T00:00:00Z', 40252 * is_anonymous: false, 40253 * } 40254 * } 40255 * error: null 40256 * } 40257 * ``` 40258 */ 40259 async getUserById(e) { 40260 Ri(e); 40261 try { 40262 return await He(this.fetch, "GET", `${this.url}/admin/users/${e}`, { 40263 headers: this.headers, 40264 xform: Qi 40265 }); 40266 } catch (t) { 40267 if (Re(t)) 40268 return { data: { user: null }, error: t }; 40269 throw t; 40270 } 40271 } 40272 /** 40273 * Updates the user data. Changes are applied directly without confirmation flows. 40274 * 40275 * @param uid The user's unique identifier 40276 * @param attributes The data you want to update. 40277 * 40278 * This function should only be called on a server. Never expose your `service_role` key in the browser. 40279 * 40280 * @remarks 40281 * **Important:** This is a server-side operation and does **not** trigger client-side 40282 * `onAuthStateChange` listeners. The admin API has no connection to client state. 40283 * 40284 * To sync changes to the client after calling this method: 40285 * 1. On the client, call `supabase.auth.refreshSession()` to fetch the updated user data 40286 * 2. This will trigger the `TOKEN_REFRESHED` event and notify all listeners 40287 * 40288 * @example 40289 * ```typescript 40290 * // Server-side (Edge Function) 40291 * const { data, error } = await supabase.auth.admin.updateUserById( 40292 * userId, 40293 * { user_metadata: { preferences: { theme: 'dark' } } } 40294 * ) 40295 * 40296 * // Client-side (to sync the changes) 40297 * const { data, error } = await supabase.auth.refreshSession() 40298 * // onAuthStateChange listeners will now be notified with updated user 40299 * ``` 40300 * 40301 * @see {@link GoTrueClient.refreshSession} for syncing admin changes to the client 40302 * @see {@link GoTrueClient.updateUser} for client-side user updates (triggers listeners automatically) 40303 * 40304 * @category Auth 40305 * @subcategory Auth Admin 40306 * 40307 * @example Updates a user's email 40308 * ```js 40309 * const { data: user, error } = await supabase.auth.admin.updateUserById( 40310 * '11111111-1111-1111-1111-111111111111', 40311 * { email: '[email protected]' } 40312 * ) 40313 * ``` 40314 * 40315 * @exampleResponse Updates a user's email 40316 * ```json 40317 * { 40318 * "data": { 40319 * "user": { 40320 * "id": "11111111-1111-1111-1111-111111111111", 40321 * "aud": "authenticated", 40322 * "role": "authenticated", 40323 * "email": "[email protected]", 40324 * "email_confirmed_at": "2024-01-01T00:00:00Z", 40325 * "phone": "", 40326 * "confirmed_at": "2024-01-01T00:00:00Z", 40327 * "recovery_sent_at": "2024-01-01T00:00:00Z", 40328 * "last_sign_in_at": "2024-01-01T00:00:00Z", 40329 * "app_metadata": { 40330 * "provider": "email", 40331 * "providers": [ 40332 * "email" 40333 * ] 40334 * }, 40335 * "user_metadata": { 40336 * "email": "[email protected]", 40337 * "email_verified": false, 40338 * "phone_verified": false, 40339 * "sub": "11111111-1111-1111-1111-111111111111" 40340 * }, 40341 * "identities": [ 40342 * { 40343 * "identity_id": "22222222-2222-2222-2222-222222222222", 40344 * "id": "11111111-1111-1111-1111-111111111111", 40345 * "user_id": "11111111-1111-1111-1111-111111111111", 40346 * "identity_data": { 40347 * "email": "[email protected]", 40348 * "email_verified": false, 40349 * "phone_verified": false, 40350 * "sub": "11111111-1111-1111-1111-111111111111" 40351 * }, 40352 * "provider": "email", 40353 * "last_sign_in_at": "2024-01-01T00:00:00Z", 40354 * "created_at": "2024-01-01T00:00:00Z", 40355 * "updated_at": "2024-01-01T00:00:00Z", 40356 * "email": "[email protected]" 40357 * } 40358 * ], 40359 * "created_at": "2024-01-01T00:00:00Z", 40360 * "updated_at": "2024-01-01T00:00:00Z", 40361 * "is_anonymous": false 40362 * } 40363 * }, 40364 * "error": null 40365 * } 40366 * ``` 40367 * 40368 * @example Updates a user's password 40369 * ```js 40370 * const { data: user, error } = await supabase.auth.admin.updateUserById( 40371 * '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4', 40372 * { password: 'new_password' } 40373 * ) 40374 * ``` 40375 * 40376 * @example Updates a user's metadata 40377 * ```js 40378 * const { data: user, error } = await supabase.auth.admin.updateUserById( 40379 * '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4', 40380 * { user_metadata: { hello: 'world' } } 40381 * ) 40382 * ``` 40383 * 40384 * @example Updates a user's app_metadata 40385 * ```js 40386 * const { data: user, error } = await supabase.auth.admin.updateUserById( 40387 * '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4', 40388 * { app_metadata: { plan: 'trial' } } 40389 * ) 40390 * ``` 40391 * 40392 * @example Confirms a user's email address 40393 * ```js 40394 * const { data: user, error } = await supabase.auth.admin.updateUserById( 40395 * '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4', 40396 * { email_confirm: true } 40397 * ) 40398 * ``` 40399 * 40400 * @example Confirms a user's phone number 40401 * ```js 40402 * const { data: user, error } = await supabase.auth.admin.updateUserById( 40403 * '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4', 40404 * { phone_confirm: true } 40405 * ) 40406 * ``` 40407 * 40408 * @example Ban a user for 100 years 40409 * ```js 40410 * const { data: user, error } = await supabase.auth.admin.updateUserById( 40411 * '6aa5d0d4-2a9f-4483-b6c8-0cf4c6c98ac4', 40412 * { ban_duration: '876000h' } 40413 * ) 40414 * ``` 40415 */ 40416 async updateUserById(e, t) { 40417 Ri(e); 40418 try { 40419 return await He(this.fetch, "PUT", `${this.url}/admin/users/${e}`, { 40420 body: t, 40421 headers: this.headers, 40422 xform: Qi 40423 }); 40424 } catch (i) { 40425 if (Re(i)) 40426 return { data: { user: null }, error: i }; 40427 throw i; 40428 } 40429 } 40430 /** 40431 * Delete a user. Requires a `service_role` key. 40432 * 40433 * @param id The user id you want to remove. 40434 * @param shouldSoftDelete If true, then the user will be soft-deleted from the auth schema. Soft deletion allows user identification from the hashed user ID but is not reversible. 40435 * Defaults to false for backward compatibility. 40436 * 40437 * This function should only be called on a server. Never expose your `service_role` key in the browser. 40438 * 40439 * @category Auth 40440 * @subcategory Auth Admin 40441 * 40442 * @remarks 40443 * - The `deleteUser()` method requires the user's ID, which maps to the `auth.users.id` column. 40444 * 40445 * @example Removes a user 40446 * ```js 40447 * const { data, error } = await supabase.auth.admin.deleteUser( 40448 * '715ed5db-f090-4b8c-a067-640ecee36aa0' 40449 * ) 40450 * ``` 40451 * 40452 * @exampleResponse Removes a user 40453 * ```json 40454 * { 40455 * "data": { 40456 * "user": {} 40457 * }, 40458 * "error": null 40459 * } 40460 * ``` 40461 */ 40462 async deleteUser(e, t = !1) { 40463 Ri(e); 40464 try {
40465 return await He(this.fetch, "DELETE", `${this.url}/admin/users/${e}`, { 40466 headers: this.headers, 40467 body: { 40468 should_soft_delete: t 40469 }, 40470 xform: Qi 40471 }); 40472 } catch (i) { 40473 if (Re(i)) 40474 return { data: { user: null }, error: i }; 40475 throw i; 40476 } 40477 } 40478 async _listFactors(e) { 40479 Ri(e.userId); 40480 try { 40481 const { data: t, error: i } = await He(this.fetch, "GET", `${this.url}/admin/users/${e.userId}/factors`, { 40482 headers: this.headers, 40483 xform: (r) => ({ data: { factors: r }, error: null }) 40484 }); 40485 return { data: t, error: i }; 40486 } catch (t) { 40487 if (Re(t)) 40488 return { data: null, error: t }; 40489 throw t; 40490 } 40491 } 40492 async _deleteFactor(e) { 40493 Ri(e.userId), Ri(e.id); 40494 try { 40495 return { data: await He(this.fetch, "DELETE", `${this.url}/admin/users/${e.userId}/factors/${e.id}`, { 40496 headers: this.headers 40497 }), error: null }; 40498 } catch (t) { 40499 if (Re(t)) 40500 return { data: null, error: t }; 40501 throw t; 40502 } 40503 } 40504 /** 40505 * Lists all OAuth clients with optional pagination. 40506 * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. 40507 * 40508 * This function should only be called on a server. Never expose your `service_role` key in the browser. 40509 */ 40510 async _listOAuthClients(e) { 40511 var t, i, r, s, a, l, o; 40512 try { 40513 const c = { nextPage: null, lastPage: 0, total: 0 }, u = await He(this.fetch, "GET", `${this.url}/admin/oauth/clients`, { 40514 headers: this.headers, 40515 noResolveJson: !0, 40516 query: { 40517 page: (i = (t = e?.page) === null || t === void 0 ? void 0 : t.toString()) !== null && i !== void 0 ? i : "", 40518 per_page: (s = (r = e?.perPage) === null || r === void 0 ? void 0 : r.toString()) !== null && s !== void 0 ? s : "" 40519 }, 40520 xform: wf 40521 }); 40522 if (u.error) 40523 throw u.error; 40524 const h = await u.json(), d = (a = u.headers.get("x-total-count")) !== null && a !== void 0 ? a : 0, f = (o = (l = u.headers.get("link")) === null || l === void 0 ? void 0 : l.split(",")) !== null && o !== void 0 ? o : []; 40525 return f.length > 0 && (f.forEach((p) => { 40526 const v = parseInt(p.split(";")[0].split("=")[1].substring(0, 1)), m = JSON.parse(p.split(";")[1].split("=")[1]); 40527 c[`${m}Page`] = v; 40528 }), c.total = parseInt(d)), { data: Object.assign(Object.assign({}, h), c), error: null }; 40529 } catch (c) { 40530 if (Re(c)) 40531 return { data: { clients: [] }, error: c }; 40532 throw c; 40533 } 40534 } 40535 /** 40536 * Creates a new OAuth client. 40537 * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. 40538 * 40539 * This function should only be called on a server. Never expose your `service_role` key in the browser. 40540 */ 40541 async _createOAuthClient(e) { 40542 try { 40543 return await He(this.fetch, "POST", `${this.url}/admin/oauth/clients`, { 40544 body: e, 40545 headers: this.headers, 40546 xform: (t) => ({ data: t, error: null }) 40547 }); 40548 } catch (t) { 40549 if (Re(t)) 40550 return { data: null, error: t }; 40551 throw t; 40552 } 40553 } 40554 /** 40555 * Gets details of a specific OAuth client. 40556 * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. 40557 * 40558 * This function should only be called on a server. Never expose your `service_role` key in the browser. 40559 */ 40560 async _getOAuthClient(e) { 40561 try { 40562 return await He(this.fetch, "GET", `${this.url}/admin/oauth/clients/${e}`, { 40563 headers: this.headers, 40564 xform: (t) => ({ data: t, error: null }) 40565 }); 40566 } catch (t) { 40567 if (Re(t)) 40568 return { data: null, error: t }; 40569 throw t; 40570 } 40571 } 40572 /** 40573 * Updates an existing OAuth client. 40574 * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. 40575 * 40576 * This function should only be called on a server. Never expose your `service_role` key in the browser. 40577 */ 40578 async _updateOAuthClient(e, t) { 40579 try { 40580 return await He(this.fetch, "PUT", `${this.url}/admin/oauth/clients/${e}`, { 40581 body: t, 40582 headers: this.headers, 40583 xform: (i) => ({ data: i, error: null }) 40584 }); 40585 } catch (i) { 40586 if (Re(i)) 40587 return { data: null, error: i }; 40588 throw i; 40589 } 40590 } 40591 /** 40592 * Deletes an OAuth client. 40593 * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. 40594 * 40595 * This function should only be called on a server. Never expose your `service_role` key in the browser. 40596 */ 40597 async _deleteOAuthClient(e) { 40598 try {
40599 return await He(this.fetch, "DELETE", `${this.url}/admin/oauth/clients/${e}`, { 40600 headers: this.headers, 40601 noResolveJson: !0 40602 }), { data: null, error: null }; 40603 } catch (t) { 40604 if (Re(t)) 40605 return { data: null, error: t }; 40606 throw t; 40607 } 40608 } 40609 /** 40610 * Regenerates the secret for an OAuth client. 40611 * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. 40612 * 40613 * This function should only be called on a server. Never expose your `service_role` key in the browser. 40614 */ 40615 async _regenerateOAuthClientSecret(e) { 40616 try { 40617 return await He(this.fetch, "POST", `${this.url}/admin/oauth/clients/${e}/regenerate_secret`, { 40618 headers: this.headers, 40619 xform: (t) => ({ data: t, error: null }) 40620 }); 40621 } catch (t) { 40622 if (Re(t)) 40623 return { data: null, error: t }; 40624 throw t; 40625 } 40626 } 40627 /** 40628 * Lists all custom providers with optional type filter. 40629 * 40630 * This function should only be called on a server. Never expose your `service_role` key in the browser. 40631 */ 40632 async _listCustomProviders(e) { 40633 try { 40634 const t = {}; 40635 return e?.type && (t.type = e.type), await He(this.fetch, "GET", `${this.url}/admin/custom-providers`, { 40636 headers: this.headers, 40637 query: t, 40638 xform: (i) => { 40639 var r; 40640 return { data: { providers: (r = i?.providers) !== null && r !== void 0 ? r : [] }, error: null }; 40641 } 40642 }); 40643 } catch (t) { 40644 if (Re(t)) 40645 return { data: { providers: [] }, error: t }; 40646 throw t; 40647 } 40648 } 40649 /** 40650 * Creates a new custom OIDC/OAuth provider. 40651 * 40652 * For OIDC providers, the server fetches and validates the OpenID Connect discovery document 40653 * from the issuer's well-known endpoint (or the provided `discovery_url`) at creation time. 40654 * This may return a validation error (`error_code: "validation_failed"`) if the discovery 40655 * document is unreachable, not valid JSON, missing required fields, or if the issuer 40656 * in the document does not match the expected issuer. 40657 * 40658 * This function should only be called on a server. Never expose your `service_role` key in the browser. 40659 */ 40660 async _createCustomProvider(e) { 40661 try { 40662 return await He(this.fetch, "POST", `${this.url}/admin/custom-providers`, { 40663 body: e, 40664 headers: this.headers, 40665 xform: (t) => ({ data: t, error: null }) 40666 }); 40667 } catch (t) { 40668 if (Re(t)) 40669 return { data: null, error: t }; 40670 throw t; 40671 } 40672 } 40673 /** 40674 * Gets details of a specific custom provider by identifier. 40675 * 40676 * This function should only be called on a server. Never expose your `service_role` key in the browser. 40677 */ 40678 async _getCustomProvider(e) { 40679 try { 40680 return await He(this.fetch, "GET", `${this.url}/admin/custom-providers/${e}`, { 40681 headers: this.headers, 40682 xform: (t) => ({ data: t, error: null }) 40683 }); 40684 } catch (t) { 40685 if (Re(t)) 40686 return { data: null, error: t }; 40687 throw t; 40688 } 40689 } 40690 /** 40691 * Updates an existing custom provider. 40692 * 40693 * When `issuer` or `discovery_url` is changed on an OIDC provider, the server re-fetches and 40694 * validates the discovery document before persisting. This may return a validation error 40695 * (`error_code: "validation_failed"`) if the discovery document is unreachable, invalid, or 40696 * the issuer does not match. 40697 * 40698 * This function should only be called on a server. Never expose your `service_role` key in the browser. 40699 */ 40700 async _updateCustomProvider(e, t) { 40701 try { 40702 return await He(this.fetch, "PUT", `${this.url}/admin/custom-providers/${e}`, { 40703 body: t, 40704 headers: this.headers, 40705 xform: (i) => ({ data: i, error: null }) 40706 }); 40707 } catch (i) { 40708 if (Re(i)) 40709 return { data: null, error: i }; 40710 throw i; 40711 } 40712 } 40713 /** 40714 * Deletes a custom provider. 40715 * 40716 * This function should only be called on a server. Never expose your `service_role` key in the browser. 40717 */ 40718 async _deleteCustomProvider(e) { 40719 try { 40720 return await He(this.fetch, "DELETE", `${this.url}/admin/custom-providers/${e}`, { 40721 headers: this.headers, 40722 noResolveJson: !0 40723 }), { data: null, error: null }; 40724 } catch (t) { 40725 if (Re(t)) 40726 return { data: null, error: t }; 40727 throw t; 40728 } 40729 } 40730 /** 40731 * Lists all passkeys for a user. 40732 * 40733 * This function should only be called on a server. Never expose your secret key in the browser. 40734 * 40735 * Requires `auth.experimental.passkey: true`. 40736 */ 40737 async _adminListPasskeys(e) { 40738 Kn(this.experimental), Ri(e.userId); 40739 try { 40740 return await He(this.fetch, "GET", `${this.url}/admin/users/${e.userId}/passkeys`, { headers: this.headers, xform: (t) => ({ data: t, error: null }) }); 40741 } catch (t) { 40742 if (Re(t)) 40743 return { data: null, error: t }; 40744 throw t; 40745 } 40746 } 40747 /** 40748 * Deletes a user's passkey. 40749 * 40750 * This function should only be called on a server. Never expose your secret key in the browser. 40751 * 40752 * Requires `auth.experimental.passkey: true`. 40753 */ 40754 async _adminDeletePasskey(e) { 40755 Kn(this.experimental), Ri(e.userId), Ri(e.passkeyId); 40756 try {
40757 return await He(this.fetch, "DELETE", `${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`, { headers: this.headers, noResolveJson: !0 }), { data: null, error: null }; 40758 } catch (t) { 40759 if (Re(t)) 40760 return { data: null, error: t }; 40761 throw t; 40762 } 40763 } 40764} 40765function Sf(n = {}) { 40766 return { 40767 getItem: (e) => n[e] || null, 40768 setItem: (e, t) => { 40769 n[e] = t; 40770 }, 40771 removeItem: (e) => { 40772 delete n[e]; 40773 } 40774 }; 40775} 40776globalThis && Dm() && globalThis.localStorage && globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug"); 40777class b1 extends Error { 40778 constructor(e) { 40779 super(e), this.isAcquireTimeout = !0; 40780 } 40781} 40782function w1() { 40783 if (typeof globalThis != "object") 40784 try { 40785 Object.defineProperty(Object.prototype, "__magic__", { 40786 get: function() { 40787 return this; 40788 }, 40789 configurable: !0 40790 }), __magic__.globalThis = __magic__, delete Object.prototype.__magic__; 40791 } catch { 40792 typeof self < "u" && (self.globalThis = self); 40793 } 40794} 40795function Om(n) { 40796 if (!/^0x[a-fA-F0-9]{40}$/.test(n)) 40797 throw new Error(`@supabase/auth-js: Address "${n}" is invalid.`); 40798 return n.toLowerCase(); 40799} 40800function S1(n) { 40801 return parseInt(n, 16); 40802} 40803function E1(n) { 40804 const e = new TextEncoder().encode(n); 40805 return "0x" + Array.from(e, (i) => i.toString(16).padStart(2, "0")).join(""); 40806} 40807function M1(n) { 40808 var e; 40809 const { chainId: t, domain: i, expirationTime: r, issuedAt: s = /* @__PURE__ */ new Date(), nonce: a, notBefore: l, requestId: o, resources: c, scheme: u, uri: h, version: d } = n; 40810 { 40811 if (!Number.isInteger(t)) 40812 throw new Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${t}`); 40813 if (!i) 40814 throw new Error('@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.'); 40815 if (a && a.length < 8) 40816 throw new Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${a}`); 40817 if (!h) 40818 throw new Error('@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.'); 40819 if (d !== "1") 40820 throw new Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${d}`); 40821 if (!((e = n.statement) === null || e === void 0) && e.includes(` 40822`)) 40823 throw new Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${n.statement}`); 40824 } 40825 const f = Om(n.address), p = u ? `${u}://${i}` : i, v = n.statement ? `${n.statement} 40826` : "", m = `${p} wants you to sign in with your Ethereum account: 40827${f} 40828 40829${v}`; 40830 let g = `URI: ${h} 40831Version: ${d} 40832Chain ID: ${t}${a ? ` 40833Nonce: ${a}` : ""} 40834Issued At: ${s.toISOString()}`; 40835 if (r && (g += ` 40836Expiration Time: ${r.toISOString()}`), l && (g += ` 40837Not Before: ${l.toISOString()}`), o && (g += ` 40838Request ID: ${o}`), c) { 40839 let _ = ` 40840Resources:`; 40841 for (const x of c) { 40842 if (!x || typeof x != "string") 40843 throw new Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${x}`); 40844 _ += ` 40845- ${x}`; 40846 } 40847 g += _; 40848 } 40849 return `${m} 40850${g}`; 40851} 40852class Kt extends Error { 40853 constructor({ message: e, code: t, cause: i, name: r }) { 40854 var s; 40855 super(e, { cause: i }), this.__isWebAuthnError = !0, this.name = (s = r ?? (i instanceof Error ? i.name : void 0)) !== null && s !== void 0 ? s : "Unknown Error", this.code = t; 40856 } 40857 toJSON() { 40858 return { 40859 name: this.name, 40860 message: this.message, 40861 code: this.code 40862 }; 40863 } 40864} 40865class Fo extends Kt { 40866 constructor(e, t) { 40867 super({ 40868 code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", 40869 cause: t, 40870 message: e 40871 }), this.name = "WebAuthnUnknownError", this.originalError = t; 40872 } 40873} 40874function T1({ error: n, options: e }) { 40875 var t, i, r; 40876 const { publicKey: s } = e; 40877 if (!s) 40878 throw Error("options was missing required publicKey property"); 40879 if (n.name === "AbortError") { 40880 if (e.signal instanceof AbortSignal) 40881 return new Kt({ 40882 message: "Registration ceremony was sent an abort signal", 40883 code: "ERROR_CEREMONY_ABORTED", 40884 cause: n 40885 }); 40886 } else if (n.name === "ConstraintError") { 40887 if (((t = s.authenticatorSelection) === null || t === void 0 ? void 0 : t.requireResidentKey) === !0) 40888 return new Kt({ 40889 message: "Discoverable credentials were required but no available authenticator supported it", 40890 code: "ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT", 40891 cause: n 40892 }); 40893 if ( 40894 // @ts-ignore: `mediation` doesn't yet exist on CredentialCreationOptions but it's possible as of Sept 2024 40895 e.mediation === "conditional" && ((i = s.authenticatorSelection) === null || i === void 0 ? void 0 : i.userVerification) === "required" 40896 ) 40897 return new Kt({ 40898 message: "User verification was required during automatic registration but it could not be performed", 40899 code: "ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE", 40900 cause: n 40901 }); 40902 if (((r = s.authenticatorSelection) === null || r === void 0 ? void 0 : r.userVerification) === "required") 40903 return new Kt({ 40904 message: "User verification was required but no available authenticator supported it", 40905 code: "ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT", 40906 cause: n 40907 }); 40908 } else { 40909 if (n.name === "InvalidStateError") 40910 return new Kt({ 40911 message: "The authenticator was previously registered", 40912 code: "ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED", 40913 cause: n 40914 }); 40915 if (n.name === "NotAllowedError") 40916 return new Kt({ 40917 message: n.message, 40918 code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", 40919 cause: n 40920 }); 40921 if (n.name === "NotSupportedError") 40922 return s.pubKeyCredParams.filter((l) => l.type === "public-key").length === 0 ? new Kt({ 40923 message: 'No entry in pubKeyCredParams was of type "public-key"', 40924 code: "ERROR_MALFORMED_PUBKEYCREDPARAMS", 40925 cause: n 40926 }) : new Kt({ 40927 message: "No available authenticator supported any of the specified pubKeyCredParams algorithms", 40928 code: "ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG", 40929 cause: n 40930 }); 40931 if (n.name === "SecurityError") { 40932 const a = window.location.hostname; 40933 if (km(a)) { 40934 if (s.rp.id !== a) 40935 return new Kt({ 40936 message: `The RP ID "${s.rp.id}
40936" is invalid for this domain`, 40937 code: "ERROR_INVALID_RP_ID", 40938 cause: n 40939 }); 40940 } else return new Kt({ 40941 message: `${window.location.hostname} is an invalid domain`, 40942 code: "ERROR_INVALID_DOMAIN", 40943 cause: n 40944 }); 40945 } else if (n.name === "TypeError") { 40946 if (s.user.id.byteLength < 1 || s.user.id.byteLength > 64) 40947 return new Kt({ 40948 message: "User ID was not between 1 and 64 characters", 40949 code: "ERROR_INVALID_USER_ID_LENGTH", 40950 cause: n 40951 }); 40952 } else if (n.name === "UnknownError") 40953 return new Kt({ 40954 message: "The authenticator was unable to process the specified options, or could not create a new credential", 40955 code: "ERROR_AUTHENTICATOR_GENERAL_ERROR", 40956 cause: n 40957 }); 40958 } 40959 return new Kt({ 40960 message: "a Non-Webauthn related error has occurred", 40961 code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", 40962 cause: n 40963 }); 40964} 40965function A1({ error: n, options: e }) { 40966 const { publicKey: t } = e; 40967 if (!t) 40968 throw Error("options was missing required publicKey property"); 40969 if (n.name === "AbortError") { 40970 if (e.signal instanceof AbortSignal) 40971 return new Kt({ 40972 message: "Authentication ceremony was sent an abort signal", 40973 code: "ERROR_CEREMONY_ABORTED", 40974 cause: n 40975 }); 40976 } else { 40977 if (n.name === "NotAllowedError") 40978 return new Kt({ 40979 message: n.message, 40980 code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", 40981 cause: n 40982 }); 40983 if (n.name === "SecurityError") { 40984 const i = window.location.hostname; 40985 if (km(i)) { 40986 if (t.rpId !== i) 40987 return new Kt({ 40988 message: `The RP ID "${t.rpId}" is invalid for this domain`, 40989 code: "ERROR_INVALID_RP_ID", 40990 cause: n 40991 }); 40992 } else return new Kt({ 40993 message: `${window.location.hostname} is an invalid domain`, 40994 code: "ERROR_INVALID_DOMAIN", 40995 cause: n 40996 }); 40997 } else if (n.name === "UnknownError") 40998 return new Kt({ 40999 message: "The authenticator was unable to process the specified options, or could not create a new assertion signature", 41000 code: "ERROR_AUTHENTICATOR_GENERAL_ERROR", 41001 cause: n 41002 }); 41003 } 41004 return new Kt({ 41005 message: "a Non-Webauthn related error has occurred", 41006 code: "ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY", 41007 cause: n 41008 }); 41009} 41010class R1 { 41011 /** 41012 * Create an abort signal for a new WebAuthn operation. 41013 * Automatically cancels any existing operation. 41014 * 41015 * @returns {AbortSignal} Signal to pass to navigator.credentials.create() or .get() 41016 * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal MDN - AbortSignal} 41017 */ 41018 createNewAbortSignal() { 41019 if (this.controller) { 41020 const t = new Error("Cancelling existing WebAuthn API call for new one"); 41021 t.name = "AbortError", this.controller.abort(t); 41022 } 41023 const e = new AbortController(); 41024 return this.controller = e, e.signal; 41025 } 41026 /** 41027 * Manually cancel the current WebAuthn operation. 41028 * Useful for cleaning up when user cancels or navigates away. 41029 * 41030 * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort MDN - AbortController.abort} 41031 */ 41032 cancelCeremony() { 41033 if (this.controller) { 41034 const e = new Error("Manually cancelling existing WebAuthn API call"); 41035 e.name = "AbortError", this.controller.abort(e), this.controller = void 0; 41036 } 41037 } 41038} 41039const gu = new R1(); 41040function Ef(n) { 41041 if (!n) 41042 throw new Error("Credential creation options are required"); 41043 if (typeof PublicKeyCredential < "u" && "parseCreationOptionsFromJSON" in PublicKeyCredential && typeof PublicKeyCredential.parseCreationOptionsFromJSON == "function") 41044 return PublicKeyCredential.parseCreationOptionsFromJSON( 41045 /** we assert the options here as typescript still doesn't know about future webauthn types */ 41046 n 41047 ); 41048 const { challenge: e, user: t, excludeCredentials: i } = n, r = Qo( 41049 n, 41050 ["challenge", "user", "excludeCredentials"] 41051 ), s = fs(e).buffer, a = Object.assign(Object.assign({}, t), { id: fs(t.id).buffer }), l = Object.assign(Object.assign({}, r), { 41052 challenge: s, 41053 user: a 41054 }); 41055 if (i && i.length > 0) { 41056 l.excludeCredentials = new Array(i.length); 41057 for (let o = 0; o < i.length; o++) { 41058 const c = i[o]; 41059 l.excludeCredentials[o] = Object.assign(Object.assign({}, c), { 41060 id: fs(c.id).buffer, 41061 type: c.type || "public-key", 41062 // Cast transports to handle future transport types like "cable" 41063 transports: c.transports 41064 }); 41065 } 41066 } 41067 return l; 41068} 41069function Mf(n) { 41070 if (!n) 41071 throw new Error("Credential request options are required"); 41072 if (typeof PublicKeyCredential < "u" && "parseRequestOptionsFromJSON" in PublicKeyCredential && typeof PublicKeyCredential.parseRequestOptionsFromJSON == "function") 41073 return PublicKeyCredential.parseRequestOptionsFromJSON(n); 41074 const { challenge: e, allowCredentials: t } = n, i = Qo( 41075 n, 41076 ["challenge", "allowCredentials"] 41077 ), r = fs(e).buffer, s = Object.assign(Object.assign({}, i), { challenge: r }); 41078 if (t && t.length > 0) { 41079 s.allowCredentials = new Array(t.length); 41080 for (let a = 0; a < t.length; a++) { 41081 const l = t[a]; 41082 s.allowCredentials[a] = Object.assign(Object.assign({}, l), { 41083 id: fs(l.id).buffer, 41084 type: l.type || "public-key", 41085 // Cast transports to handle future transport types like "cable" 41086 transports: l.transports 41087 }); 41088 } 41089 } 41090 return s; 41091} 41092function Tf(n) { 41093 var e; 41094 if ("toJSON" in n && typeof n.toJSON == "function") 41095 return n.toJSON(); 41096 const t = n; 41097 return { 41098 id: n.id, 41099 rawId: n.id, 41100 response: {
41101 attestationObject: Rr(new Uint8Array(n.response.attestationObject)), 41102 clientDataJSON: Rr(new Uint8Array(n.response.clientDataJSON)) 41103 }, 41104 type: "public-key", 41105 clientExtensionResults: n.getClientExtensionResults(), 41106 // Convert null to undefined and cast to AuthenticatorAttachment type 41107 authenticatorAttachment: (e = t.authenticatorAttachment) !== null && e !== void 0 ? e : void 0 41108 }; 41109} 41110function Af(n) { 41111 var e; 41112 if ("toJSON" in n && typeof n.toJSON == "function") 41113 return n.toJSON(); 41114 const t = n, i = n.getClientExtensionResults(), r = n.response; 41115 return { 41116 id: n.id, 41117 rawId: n.id, 41118 // W3C spec expects rawId to match id for JSON format 41119 response: { 41120 authenticatorData: Rr(new Uint8Array(r.authenticatorData)), 41121 clientDataJSON: Rr(new Uint8Array(r.clientDataJSON)), 41122 signature: Rr(new Uint8Array(r.signature)), 41123 userHandle: r.userHandle ? Rr(new Uint8Array(r.userHandle)) : void 0 41124 }, 41125 type: "public-key", 41126 clientExtensionResults: i, 41127 // Convert null to undefined and cast to AuthenticatorAttachment type 41128 authenticatorAttachment: (e = t.authenticatorAttachment) !== null && e !== void 0 ? e : void 0 41129 }; 41130} 41131function km(n) { 41132 return ( 41133 // Consider localhost valid as well since it's okay wrt Secure Contexts 41134 n === "localhost" || /^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(n) 41135 ); 41136} 41137function Bo() { 41138 var n, e; 41139 return !!(hn() && "PublicKeyCredential" in window && window.PublicKeyCredential && "credentials" in navigator && typeof ((n = navigator?.credentials) === null || n === void 0 ? void 0 : n.create) == "function" && typeof ((e = navigator?.credentials) === null || e === void 0 ? void 0 : e.get) == "function"); 41140} 41141async function Fm(n) { 41142 try { 41143 const e = await navigator.credentials.create( 41144 /** we assert the type here until typescript types are updated */ 41145 n 41146 ); 41147 return e ? e instanceof PublicKeyCredential ? { data: e, error: null } : { 41148 data: null, 41149 error: new Fo("Browser returned unexpected credential type", e) 41150 } : { 41151 data: null, 41152 error: new Fo("Empty credential response", e) 41153 }; 41154 } catch (e) { 41155 return { 41156 data: null, 41157 error: T1({ 41158 error: e, 41159 options: n 41160 }) 41161 }; 41162 } 41163} 41164async function Bm(n) { 41165 try { 41166 const e = await navigator.credentials.get( 41167 /** we assert the type here until typescript types are updated */ 41168 n 41169 ); 41170 return e ? e instanceof PublicKeyCredential ? { data: e, error: null } : { 41171 data: null, 41172 error: new Fo("Browser returned unexpected credential type", e) 41173 } : { 41174 data: null, 41175 error: new Fo("Empty credential response", e) 41176 }; 41177 } catch (e) { 41178 return { 41179 data: null, 41180 error: A1({ 41181 error: e, 41182 options: n 41183 }) 41184 }; 41185 } 41186} 41187const C1 = { 41188 hints: ["security-key"], 41189 authenticatorSelection: { 41190 authenticatorAttachment: "cross-platform", 41191 requireResidentKey: !1, 41192 /** set to preferred because older yubikeys don't have PIN/Biometric */ 41193 userVerification: "preferred", 41194 residentKey: "discouraged" 41195 }, 41196 attestation: "direct" 41197}, P1 = { 41198 /** set to preferred because older yubikeys don't have PIN/Biometric */ 41199 userVerification: "preferred", 41200 hints: ["security-key"], 41201 attestation: "direct" 41202}; 41203function zo(...n) { 41204 const e = (r) => r !== null && typeof r == "object" && !Array.isArray(r), t = (r) => r instanceof ArrayBuffer || ArrayBuffer.isView(r), i = {}; 41205 for (const r of n) 41206 if (r) 41207 for (const s in r) { 41208 const a = r[s]; 41209 if (a !== void 0) 41210 if (Array.isArray(a)) 41211 i[s] = a; 41212 else if (t(a)) 41213 i[s] = a; 41214 else if (e(a)) { 41215 const l = i[s]; 41216 e(l) ? i[s] = zo(l, a) : i[s] = zo(a); 41217 } else 41218 i[s] = a; 41219 } 41220 return i; 41221} 41222function L1(n, e) { 41223 return zo(C1, n, e || {}); 41224} 41225function N1(n, e) { 41226 return zo(P1, n, e || {}); 41227} 41228class I1 { 41229 constructor(e) { 41230 this.client = e, this.enroll = this._enroll.bind(this), this.challenge = this._challenge.bind(this), this.verify = this._verify.bind(this), this.authenticate = this._authenticate.bind(this), this.register = this._register.bind(this); 41231 } 41232 /** 41233 * Enroll a new WebAuthn factor. 41234 * Creates an unverified WebAuthn factor that must be verified with a credential. 41235 * 41236 * @experimental This method is experimental and may change in future releases 41237 * @param {Omit<MFAEnrollWebauthnParams, 'factorType'>} params - Enrollment parameters (friendlyName required) 41238 * @returns {Promise<AuthMFAEnrollWebauthnResponse>} Enrolled factor details or error 41239 * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registering a New Credential} 41240 */ 41241 async _enroll(e) { 41242 return this.client.mfa.enroll(Object.assign(Object.assign({}, e), { factorType: "webauthn" })); 41243 } 41244 /** 41245 * Challenge for WebAuthn credential creation or authentication. 41246 * Combines server challenge with browser credential operations. 41247 * Handles both registration (create) and authentication (request) flows. 41248 * 41249 * @experimental This method is experimental and may change in future releases 41250 * @param {MFAChallengeWebauthnParams & { friendlyName?: string; signal?: AbortSignal }} params - Challenge parameters including factorId 41251 * @param {Object}
41251 overrides - Allows you to override the parameters passed to navigator.credentials 41252 * @param {PublicKeyCredentialCreationOptionsFuture} overrides.create - Override options for credential creation 41253 * @param {PublicKeyCredentialRequestOptionsFuture} overrides.request - Override options for credential request 41254 * @returns {Promise<RequestResult>} Challenge response with credential or error 41255 * @see {@link https://w3c.github.io/webauthn/#sctn-credential-creation W3C WebAuthn Spec - Credential Creation} 41256 * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying Assertion} 41257 */ 41258 async _challenge({ factorId: e, webauthn: t, friendlyName: i, signal: r }, s) { 41259 var a; 41260 try { 41261 const { data: l, error: o } = await this.client.mfa.challenge({ 41262 factorId: e, 41263 webauthn: t 41264 }); 41265 if (!l) 41266 return { data: null, error: o }; 41267 const c = r ?? gu.createNewAbortSignal(); 41268 if (l.webauthn.type === "create") { 41269 const { user: u } = l.webauthn.credential_options.publicKey; 41270 if (!u.name) { 41271 const h = i; 41272 if (h) 41273 u.name = `${u.id}:${h}`; 41274 else { 41275 const f = (await this.client.getUser()).data.user, p = ((a = f?.user_metadata) === null || a === void 0 ? void 0 : a.name) || f?.email || f?.id || "User"; 41276 u.name = `${u.id}:${p}`; 41277 } 41278 }
41279 u.displayName || (u.displayName = u.name); 41280 } 41281 switch (l.webauthn.type) { 41282 case "create": { 41283 const u = L1(l.webauthn.credential_options.publicKey, s?.create), { data: h, error: d } = await Fm({ 41284 publicKey: u, 41285 signal: c 41286 }); 41287 return h ? { 41288 data: { 41289 factorId: e, 41290 challengeId: l.id, 41291 webauthn: { 41292 type: l.webauthn.type, 41293 credential_response: h 41294 } 41295 }, 41296 error: null 41297 } : { data: null, error: d }; 41298 } 41299 case "request": { 41300 const u = N1(l.webauthn.credential_options.publicKey, s?.request), { data: h, error: d } = await Bm(Object.assign(Object.assign({}, l.webauthn.credential_options), { publicKey: u, signal: c })); 41301 return h ? { 41302 data: { 41303 factorId: e, 41304 challengeId: l.id, 41305 webauthn: { 41306 type: l.webauthn.type, 41307 credential_response: h 41308 } 41309 }, 41310 error: null 41311 } : { data: null, error: d }; 41312 } 41313 } 41314 } catch (l) { 41315 return Re(l) ? { data: null, error: l } : { 41316 data: null, 41317 error: new ei("Unexpected error in challenge", l) 41318 }; 41319 } 41320 } 41321 /** 41322 * Verify a WebAuthn credential with the server. 41323 * Completes the WebAuthn ceremony by sending the credential to the server for verification. 41324 * 41325 * @experimental This method is experimental and may change in future releases 41326 * @param {Object} params - Verification parameters 41327 * @param {string} params.challengeId - ID of the challenge being verified 41328 * @param {string} params.factorId - ID of the WebAuthn factor 41329 * @param {MFAVerifyWebauthnParams<T>['webauthn']} params.webauthn - WebAuthn credential response 41330 * @returns {Promise<AuthMFAVerifyResponse>} Verification result with session or error 41331 * @see {@link https://w3c.github.io/webauthn/#sctn-verifying-assertion W3C WebAuthn Spec - Verifying an Authentication Assertion} 41332 * */ 41333 async _verify({ challengeId: e, factorId: t, webauthn: i }) { 41334 return this.client.mfa.verify({ 41335 factorId: t, 41336 challengeId: e, 41337 webauthn: i 41338 }); 41339 } 41340 /** 41341 * Complete WebAuthn authentication flow. 41342 * Performs challenge and verification in a single operation for existing credentials. 41343 * 41344 * @experimental This method is experimental and may change in future releases 41345 * @param {Object} params - Authentication parameters 41346 * @param {string} params.factorId - ID of the WebAuthn factor to authenticate with 41347 * @param {Object} params.webauthn - WebAuthn configuration 41348 * @param {string} params.webauthn.rpId - Relying Party ID (defaults to current hostname) 41349 * @param {string[]} params.webauthn.rpOrigins - Allowed origins (defaults to current origin) 41350 * @param {AbortSignal} params.webauthn.signal - Optional abort signal 41351 * @param {PublicKeyCredentialRequestOptionsFuture} overrides - Override options for navigator.credentials.get 41352 * @returns {Promise<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>>} Authentication result 41353 * @see {@link https://w3c.github.io/webauthn/#sctn-authentication W3C WebAuthn Spec - Authentication Ceremony} 41354 * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialRequestOptions MDN - PublicKeyCredentialRequestOptions} 41355 */ 41356 async _authenticate({ factorId: e, webauthn: { rpId: t = typeof window < "u" ? window.location.hostname : void 0, rpOrigins: i = typeof window < "u" ? [window.location.origin] : void 0, signal: r } = {} }, s) { 41357 if (!t) 41358 return { 41359 data: null, 41360 error: new pa("rpId is required for WebAuthn authentication") 41361 }; 41362 try { 41363 if (!Bo()) 41364 return { 41365 data: null, 41366 error: new ei("Browser does not support WebAuthn", null) 41367 }; 41368 const { data: a, error: l } = await this.challenge({ 41369 factorId: e, 41370 webauthn: { rpId: t, rpOrigins: i }, 41371 signal: r 41372 }, { request: s }); 41373 if (!a) 41374 return { data: null, error: l }; 41375 const { webauthn: o } = a; 41376 return this._verify({ 41377 factorId: e, 41378 challengeId: a.challengeId, 41379 webauthn: { 41380 type: o.type, 41381 rpId: t, 41382 rpOrigins: i, 41383 credential_response: o.credential_response 41384 } 41385 }); 41386 } catch (a) {
41387 return Re(a) ? { data: null, error: a } : { 41388 data: null, 41389 error: new ei("Unexpected error in authenticate", a) 41390 }; 41391 } 41392 } 41393 /** 41394 * Complete WebAuthn registration flow. 41395 * Performs enrollment, challenge, and verification in a single operation for new credentials. 41396 * 41397 * @experimental This method is experimental and may change in future releases 41398 * @param {Object} params - Registration parameters 41399 * @param {string} params.friendlyName - User-friendly name for the credential 41400 * @param {string} params.rpId - Relying Party ID (defaults to current hostname) 41401 * @param {string[]} params.rpOrigins - Allowed origins (defaults to current origin) 41402 * @param {AbortSignal} params.signal - Optional abort signal 41403 * @param {PublicKeyCredentialCreationOptionsFuture} overrides - Override options for navigator.credentials.create 41404 * @returns {Promise<RequestResult<AuthMFAVerifyResponseData, WebAuthnError | AuthError>>} Registration result 41405 * @see {@link https://w3c.github.io/webauthn/#sctn-registering-a-new-credential W3C WebAuthn Spec - Registration Ceremony} 41406 * @see {@link https://developer.mozilla.org/en-US/docs/Web/API/PublicKeyCredentialCreationOptions MDN - PublicKeyCredentialCreationOptions} 41407 */ 41408 async _register({ friendlyName: e, webauthn: { rpId: t = typeof window < "u" ? window.location.hostname : void 0, rpOrigins: i = typeof window < "u" ? [window.location.origin] : void 0, signal: r } = {} }, s) { 41409 if (!t) 41410 return { 41411 data: null, 41412 error: new pa("rpId is required for WebAuthn registration") 41413 }; 41414 try { 41415 if (!Bo()) 41416 return { 41417 data: null, 41418 error: new ei("Browser does not support WebAuthn", null) 41419 }; 41420 const { data: a, error: l } = await this._enroll({ 41421 friendlyName: e 41422 }); 41423 if (!a) 41424 return await this.client.mfa.listFactors().then((u) => { 41425 var h; 41426 return (h = u.data) === null || h === void 0 ? void 0 : h.all.find((d) => d.factor_type === "webauthn" && d.friendly_name === e && d.status !== "unverified"); 41427 }).then((u) => u ? this.client.mfa.unenroll({ factorId: u?.id }) : void 0), { data: null, error: l }; 41428 const { data: o, error: c } = await this._challenge({ 41429 factorId: a.id, 41430 friendlyName: a.friendly_name, 41431 webauthn: { rpId: t, rpOrigins: i }, 41432 signal: r 41433 }, { 41434 create: s 41435 }); 41436 return o ? this._verify({ 41437 factorId: a.id, 41438 challengeId: o.challengeId, 41439 webauthn: { 41440 rpId: t, 41441 rpOrigins: i, 41442 type: o.webauthn.type, 41443 credential_response: o.webauthn.credential_response 41444 } 41445 }) : { data: null, error: c }; 41446 } catch (a) { 41447 return Re(a) ? { data: null, error: a } : { 41448 data: null, 41449 error: new ei("Unexpected error in register", a) 41450 }; 41451 } 41452 } 41453} 41454w1(); 41455const D1 = { 41456 url: kT, 41457 storageKey: FT, 41458 autoRefreshToken: !0, 41459 persistSession: !0, 41460 detectSessionInUrl: !0, 41461 headers: BT, 41462 flowType: "implicit", 41463 debug: !1, 41464 hasCustomAuthorizationHeader: !1, 41465 throwOnError: !1, 41466 lockAcquireTimeout: 5e3, 41467 // 5 seconds. Only used when a custom `lock` is supplied. TODO(v3): remove. 41468 skipAutoInitialize: !1, 41469 experimental: {} 41470}, ts = {}; 41471class ma { 41472 /** 41473 * The JWKS used for verifying asymmetric JWTs 41474 */ 41475 get jwks() { 41476 var e, t; 41477 return (t = (e = ts[this.storageKey]) === null || e === void 0 ? void 0 : e.jwks) !== null && t !== void 0 ? t : { keys: [] }; 41478 } 41479 set jwks(e) { 41480 ts[this.storageKey] = Object.assign(Object.assign({}, ts[this.storageKey]), { jwks: e }); 41481 } 41482 get jwks_cached_at() { 41483 var e, t; 41484 return (t = (e = ts[this.storageKey]) === null || e === void 0 ? void 0 : e.cachedAt) !== null && t !== void 0 ? t : Number.MIN_SAFE_INTEGER; 41485 } 41486 set jwks_cached_at(e) { 41487 ts[this.storageKey] = Object.assign(Object.assign({}, ts[this.storageKey]), { cachedAt: e }); 41488 } 41489 /** 41490 * Create a new client for use in the browser. 41491 * 41492 * @example Using supabase-js (recommended) 41493 * ```ts 41494 * import { createClient } from '@supabase/supabase-js' 41495 * 41496 * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key') 41497 * const { data, error } = await supabase.auth.getUser() 41498 * ``` 41499 * 41500 * @example Standalone import for bundle-sensitive environments 41501 * ```ts 41502 * import { GoTrueClient } from '@supabase/auth-js' 41503 * 41504 * const auth = new GoTrueClient({ 41505 * url: 'https://xyzcompany.supabase.co/auth/v1', 41506 * headers: { apikey: 'your-publishable-key' }, 41507 * storageKey: 'supabase-auth', 41508 * }) 41509 * ``` 41510 */ 41511 constructor(e) { 41512 var t, i, r; 41513 this.userStorage = null, this.memoryStorage = null, this.stateChangeEmitters = /* @__PURE__ */ new Map(), this.autoRefreshTicker = null, this.autoRefreshTickTimeout = null, this.visibilityChangedCallback = null, this.refreshingDeferred = null, this._sessionRemovalEpoch = 0, this.initializePromise = null, this.detectSessionInUrl = !0, this.hasCustomAuthorizationHeader = !1, this.suppressGetSessionWarning = !1, this.lock = null, this.lockAcquired = !1, this.pendingInLock = [], this.broadcastChannel = null, this.logger = console.log; 41514 const s = Object.assign(Object.assign({}, D1), e); 41515 if (this.storageKey = s.storageKey, this.instanceID = (t = ma.nextInstanceID[this.storageKey]) !== null && t !== void 0 ? t : 0, ma.nextInstanceID[this.storageKey] = this.instanceID + 1, this.logDebugMessages = !!s.debug, typeof s.debug == "function" && (this.logger = s.debug), this.instanceID > 0 && hn()) { 41516 const a = `${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`; 41517 console.warn(a), this.logDebugMessages && console.trace(a); 41518 } 41519 if (this.persistSession = s.persistSession, this.autoRefreshToken = s.autoRefreshToken, this.experimental = (i = s.experimental) !== null && i !== void 0 ? i : {}, this.admin = new x1({ 41520 url: s.url, 41521 headers: s.headers, 41522 fetch: s.fetch, 41523 experimental: this.experimental 41524 }), this.url = s.url, this.headers = s.headers, this.fetch = Um(s.fetch), this.detectSessionInUrl = s.detectSessionInUrl, this.flowType = s.flowType, this.hasCustomAuthorizationHeader = s.hasCustomAuthorizationHeader, this.throwOnError = s.throwOnError, this.lockAcquireTimeout = s.lockAcquireTimeout, s.lock != null && (this.lock = s.lock), this.jwks || (this.jwks = { keys: [] }, this.jwks_cached_at = Number.MIN_SAFE_INTEGER), this.mfa = { 41525 verify: this._verify.bind(this), 41526 enroll: this._enroll.bind(this), 41527 unenroll: this._unenroll.bind(this), 41528 challenge: this._challenge.bind(this), 41529 listFactors: this._listFactors.bind(this), 41530 challengeAndVerify: this._challengeAndVerify.bind(this), 41531 getAuthenticatorAssuranceLevel: this._getAuthenticatorAssuranceLevel.bind(this), 41532 webauthn: new I1(this) 41533 }, this.oauth = {
41534 getAuthorizationDetails: this._getAuthorizationDetails.bind(this), 41535 approveAuthorization: this._approveAuthorization.bind(this), 41536 denyAuthorization: this._denyAuthorization.bind(this), 41537 listGrants: this._listOAuthGrants.bind(this), 41538 revokeGrant: this._revokeOAuthGrant.bind(this) 41539 }, this.passkey = { 41540 startRegistration: this._startPasskeyRegistration.bind(this), 41541 verifyRegistration: this._verifyPasskeyRegistration.bind(this), 41542 startAuthentication: this._startPasskeyAuthentication.bind(this), 41543 verifyAuthentication: this._verifyPasskeyAuthentication.bind(this), 41544 list: this._listPasskeys.bind(this), 41545 update: this._updatePasskey.bind(this), 41546 delete: this._deletePasskey.bind(this) 41547 }, this.persistSession ? (s.storage ? this.storage = s.storage : Dm() ? this.storage = globalThis.localStorage : (this.memoryStorage = {}, this.storage = Sf(this.memoryStorage)), s.userStorage && (this.userStorage = s.userStorage)) : (this.memoryStorage = {}, this.storage = Sf(this.memoryStorage)), hn() && globalThis.BroadcastChannel && this.persistSession && this.storageKey) { 41548 try { 41549 this.broadcastChannel = new globalThis.BroadcastChannel(this.storageKey); 41550 } catch (a) { 41551 console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available", a); 41552 } 41553 (r = this.broadcastChannel) === null || r === void 0 || r.addEventListener("message", async (a) => { 41554 this._debug("received broadcast notification from other tab or client", a); 41555 try { 41556 await this._notifyAllSubscribers(a.data.event, a.data.session, !1); 41557 } catch (l) { 41558 this._debug("#broadcastChannel", "error", l); 41559 } 41560 }); 41561 } 41562 s.skipAutoInitialize || this.initialize().catch((a) => { 41563 this._debug("#initialize()", "error", a); 41564 }); 41565 } 41566 /** 41567 * Returns whether error throwing mode is enabled for this client. 41568 */ 41569 isThrowOnErrorEnabled() { 41570 return this.throwOnError; 41571 } 41572 /** 41573 * Centralizes return handling with optional error throwing. When `throwOnError` is enabled 41574 * and the provided result contains a non-nullish error, the error is thrown instead of 41575 * being returned. This ensures consistent behavior across all public API methods. 41576 */ 41577 _returnResult(e) { 41578 if (this.throwOnError && e && e.error) 41579 throw e.error; 41580 return e; 41581 } 41582 _logPrefix() { 41583 return `GoTrueClient@${this.storageKey}:${this.instanceID} (${Lm}) ${(/* @__PURE__ */ new Date()).toISOString()}`; 41584 } 41585 _debug(...e) { 41586 return this.logDebugMessages && this.logger(this._logPrefix(), ...e), this; 41587 } 41588 /** 41589 * Initialize the auth client by loading the session from storage or 41590 * detecting it from the URL after an OAuth, magic-link, or password-recovery 41591 * redirect. 41592 * 41593 * **Most callers do not need to invoke this directly.** The client calls it 41594 * automatically during construction, and to react to sign-in events (including 41595 * post-redirect events) you should subscribe to `onAuthStateChange` rather 41596 * than awaiting `initialize()`. 41597 * 41598 * You only need to call it manually when you have opted out of the automatic 41599 * call by passing `skipAutoInitialize: true` â for example, in an SSR context 41600 * where you need to control initialization timing. In that case, awaiting 41601 * `initialize()` returns the resolved session result (or any error encountered 41602 * while detecting it from the URL). 41603 * 41604 * @category Auth 41605 */ 41606 async initialize() { 41607 return this.initializePromise ? await this.initializePromise : (this.initializePromise = (async () => this.lock != null ? await this._acquireLock(this.lockAcquireTimeout, async () => await this._initialize()) : await this._initialize())(), await this.initializePromise); 41608 } 41609 /** 41610 * IMPORTANT: 41611 * 1. Never throw in this method, as it is called from the constructor 41612 * 2. Never return a session from this method as it would be cached over 41613 * the whole lifetime of the client 41614 */ 41615 async _initialize() { 41616 var e; 41617 try { 41618 let t = {}, i = "none"; 41619 if (hn() && (t = e1(window.location.href), this._isImplicitGrantCallback(t) ? i = "implicit" : await this._isPKCECallback(t) && (i = "pkce")), hn() && this.detectSessionInUrl && i !== "none") { 41620 const { data: r, error: s } = await this._getSessionFromURL(t, i); 41621 if (s) { 41622 if (this._debug("#_initialize()", "error detecting session from URL", s), WT(s)) { 41623 const o = (e = s.details) === null || e === void 0 ? void 0 : e.code; 41624 if (o === "identity_already_exists" || o === "identity_not_found" || o === "single_identity_not_deletable") 41625 return { error: s }; 41626 } 41627 return { error: s }; 41628 } 41629 const { session: a, redirectType: l } = r; 41630 return this._debug("#_initialize()", "detected session in URL", a, "redirect type", l), await this._saveSession(a), setTimeout(async () => { 41631 l === "recovery" ? await this._notifyAllSubscribers("PASSWORD_RECOVERY", a) : await this._notifyAllSubscribers("SIGNED_IN", a); 41632 }, 0), { error: null }; 41633 } 41634 return await this._recoverAndRefresh(), { error: null }; 41635 } catch (t) { 41636 return Re(t) ? this._returnResult({ error: t }) : this._returnResult({ 41637 error: new ei("Unexpected error during initialization", t) 41638 }); 41639 } finally { 41640 await this._handleVisibilityChange(), this._debug("#_initialize()", "end"); 41641 } 41642 } 41643 /** 41644 * Creates a new anonymous user. 41645 * 41646 * @returns A session where the is_anonymous claim in the access token JWT set to true 41647 * 41648 * @category Auth 41649 * 41650 * @remarks 41651 * - Returns an anonymous user 41652 * - It is recommended to set up captcha for anonymous sign-ins to prevent abuse. You can pass in the captcha token in the `options` param. 41653 * 41654 * @example Create an anonymous user 41655 * ```js 41656 * const { data, error } = await supabase.auth.signInAnonymously({ 41657 * options: { 41658 * captchaToken 41659 * } 41660 * }); 41661 * ``` 41662 * 41663 * @exampleResponse Create an anonymous user 41664 * ```json 41665 * { 41666 * "data": { 41667 * "user": { 41668 * "id": "11111111-1111-1111-1111-111111111111", 41669 * "aud": "authenticated", 41670 * "role": "authenticated", 41671 * "email": "", 41672 * "phone": "", 41673 * "last_sign_in_at": "2024-01-01T00:00:00Z", 41674 * "app_metadata": {}, 41675 * "user_metadata": {}, 41676 * "identities": [], 41677 * "created_at": "2024-01-01T00:00:00Z", 41678 * "updated_at": "2024-01-01T00:00:00Z", 41679 * "is_anonymous": true 41680 * }, 41681 * "session": { 41682 * "access_token": "<ACCESS_TOKEN>", 41683 * "token_type": "bearer", 41684 * "expires_in": 3600, 41685 * "expires_at": 1700000000, 41686 * "refresh_token": "<REFRESH_TOKEN>", 41687 * "user": { 41688 * "id": "11111111-1111-1111-1111-111111111111", 41689 * "aud": "authenticated", 41690 * "role": "authenticated", 41691 * "email": "", 41692 * "phone": "", 41693 * "last_sign_in_at": "2024-01-01T00:00:00Z", 41694 * "app_metadata": {}, 41695 * "user_metadata": {}, 41696 * "identities": [], 41697 * "created_at": "2024-01-01T00:00:00Z", 41698 * "updated_at": "2024-01-01T00:00:00Z", 41699 * "is_anonymous": true 41700 * } 41701 * } 41702 * }, 41703 * "error": null 41704 * } 41705 * ``` 41706 * 41707 * @example Create an anonymous user with custom user metadata 41708 * ```js 41709 * const { data, error } = await supabase.auth.signInAnonymously({ 41710 * options: { 41711 * data 41712 * } 41713 * }) 41714 * ``` 41715 */ 41716 async signInAnonymously(e) { 41717 var t, i, r; 41718 try { 41719 const s = await He(this.fetch, "POST", `${this.url}/signup`, { 41720 headers: this.headers, 41721 body: { 41722 data: (i = (t = e?.options) === null || t === void 0 ? void 0 : t.data) !== null && i !== void 0 ? i : {},
41723 gotrue_meta_security: { captcha_token: (r = e?.options) === null || r === void 0 ? void 0 : r.captchaToken } 41724 }, 41725 xform: Bn 41726 }), { data: a, error: l } = s; 41727 if (l || !a) 41728 return this._returnResult({ data: { user: null, session: null }, error: l }); 41729 const o = a.session, c = a.user; 41730 return a.session && (await this._saveSession(a.session), await this._notifyAllSubscribers("SIGNED_IN", o)), this._returnResult({ data: { user: c, session: o }, error: null }); 41731 } catch (s) { 41732 if (Re(s)) 41733 return this._returnResult({ data: { user: null, session: null }, error: s }); 41734 throw s; 41735 } 41736 } 41737 /** 41738 * Creates a new user. 41739 * 41740 * Be aware that if a user account exists in the system you may get back an 41741 * error message that attempts to hide this information from the user. 41742 * This method has support for PKCE via email signups. The PKCE flow cannot be used when autoconfirm is enabled. 41743 * 41744 * @returns A logged-in session if the server has "autoconfirm" ON 41745 * @returns A user if the server has "autoconfirm" OFF 41746 * 41747 * @category Auth 41748 * 41749 * @remarks 41750 * - By default, the user needs to verify their email address before logging in. To turn this off, disable **Confirm email** in [your project](/dashboard/project/_/auth/providers). 41751 * - **Confirm email** determines if users need to confirm their email address after signing up. 41752 * - If **Confirm email** is enabled, a `user` is returned but `session` is null. 41753 * - If **Confirm email** is disabled, both a `user` and a `session` are returned. 41754 * - When the user confirms their email address, they are redirected to the [`SITE_URL`](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) by default. You can modify your `SITE_URL` or add additional redirect URLs in [your project](/dashboard/project/_/auth/url-configuration). 41755 * - If signUp() is called for an existing confirmed user: 41756 * - When both **Confirm email** and **Confirm phone** (even when phone provider is disabled) are enabled in [your project](/dashboard/project/_/auth/providers), an obfuscated/fake user object is returned. 41757 * - When either **Confirm email** or **Confirm phone** (even when phone provider is disabled) is disabled, the error message, `User already registered` is returned. 41758 * - To fetch the currently logged-in user, refer to [`getUser()`](/docs/reference/javascript/auth-getuser). 41759 * 41760 * @example Sign up with an email and password 41761 * ```js 41762 * const { data, error } = await supabase.auth.signUp({ 41763 * email: '[email protected]', 41764 * password: 'example-password', 41765 * }) 41766 * ``` 41767 * 41768 * @exampleResponse Sign up with an email and password 41769 * ```json 41770 * // Some fields may be null if "confirm email" is enabled. 41771 * { 41772 * "data": { 41773 * "user": { 41774 * "id": "11111111-1111-1111-1111-111111111111", 41775 * "aud": "authenticated", 41776 * "role": "authenticated", 41777 * "email": "[email protected]", 41778 * "email_confirmed_at": "2024-01-01T00:00:00Z", 41779 * "phone": "", 41780 * "last_sign_in_at": "2024-01-01T00:00:00Z", 41781 * "app_metadata": { 41782 * "provider": "email", 41783 * "providers": [ 41784 * "email" 41785 * ] 41786 * }, 41787 * "user_metadata": {}, 41788 * "identities": [ 41789 * { 41790 * "identity_id": "22222222-2222-2222-2222-222222222222", 41791 * "id": "11111111-1111-1111-1111-111111111111", 41792 * "user_id": "11111111-1111-1111-1111-111111111111", 41793 * "identity_data": { 41794 * "email": "[email protected]", 41795 * "email_verified": false, 41796 * "phone_verified": false, 41797 * "sub": "11111111-1111-1111-1111-111111111111" 41798 * }, 41799 * "provider": "email", 41800 * "last_sign_in_at": "2024-01-01T00:00:00Z", 41801 * "created_at": "2024-01-01T00:00:00Z", 41802 * "updated_at": "2024-01-01T00:00:00Z", 41803 * "email": "[email protected]" 41804 * } 41805 * ], 41806 * "created_at": "2024-01-01T00:00:00Z", 41807 * "updated_at": "2024-01-01T00:00:00Z" 41808 * }, 41809 * "session": { 41810 * "access_token": "<ACCESS_TOKEN>", 41811 * "token_type": "bearer", 41812 * "expires_in": 3600, 41813 * "expires_at": 1700000000, 41814 * "refresh_token": "<REFRESH_TOKEN>", 41815 * "user": { 41816 * "id": "11111111-1111-1111-1111-111111111111", 41817 * "aud": "authenticated", 41818 * "role": "authenticated", 41819 * "email": "[email protected]", 41820 * "email_confirmed_at": "2024-01-01T00:00:00Z", 41821 * "phone": "", 41822 * "last_sign_in_at": "2024-01-01T00:00:00Z", 41823 * "app_metadata": { 41824 * "provider": "email", 41825 * "providers": [ 41826 * "email" 41827 * ] 41828 * }, 41829 * "user_metadata": {}, 41830 * "identities": [ 41831 * { 41832 * "identity_id": "22222222-2222-2222-2222-222222222222", 41833 * "id": "11111111-1111-1111-1111-111111111111", 41834 * "user_id": "11111111-1111-1111-1111-111111111111", 41835 * "identity_data": { 41836 * "email": "[email protected]", 41837 * "email_verified": false, 41838 * "phone_verified": false, 41839 * "sub": "11111111-1111-1111-1111-111111111111" 41840 * }, 41841 * "provider": "email", 41842 * "last_sign_in_at": "2024-01-01T00:00:00Z", 41843 * "created_at": "2024-01-01T00:00:00Z", 41844 * "updated_at": "2024-01-01T00:00:00Z", 41845 * "email": "[email protected]" 41846 * } 41847 * ], 41848 * "created_at": "2024-01-01T00:00:00Z", 41849 * "updated_at": "2024-01-01T00:00:00Z" 41850 * } 41851 * } 41852 * }, 41853 * "error": null 41854 * } 41855 * ``` 41856 * 41857 * @example Sign up with a phone number and password (SMS) 41858 * ```js 41859 * const { data, error } = await supabase.auth.signUp({ 41860 * phone: '123456789', 41861 * password: 'example-password', 41862 * options: { 41863 * channel: 'sms' 41864 * } 41865 * }) 41866 * ``` 41867 * 41868 * @exampleDescription Sign up with a phone number and password (whatsapp) 41869 * The user will be sent a WhatsApp message which contains a OTP. By default, a given user can only request a OTP once every 60 seconds. Note that a user will need to have a valid WhatsApp account that is linked to Twilio in order to use this feature. 41870 * 41871 * @example Sign up with a phone number and password (whatsapp) 41872 * ```js 41873 * const { data, error } = await supabase.auth.signUp({ 41874 * phone: '123456789', 41875 * password: 'example-password', 41876 * options: { 41877 * channel: 'whatsapp' 41878 * } 41879 * }) 41880 * ``` 41881 * 41882 * @example Sign up with additional user metadata 41883 * ```js 41884 * const { data, error } = await supabase.auth.signUp( 41885 * { 41886 * email: '[email protected]', 41887 * password: 'example-password', 41888 * options: { 41889 * data: { 41890 * first_name: 'John', 41891 * age: 27, 41892 * } 41893 * } 41894 * } 41895 * ) 41896 * ``` 41897 * 41898 * @exampleDescription Sign up with a redirect URL
41899 * - See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project. 41900 * 41901 * @example Sign up with a redirect URL 41902 * ```js 41903 * const { data, error } = await supabase.auth.signUp( 41904 * { 41905 * email: '[email protected]', 41906 * password: 'example-password', 41907 * options: { 41908 * emailRedirectTo: 'https://example.com/welcome' 41909 * } 41910 * } 41911 * ) 41912 * ``` 41913 */ 41914 async signUp(e) { 41915 var t, i, r; 41916 try { 41917 let s; 41918 if ("email" in e) { 41919 const { email: u, password: h, options: d } = e; 41920 let f = null, p = null; 41921 this.flowType === "pkce" && ([f, p] = await _r(this.storage, this.storageKey)), s = await He(this.fetch, "POST", `${this.url}/signup`, { 41922 headers: this.headers, 41923 redirectTo: d?.emailRedirectTo, 41924 body: { 41925 email: u, 41926 password: h, 41927 data: (t = d?.data) !== null && t !== void 0 ? t : {}, 41928 gotrue_meta_security: { captcha_token: d?.captchaToken }, 41929 code_challenge: f, 41930 code_challenge_method: p 41931 }, 41932 xform: Bn 41933 }); 41934 } else if ("phone" in e) { 41935 const { phone: u, password: h, options: d } = e; 41936 s = await He(this.fetch, "POST", `${this.url}/signup`, { 41937 headers: this.headers, 41938 body: { 41939 phone: u, 41940 password: h, 41941 data: (i = d?.data) !== null && i !== void 0 ? i : {}, 41942 channel: (r = d?.channel) !== null && r !== void 0 ? r : "sms", 41943 gotrue_meta_security: { captcha_token: d?.captchaToken } 41944 }, 41945 xform: Bn 41946 }); 41947 } else 41948 throw new lo("You must provide either an email or phone number and a password"); 41949 const { data: a, error: l } = s; 41950 if (l || !a) 41951 return await $t(this.storage, `${this.storageKey}-code-verifier`), this._returnResult({ data: { user: null, session: null }, error: l }); 41952 const o = a.session, c = a.user; 41953 return a.session && (await this._saveSession(a.session), await this._notifyAllSubscribers("SIGNED_IN", o)), this._returnResult({ data: { user: c, session: o }, error: null }); 41954 } catch (s) { 41955 if (await $t(this.storage, `${this.storageKey}-code-verifier`), Re(s)) 41956 return this._returnResult({ data: { user: null, session: null }, error: s }); 41957 throw s; 41958 } 41959 } 41960 /** 41961 * Log in an existing user with an email and password or phone and password. 41962 * 41963 * Be aware that you may get back an error message that will not distinguish 41964 * between the cases where the account does not exist or that the 41965 * email/phone and password combination is wrong or that the account can only 41966 * be accessed via social login. 41967 * 41968 * @category Auth 41969 * 41970 * @remarks 41971 * - Requires either an email and password or a phone number and password. 41972 * 41973 * @example Sign in with email and password 41974 * ```js 41975 * const { data, error } = await supabase.auth.signInWithPassword({ 41976 * email: '[email protected]', 41977 * password: 'example-password', 41978 * }) 41979 * ``` 41980 * 41981 * @exampleResponse Sign in with email and password 41982 * ```json 41983 * { 41984 * "data": { 41985 * "user": { 41986 * "id": "11111111-1111-1111-1111-111111111111", 41987 * "aud": "authenticated", 41988 * "role": "authenticated", 41989 * "email": "[email protected]", 41990 * "email_confirmed_at": "2024-01-01T00:00:00Z", 41991 * "phone": "", 41992 * "last_sign_in_at": "2024-01-01T00:00:00Z", 41993 * "app_metadata": { 41994 * "provider": "email", 41995 * "providers": [ 41996 * "email" 41997 * ] 41998 * }, 41999 * "user_metadata": {}, 42000 * "identities": [ 42001 * { 42002 * "identity_id": "22222222-2222-2222-2222-222222222222", 42003 * "id": "11111111-1111-1111-1111-111111111111", 42004 * "user_id": "11111111-1111-1111-1111-111111111111", 42005 * "identity_data": { 42006 * "email": "[email protected]", 42007 * "email_verified": false, 42008 * "phone_verified": false, 42009 * "sub": "11111111-1111-1111-1111-111111111111" 42010 * }, 42011 * "provider": "email", 42012 * "last_sign_in_at": "2024-01-01T00:00:00Z", 42013 * "created_at": "2024-01-01T00:00:00Z", 42014 * "updated_at": "2024-01-01T00:00:00Z", 42015 * "email": "[email protected]" 42016 * } 42017 * ], 42018 * "created_at": "2024-01-01T00:00:00Z", 42019 * "updated_at": "2024-01-01T00:00:00Z" 42020 * }, 42021 * "session": { 42022 * "access_token": "<ACCESS_TOKEN>", 42023 * "token_type": "bearer", 42024 * "expires_in": 3600, 42025 * "expires_at": 1700000000, 42026 * "refresh_token": "<REFRESH_TOKEN>", 42027 * "user": { 42028 * "id": "11111111-1111-1111-1111-111111111111", 42029 * "aud": "authenticated", 42030 * "role": "authenticated", 42031 * "email": "[email protected]", 42032 * "email_confirmed_at": "2024-01-01T00:00:00Z", 42033 * "phone": "", 42034 * "last_sign_in_at": "2024-01-01T00:00:00Z", 42035 * "app_metadata": { 42036 * "provider": "email", 42037 * "providers": [ 42038 * "email" 42039 * ] 42040 * }, 42041 * "user_metadata": {}, 42042 * "identities": [ 42043 * { 42044 * "identity_id": "22222222-2222-2222-2222-222222222222", 42045 * "id": "11111111-1111-1111-1111-111111111111", 42046 * "user_id": "11111111-1111-1111-1111-111111111111", 42047 * "identity_data": { 42048 * "email": "[email protected]", 42049 * "email_verified": false, 42050 * "phone_verified": false, 42051 * "sub": "11111111-1111-1111-1111-111111111111" 42052 * }, 42053 * "provider": "email", 42054 * "last_sign_in_at": "2024-01-01T00:00:00Z", 42055 * "created_at": "2024-01-01T00:00:00Z", 42056 * "updated_at": "2024-01-01T00:00:00Z", 42057 * "email": "[email protected]" 42058 * } 42059 * ], 42060 * "created_at": "2024-01-01T00:00:00Z", 42061 * "updated_at": "2024-01-01T00:00:00Z" 42062 * } 42063 * } 42064 * }, 42065 * "error": null 42066 * } 42067 * ``` 42068 * 42069 * @example Sign in with phone and password 42070 * ```js 42071 * const { data, error } = await supabase.auth.signInWithPassword({ 42072 * phone: '+13334445555', 42073 * password: 'some-password', 42074 * }) 42075 * ``` 42076 * 42077 * @exampleDescription Handling errors 42078 * Log the full `error` object so fields like `code`, `status`, and `name` aren't hidden. The `error.code` (e.g. `'invalid_credentials'`, `'email_not_confirmed'`) is often more useful for branching than `error.message`, and the full object surfaces both. 42079 * 42080 * @example Handling errors 42081 * ```js 42082 * const { data, error } = await supabase.auth.signInWithPassword({ 42083 * email: '[email protected]', 42084 * password: 'example-password', 42085 * }) 42086 * if (error) { 42087 * console.error(error) 42088 * return 42089 * } 42090 * ``` 42091 */ 42092 async signInWithPassword(e) { 42093 try { 42094 let t; 42095 if ("email" in e) { 42096 const { email: s, password: a, options: l } = e; 42097 t = await He(this.fetch, "POST", `${this.url}/token?grant_type=password`, { 42098 headers: this.headers, 42099 body: { 42100 email: s, 42101 password: a,
42102 gotrue_meta_security: { captcha_token: l?.captchaToken } 42103 }, 42104 xform: bf 42105 }); 42106 } else if ("phone" in e) { 42107 const { phone: s, password: a, options: l } = e; 42108 t = await He(this.fetch, "POST", `${this.url}/token?grant_type=password`, { 42109 headers: this.headers, 42110 body: { 42111 phone: s, 42112 password: a, 42113 gotrue_meta_security: { captcha_token: l?.captchaToken } 42114 }, 42115 xform: bf 42116 }); 42117 } else 42118 throw new lo("You must provide either an email or phone number and a password"); 42119 const { data: i, error: r } = t; 42120 if (r) 42121 return this._returnResult({ data: { user: null, session: null }, error: r }); 42122 if (!i || !i.session || !i.user) { 42123 const s = new es(); 42124 return this._returnResult({ data: { user: null, session: null }, error: s }); 42125 } 42126 return i.session && (await this._saveSession(i.session), await this._notifyAllSubscribers("SIGNED_IN", i.session)), this._returnResult({ 42127 data: Object.assign({ user: i.user, session: i.session }, i.weak_password ? { weakPassword: i.weak_password } : null), 42128 error: r 42129 }); 42130 } catch (t) { 42131 if (Re(t)) 42132 return this._returnResult({ data: { user: null, session: null }, error: t }); 42133 throw t; 42134 } 42135 } 42136 /** 42137 * Log in an existing user via a third-party provider. 42138 * This method supports the PKCE flow. 42139 * 42140 * @category Auth 42141 * 42142 * @remarks 42143 * - This method is used for signing in using [Social Login (OAuth) providers](/docs/guides/auth#configure-third-party-providers). 42144 * - It works by redirecting your application to the provider's authorization screen, before bringing back the user to your app. 42145 * 42146 * @example Sign in using a third-party provider 42147 * ```js 42148 * const { data, error } = await supabase.auth.signInWithOAuth({ 42149 * provider: 'github' 42150 * }) 42151 * ``` 42152 * 42153 * @exampleResponse Sign in using a third-party provider 42154 * ```json 42155 * { 42156 * data: { 42157 * provider: 'github', 42158 * url: <PROVIDER_URL_TO_REDIRECT_TO> 42159 * }, 42160 * error: null 42161 * } 42162 * ``` 42163 * 42164 * @exampleDescription Sign in using a third-party provider with redirect 42165 * - When the OAuth provider successfully authenticates the user, they are redirected to the URL specified in the `redirectTo` parameter. This parameter defaults to the [`SITE_URL`](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls). It does not redirect the user immediately after invoking this method. 42166 * - See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project. 42167 * 42168 * @example Sign in using a third-party provider with redirect 42169 * ```js 42170 * const { data, error } = await supabase.auth.signInWithOAuth({ 42171 * provider: 'github', 42172 * options: { 42173 * redirectTo: 'https://example.com/welcome' 42174 * } 42175 * }) 42176 * ``` 42177 * 42178 * @exampleDescription Sign in with scopes and access provider tokens 42179 * If you need additional access from an OAuth provider, in order to access provider specific APIs in the name of the user, you can do this by passing in the scopes the user should authorize for your application. Note that the `scopes` option takes in **a space-separated list** of scopes. 42180 * 42181 * Because OAuth sign-in often includes redirects, you should register an `onAuthStateChange` callback immediately after you create the Supabase client. This callback will listen for the presence of `provider_token` and `provider_refresh_token` properties on the `session` object and store them in local storage. The client library will emit these values **only once** immediately after the user signs in. You can then access them by looking them up in local storage, or send them to your backend servers for further processing. 42182 * 42183 * Finally, make sure you remove them from local storage on the `SIGNED_OUT` event. If the OAuth provider supports token revocation, make sure you call those APIs either from the frontend or schedule them to be called on the backend. 42184 * 42185 * @example Sign in with scopes and access provider tokens 42186 * ```js 42187 * // Register this immediately after calling createClient! 42188 * // Because signInWithOAuth causes a redirect, you need to fetch the 42189 * // provider tokens from the callback. 42190 * supabase.auth.onAuthStateChange((event, session) => { 42191 * if (session && session.provider_token) { 42192 * window.localStorage.setItem('oauth_provider_token', session.provider_token) 42193 * } 42194 * 42195 * if (session && session.provider_refresh_token) { 42196 * window.localStorage.setItem('oauth_provider_refresh_token', session.provider_refresh_token) 42197 * } 42198 * 42199 * if (event === 'SIGNED_OUT') { 42200 * window.localStorage.removeItem('oauth_provider_token') 42201 * window.localStorage.removeItem('oauth_provider_refresh_token') 42202 * } 42203 * }) 42204 * 42205 * // Call this on your Sign in with GitHub button to initiate OAuth 42206 * // with GitHub with the requested elevated scopes. 42207 * await supabase.auth.signInWithOAuth({ 42208 * provider: 'github', 42209 * options: { 42210 * scopes: 'repo gist notifications' 42211 * } 42212 * }) 42213 * ``` 42214 */ 42215 async signInWithOAuth(e) { 42216 var t, i, r, s; 42217 return await this._handleProviderSignIn(e.provider, { 42218 redirectTo: (t = e.options) === null || t === void 0 ? void 0 : t.redirectTo, 42219 scopes: (i = e.options) === null || i === void 0 ? void 0 : i.scopes, 42220 queryParams: (r = e.options) === null || r === void 0 ? void 0 : r.queryParams, 42221 skipBrowserRedirect: (s = e.options) === null || s === void 0 ? void 0 : s.skipBrowserRedirect 42222 }); 42223 } 42224 /** 42225 * Log in an existing user by exchanging an Auth Code issued during the PKCE flow. 42226 * 42227 * @category Auth 42228 * 42229 * @remarks 42230 * - Used when `flowType` is set to `pkce` in client options. 42231 * 42232 * @example Exchange Auth Code 42233 * ```js 42234 * supabase.auth.exchangeCodeForSession('34e770dd-9ff9-416c-87fa-43b31d7ef225') 42235 * ``` 42236 * 42237 * @exampleResponse Exchange Auth Code 42238 * ```json 42239 * { 42240 * "data": { 42241 * session: { 42242 * access_token: '<ACCESS_TOKEN>', 42243 * token_type: 'bearer', 42244 * expires_in: 3600, 42245 * expires_at: 1700000000,
42246 * refresh_token: '<REFRESH_TOKEN>', 42247 * user: { 42248 * id: '11111111-1111-1111-1111-111111111111', 42249 * aud: 'authenticated', 42250 * role: 'authenticated', 42251 * email: '[email protected]' 42252 * email_confirmed_at: '2024-01-01T00:00:00Z', 42253 * phone: '', 42254 * confirmation_sent_at: '2024-01-01T00:00:00Z', 42255 * confirmed_at: '2024-01-01T00:00:00Z', 42256 * last_sign_in_at: '2024-01-01T00:00:00Z', 42257 * app_metadata: { 42258 * "provider": "email", 42259 * "providers": [ 42260 * "email", 42261 * "<OTHER_PROVIDER>" 42262 * ] 42263 * }, 42264 * user_metadata: { 42265 * email: '[email protected]', 42266 * email_verified: true, 42267 * full_name: 'User Name', 42268 * iss: '<ISS>', 42269 * name: 'User Name', 42270 * phone_verified: false, 42271 * provider_id: '<PROVIDER_ID>', 42272 * sub: '<SUB>' 42273 * }, 42274 * identities: [ 42275 * { 42276 * "identity_id": "22222222-2222-2222-2222-222222222222", 42277 * "id": "11111111-1111-1111-1111-111111111111", 42278 * "user_id": "11111111-1111-1111-1111-111111111111", 42279 * "identity_data": { 42280 * "email": "[email protected]", 42281 * "email_verified": false, 42282 * "phone_verified": false, 42283 * "sub": "11111111-1111-1111-1111-111111111111" 42284 * }, 42285 * "provider": "email", 42286 * "last_sign_in_at": "2024-01-01T00:00:00Z", 42287 * "created_at": "2024-01-01T00:00:00Z", 42288 * "updated_at": "2024-01-01T00:00:00Z", 42289 * "email": "[email protected]" 42290 * }, 42291 * { 42292 * "identity_id": "33333333-3333-3333-3333-333333333333", 42293 * "id": "<ID>", 42294 * "user_id": "<USER_ID>", 42295 * "identity_data": { 42296 * "email": "[email protected]", 42297 * "email_verified": true, 42298 * "full_name": "User Name", 42299 * "iss": "<ISS>", 42300 * "name": "User Name", 42301 * "phone_verified": false, 42302 * "provider_id": "<PROVIDER_ID>", 42303 * "sub": "<SUB>" 42304 * }, 42305 * "provider": "<PROVIDER>", 42306 * "last_sign_in_at": "2024-01-01T00:00:00Z", 42307 * "created_at": "2024-01-01T00:00:00Z", 42308 * "updated_at": "2024-01-01T00:00:00Z", 42309 * "email": "[email protected]" 42310 * } 42311 * ], 42312 * created_at: '2024-01-01T00:00:00Z', 42313 * updated_at: '2024-01-01T00:00:00Z', 42314 * is_anonymous: false 42315 * }, 42316 * provider_token: '<PROVIDER_TOKEN>', 42317 * provider_refresh_token: '<PROVIDER_REFRESH_TOKEN>' 42318 * }, 42319 * user: { 42320 * id: '11111111-1111-1111-1111-111111111111', 42321 * aud: 'authenticated', 42322 * role: 'authenticated', 42323 * email: '[email protected]', 42324 * email_confirmed_at: '2024-01-01T00:00:00Z', 42325 * phone: '', 42326 * confirmation_sent_at: '2024-01-01T00:00:00Z', 42327 * confirmed_at: '2024-01-01T00:00:00Z', 42328 * last_sign_in_at: '2024-01-01T00:00:00Z', 42329 * app_metadata: { 42330 * provider: 'email', 42331 * providers: [ 42332 * "email", 42333 * "<OTHER_PROVIDER>" 42334 * ] 42335 * }, 42336 * user_metadata: { 42337 * email: '[email protected]', 42338 * email_verified: true, 42339 * full_name: 'User Name', 42340 * iss: '<ISS>', 42341 * name: 'User Name', 42342 * phone_verified: false, 42343 * provider_id: '<PROVIDER_ID>', 42344 * sub: '<SUB>' 42345 * }, 42346 * identities: [ 42347 * { 42348 * "identity_id": "22222222-2222-2222-2222-222222222222", 42349 * "id": "11111111-1111-1111-1111-111111111111", 42350 * "user_id": "11111111-1111-1111-1111-111111111111", 42351 * "identity_data": { 42352 * "email": "[email protected]", 42353 * "email_verified": false, 42354 * "phone_verified": false, 42355 * "sub": "11111111-1111-1111-1111-111111111111" 42356 * }, 42357 * "provider": "email", 42358 * "last_sign_in_at": "2024-01-01T00:00:00Z", 42359 * "created_at": "2024-01-01T00:00:00Z", 42360 * "updated_at": "2024-01-01T00:00:00Z", 42361 * "email": "[email protected]" 42362 * }, 42363 * { 42364 * "identity_id": "33333333-3333-3333-3333-333333333333", 42365 * "id": "<ID>", 42366 * "user_id": "<USER_ID>", 42367 * "identity_data": { 42368 * "email": "[email protected]", 42369 * "email_verified": true, 42370 * "full_name": "User Name", 42371 * "iss": "<ISS>", 42372 * "name": "User Name", 42373 * "phone_verified": false, 42374 * "provider_id": "<PROVIDER_ID>", 42375 * "sub": "<SUB>" 42376 * }, 42377 * "provider": "<PROVIDER>", 42378 * "last_sign_in_at": "2024-01-01T00:00:00Z", 42379 * "created_at": "2024-01-01T00:00:00Z", 42380 * "updated_at": "2024-01-01T00:00:00Z", 42381 * "email": "[email protected]" 42382 * } 42383 * ], 42384 * created_at: '2024-01-01T00:00:00Z', 42385 * updated_at: '2024-01-01T00:00:00Z', 42386 * is_anonymous: false 42387 * }, 42388 * redirectType: null 42389 * }, 42390 * "error": null 42391 * } 42392 * ``` 42393 */ 42394 async exchangeCodeForSession(e) { 42395 return await this.initializePromise, this.lock != null ? this._acquireLock(this.lockAcquireTimeout, async () => this._exchangeCodeForSession(e)) : this._exchangeCodeForSession(e); 42396 } 42397 /** 42398 * Signs in a user by verifying a message signed by the user's private key. 42399 * Supports Ethereum (via Sign-In-With-Ethereum) & Solana (Sign-In-With-Solana) standards, 42400 * both of which derive from the EIP-4361 standard 42401 * With slight variation on Solana's side. 42402 * @reference https://eips.ethereum.org/EIPS/eip-4361 42403 * 42404 * @category Auth 42405 * 42406 * @remarks 42407 * - Uses a Web3 (Ethereum, Solana) wallet to sign a user in. 42408 * - Read up on the [potential for abuse](/docs/guides/auth/auth-web3#potential-for-abuse) before using it. 42409 * 42410 * @example Sign in with Solana or Ethereum (Window API) 42411 * ```js 42412 * // uses window.ethereum for the wallet 42413 * const { data, error } = await supabase.auth.signInWithWeb3({ 42414 * chain: 'ethereum', 42415 * statement: 'I accept the Terms of Service at https://example.com/tos' 42416 * }) 42417 * 42418 * // uses window.solana for the wallet 42419 * const { data, error } = await supabase.auth.signInWithWeb3({ 42420 * chain: 'solana', 42421 * statement: 'I accept the Terms of Service at https://example.com/tos' 42422 * }) 42423 * ``` 42424 * 42425 * @example Sign in with Ethereum (Message and Signature) 42426 * ```js 42427 * const { data, error } = await supabase.auth.signInWithWeb3({ 42428 * chain: 'ethereum', 42429 * message: '<sign in with ethereum message>', 42430 * signature: '<hex of the ethereum signature over the message>', 42431 * }) 42432 * ``` 42433 * 42434 * @example Sign in with Solana (Brave) 42435 * ```js 42436 * const { data, error } = await supabase.auth.signInWithWeb3({ 42437 * chain: 'solana', 42438 * statement: 'I accept the Terms of Service at https://example.com/tos', 42439 * wallet: window.braveSolana 42440 * }) 42441 * ``` 42442 * 42443 * @example Sign in with Solana (Wallet Adapter) 42444 * ```jsx 42445 * function SignInButton() { 42446 * const wallet = useWallet() 42447 * 42448 * return ( 42449 * <> 42450 * {wallet.connected ? ( 42451 * <button 42452 * onClick={() => { 42453 * supabase.auth.signInWithWeb3({ 42454 * chain: 'solana', 42455 * statement: 'I accept the Terms of Service at https://example.com/tos', 42456 * wallet, 42457 * }) 42458 * }} 42459 * > 42460 * Sign in with Solana 42461 * </button> 42462 * ) : ( 42463 * <WalletMultiButton /> 42464 * )} 42465 * </> 42466 * ) 42467 * } 42468 * 42469 * function App() { 42470 * const endpoint = clusterApiUrl('devnet') 42471 * const wallets = useMemo(() => [], []) 42472 * 42473 * return ( 42474 * <ConnectionProvider endpoint={endpoint}> 42475 * <WalletProvider wallets={wallets}> 42476 * <WalletModalProvider> 42477 * <SignInButton /> 42478 * </WalletModalProvider> 42479 * </WalletProvider> 42480 * </ConnectionProvider> 42481 * ) 42482 * } 42483 * ``` 42484 */ 42485 async signInWithWeb3(e) { 42486 const { chain: t } = e; 42487 switch (t) { 42488 case "ethereum": 42489 return await this.signInWithEthereum(e); 42490 case "solana": 42491 return await this.signInWithSolana(e); 42492 default: 42493 throw new Error(`@supabase/auth-js: Unsupported chain "${t}"`); 42494 } 42495 } 42496 async signInWithEthereum(e) { 42497 var t, i, r, s, a, l, o, c, u, h, d; 42498 let f, p; 42499 if ("message" in e) 42500 f = e.message, p = e.signature; 42501 else { 42502 const { chain: v, wallet: m, statement: g, options: _ } = e; 42503 let x; 42504 if (hn()) 42505 if (typeof m == "object") 42506 x = m; 42507 else { 42508 const M = window; 42509 if ("ethereum" in M && typeof M.ethereum == "object" && "request" in M.ethereum && typeof M.ethereum.request == "function") 42510 x = M.ethereum; 42511 else 42512 throw new Error("@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead."); 42513 } 42514 else { 42515 if (typeof m != "object" || !_?.url) 42516 throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments."); 42517 x = m; 42518 } 42519 const E = new URL((t = _?.url) !== null && t !== void 0 ? t : window.location.href), R = await x.request({ 42520 method: "eth_requestAccounts" 42521 }).then((M) => M).catch(() => { 42522 throw new Error("@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid"); 42523 }); 42524 if (!R || R.length === 0) 42525 throw new Error("@supabase/auth-js: No accounts available. Please ensure the wallet is connected."); 42526 const T = Om(R[0]); 42527 let w = (i = _?.signInWithEthereum) === null || i === void 0 ? void 0 : i.chainId; 42528 if (!w) { 42529 const M = await x.request({ 42530 method: "eth_chainId" 42531 }); 42532 w = S1(M); 42533 } 42534 const y = { 42535 domain: E.host, 42536 address: T, 42537 statement: g, 42538 uri: E.href, 42539 version: "1", 42540 chainId: w, 42541 nonce: (r = _?.signInWithEthereum) === null || r === void 0 ? void 0 : r.nonce, 42542 issuedAt: (a = (s = _?.signInWithEthereum) === null || s === void 0 ? void 0 : s.issuedAt) !== null && a !== void 0 ? a : /* @__PURE__ */ new Date(), 42543 expirationTime: (l = _?.signInWithEthereum) === null || l === void 0 ? void 0 : l.expirationTime, 42544 notBefore: (o = _?.signInWithEthereum) === null || o === void 0 ? void 0 : o.notBefore, 42545 requestId: (c = _?.signInWithEthereum) === null || c === void 0 ? void 0 : c.requestId, 42546 resources: (u = _?.signInWithEthereum) === null || u === void 0 ? void 0 : u.resources 42547 }; 42548 f = M1(y), p = await x.request({ 42549 method: "personal_sign",
42550 params: [E1(f), T] 42551 }); 42552 } 42553 try { 42554 const { data: v, error: m } = await He(this.fetch, "POST", `${this.url}/token?grant_type=web3`, { 42555 headers: this.headers, 42556 body: Object.assign({ 42557 chain: "ethereum", 42558 message: f, 42559 signature: p 42560 }, !((h = e.options) === null || h === void 0) && h.captchaToken ? { gotrue_meta_security: { captcha_token: (d = e.options) === null || d === void 0 ? void 0 : d.captchaToken } } : null), 42561 xform: Bn 42562 }); 42563 if (m) 42564 throw m; 42565 if (!v || !v.session || !v.user) { 42566 const g = new es(); 42567 return this._returnResult({ data: { user: null, session: null }, error: g }); 42568 } 42569 return v.session && (await this._saveSession(v.session), await this._notifyAllSubscribers("SIGNED_IN", v.session)), this._returnResult({ data: Object.assign({}, v), error: m }); 42570 } catch (v) { 42571 if (Re(v)) 42572 return this._returnResult({ data: { user: null, session: null }, error: v }); 42573 throw v; 42574 } 42575 } 42576 async signInWithSolana(e) { 42577 var t, i, r, s, a, l, o, c, u, h, d, f; 42578 let p, v; 42579 if ("message" in e) 42580 p = e.message, v = e.signature; 42581 else { 42582 const { chain: m, wallet: g, statement: _, options: x } = e; 42583 let E; 42584 if (hn()) 42585 if (typeof g == "object") 42586 E = g; 42587 else { 42588 const T = window; 42589 if ("solana" in T && typeof T.solana == "object" && ("signIn" in T.solana && typeof T.solana.signIn == "function" || "signMessage" in T.solana && typeof T.solana.signMessage == "function")) 42590 E = T.solana; 42591 else 42592 throw new Error("@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead."); 42593 } 42594 else { 42595 if (typeof g != "object" || !x?.url) 42596 throw new Error("@supabase/auth-js: Both wallet and url must be specified in non-browser environments."); 42597 E = g; 42598 } 42599 const R = new URL((t = x?.url) !== null && t !== void 0 ? t : window.location.href); 42600 if ("signIn" in E && E.signIn) { 42601 const T = await E.signIn(Object.assign(Object.assign(Object.assign({ issuedAt: (/* @__PURE__ */ new Date()).toISOString() }, x?.signInWithSolana), { 42602 // non-overridable properties 42603 version: "1", 42604 domain: R.host, 42605 uri: R.href 42606 }), _ ? { statement: _ } : null)); 42607 let w; 42608 if (Array.isArray(T) && T[0] && typeof T[0] == "object") 42609 w = T[0]; 42610 else if (T && typeof T == "object" && "signedMessage" in T && "signature" in T) 42611 w = T; 42612 else 42613 throw new Error("@supabase/auth-js: Wallet method signIn() returned unrecognized value"); 42614 if ("signedMessage" in w && "signature" in w && (typeof w.signedMessage == "string" || w.signedMessage instanceof Uint8Array) && w.signature instanceof Uint8Array) 42615 p = typeof w.signedMessage == "string" ? w.signedMessage : new TextDecoder().decode(w.signedMessage), v = w.signature; 42616 else 42617 throw new Error("@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields"); 42618 } else { 42619 if (!("signMessage" in E) || typeof E.signMessage != "function" || !("publicKey" in E) || typeof E != "object" || !E.publicKey || !("toBase58" in E.publicKey) || typeof E.publicKey.toBase58 != "function") 42620 throw new Error("@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API"); 42621 p = [ 42622 `${R.host} wants you to sign in with your Solana account:`, 42623 E.publicKey.toBase58(), 42624 ..._ ? ["", _, ""] : [""], 42625 "Version: 1", 42626 `URI: ${R.href}`, 42627 `Issued At: ${(r = (i = x?.signInWithSolana) === null || i === void 0 ? void 0 : i.issuedAt) !== null && r !== void 0 ? r : (/* @__PURE__ */ new Date()).toISOString()}`, 42628 ...!((s = x?.signInWithSolana) === null || s === void 0) && s.notBefore ? [`Not Before: ${x.signInWithSolana.notBefore}`] : [], 42629 ...!((a = x?.signInWithSolana) === null || a === void 0) && a.expirationTime ? [`Expiration Time: ${x.signInWithSolana.expirationTime}`] : [], 42630 ...!((l = x?.signInWithSolana) === null || l === void 0) && l.chainId ? [`Chain ID: ${x.signInWithSolana.chainId}`] : [], 42631 ...!((o = x?.signInWithSolana) === null || o === void 0) && o.nonce ? [`Nonce: ${x.signInWithSolana.nonce}`] : [], 42632 ...!((c = x?.signInWithSolana) === null || c === void 0) && c.requestId ? [`Request ID: ${x.signInWithSolana.requestId}`] : [], 42633 ...!((h = (u = x?.signInWithSolana) === null || u === void 0 ? void 0 : u.resources) === null || h === void 0) && h.length ? [ 42634 "Resources", 42635 ...x.signInWithSolana.resources.map((w) => `- ${w}`) 42636 ] : [] 42637 ].join(` 42638`); 42639 const T = await E.signMessage(new TextEncoder().encode(p), "utf8"); 42640 if (!T || !(T instanceof Uint8Array)) 42641 throw new Error("@supabase/auth-js: Wallet signMessage() API returned an recognized value"); 42642 v = T; 42643 } 42644 } 42645 try { 42646 const { data: m, error: g } = await He(this.fetch, "POST", `${this.url}/token?grant_type=web3`, { 42647 headers: this.headers, 42648 body: Object.assign({ chain: "solana", message: p, signature: Rr(v) }, !((d = e.options) === null || d === void 0) && d.captchaToken ? { gotrue_meta_security: { c
42648aptcha_token: (f = e.options) === null || f === void 0 ? void 0 : f.captchaToken } } : null), 42649 xform: Bn 42650 }); 42651 if (g) 42652 throw g; 42653 if (!m || !m.session || !m.user) { 42654 const _ = new es(); 42655 return this._returnResult({ data: { user: null, session: null }, error: _ }); 42656 } 42657 return m.session && (await this._saveSession(m.session), await this._notifyAllSubscribers("SIGNED_IN", m.session)), this._returnResult({ data: Object.assign({}, m), error: g }); 42658 } catch (m) { 42659 if (Re(m)) 42660 return this._returnResult({ data: { user: null, session: null }, error: m }); 42661 throw m; 42662 } 42663 } 42664 async _exchangeCodeForSession(e) { 42665 const t = await Ai(this.storage, `${this.storageKey}-code-verifier`), [i, r] = (t ?? "").split("/"); 42666 try { 42667 if (!i && this.flowType === "pkce") 42668 throw new $T(); 42669 const { data: s, error: a } = await He(this.fetch, "POST", `${this.url}/token?grant_type=pkce`, { 42670 headers: this.headers, 42671 body: { 42672 auth_code: e, 42673 code_verifier: i 42674 }, 42675 xform: Bn 42676 }); 42677 if (await $t(this.storage, `${this.storageKey}-code-verifier`), a) 42678 throw a; 42679 if (!s || !s.session || !s.user) { 42680 const l = new es(); 42681 return this._returnResult({ 42682 data: { user: null, session: null, redirectType: null }, 42683 error: l 42684 }); 42685 } 42686 return s.session && (await this._saveSession(s.session), await this._notifyAllSubscribers(r === "recovery" ? "PASSWORD_RECOVERY" : "SIGNED_IN", s.session)), this._returnResult({ data: Object.assign(Object.assign({}, s), { redirectType: r ?? null }), error: a }); 42687 } catch (s) { 42688 if (await $t(this.storage, `${this.storageKey}-code-verifier`), Re(s)) 42689 return this._returnResult({ 42690 data: { user: null, session: null, redirectType: null }, 42691 error: s 42692 }); 42693 throw s; 42694 } 42695 } 42696 /** 42697 * Allows signing in with an OIDC ID token. The authentication provider used 42698 * should be enabled and configured. 42699 * 42700 * @category Auth 42701 * 42702 * @remarks 42703 * - Use an ID token to sign in. 42704 * - Especially useful when implementing sign in using native platform dialogs in mobile or desktop apps using Sign in with Apple or Sign in with Google on iOS and Android. 42705 * - You can also use Google's [One Tap](https://developers.google.com/identity/gsi/web/guides/display-google-one-tap) and [Automatic sign-in](https://developers.google.com/identity/gsi/web/guides/automatic-sign-in-sign-out) via this API. 42706 * 42707 * @example Sign In using ID Token 42708 * ```js 42709 * const { data, error } = await supabase.auth.signInWithIdToken({ 42710 * provider: 'google', 42711 * token: 'your-id-token' 42712 * }) 42713 * ``` 42714 * 42715 * @exampleResponse Sign In using ID Token 42716 * ```json 42717 * { 42718 * "data": { 42719 * "user": { 42720 * "id": "11111111-1111-1111-1111-111111111111", 42721 * "aud": "authenticated", 42722 * "role": "authenticated", 42723 * "last_sign_in_at": "2024-01-01T00:00:00Z", 42724 * "app_metadata": { 42725 * ... 42726 * }, 42727 * "user_metadata": { 42728 * ... 42729 * }, 42730 * "identities": [ 42731 * { 42732 * "identity_id": "22222222-2222-2222-2222-222222222222", 42733 * "provider": "google", 42734 * } 42735 * ], 42736 * "created_at": "2024-01-01T00:00:00Z", 42737 * "updated_at": "2024-01-01T00:00:00Z", 42738 * }, 42739 * "session": { 42740 * "access_token": "<ACCESS_TOKEN>", 42741 * "token_type": "bearer", 42742 * "expires_in": 3600, 42743 * "expires_at": 1700000000, 42744 * "refresh_token": "<REFRESH_TOKEN>", 42745 * "user": { 42746 * "id": "11111111-1111-1111-1111-111111111111", 42747 * "aud": "authenticated", 42748 * "role": "authenticated", 42749 * "last_sign_in_at": "2024-01-01T00:00:00Z", 42750 * "app_metadata": { 42751 * ... 42752 * }, 42753 * "user_metadata": { 42754 * ... 42755 * }, 42756 * "identities": [ 42757 * { 42758 * "identity_id": "22222222-2222-2222-2222-222222222222", 42759 * "provider": "google", 42760 * } 42761 * ], 42762 * "created_at": "2024-01-01T00:00:00Z", 42763 * "updated_at": "2024-01-01T00:00:00Z", 42764 * } 42765 * } 42766 * }, 42767 * "error": null 42768 * } 42769 * ``` 42770 */ 42771 async signInWithIdToken(e) { 42772 try { 42773 const { options: t, provider: i, token: r, access_token: s, nonce: a } = e, l = await He(this.fetch, "POST", `${this.url}/token?grant_type=id_token`, { 42774 headers: this.headers, 42775 body: { 42776 provider: i, 42777 id_token: r, 42778 access_token: s, 42779 nonce: a,
42780 gotrue_meta_security: { captcha_token: t?.captchaToken } 42781 }, 42782 xform: Bn 42783 }), { data: o, error: c } = l; 42784 if (c) 42785 return this._returnResult({ data: { user: null, session: null }, error: c }); 42786 if (!o || !o.session || !o.user) { 42787 const u = new es(); 42788 return this._returnResult({ data: { user: null, session: null }, error: u }); 42789 } 42790 return o.session && (await this._saveSession(o.session), await this._notifyAllSubscribers("SIGNED_IN", o.session)), this._returnResult({ data: o, error: c }); 42791 } catch (t) { 42792 if (Re(t)) 42793 return this._returnResult({ data: { user: null, session: null }, error: t }); 42794 throw t; 42795 } 42796 } 42797 /** 42798 * Log in a user using magiclink or a one-time password (OTP). 42799 * 42800 * If the `{{ .ConfirmationURL }}` variable is specified in the email template, a magiclink will be sent. 42801 * If the `{{ .Token }}` variable is specified in the email template, an OTP will be sent. 42802 * If you're using phone sign-ins, only an OTP will be sent. You won't be able to send a magiclink for phone sign-ins. 42803 * 42804 * Be aware that you may get back an error message that will not distinguish 42805 * between the cases where the account does not exist or, that the account 42806 * can only be accessed via social login. 42807 * 42808 * Do note that you will need to configure a Whatsapp sender on Twilio 42809 * if you are using phone sign in with the 'whatsapp' channel. The whatsapp 42810 * channel is not supported on other providers 42811 * at this time. 42812 * This method supports PKCE when an email is passed. 42813 * 42814 * @category Auth 42815 * 42816 * @remarks 42817 * - Requires either an email or phone number. 42818 * - This method is used for passwordless sign-ins where a OTP is sent to the user's email or phone number. 42819 * - If the user doesn't exist, `signInWithOtp()` will signup the user instead. To restrict this behavior, you can set `shouldCreateUser` in `SignInWithPasswordlessCredentials.options` to `false`. 42820 * - If you're using an email, you can configure whether you want the user to receive a magiclink or a OTP. 42821 * - If you're using phone, you can configure whether you want the user to receive a OTP. 42822 * - The magic link's destination URL is determined by the [`SITE_URL`](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls). 42823 * - See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project. 42824 * - Magic links and OTPs share the same implementation. To send users a one-time code instead of a magic link, [modify the magic link email template](/dashboard/project/_/auth/templates) to include `{{ .Token }}` instead of `{{ .ConfirmationURL }}`. 42825 * - See our [Twilio Phone Auth Guide](/docs/guides/auth/phone-login?showSMSProvider=Twilio) for details about configuring WhatsApp sign in. 42826 * 42827 * @exampleDescription Sign in with email 42828 * The user will be sent an email which contains either a magiclink or a OTP or both. By default, a given user can only request a OTP once every 60 seconds. 42829 * 42830 * @example Sign in with email 42831 * ```js 42832 * const { data, error } = await supabase.auth.signInWithOtp({ 42833 * email: '[email protected]', 42834 * options: { 42835 * emailRedirectTo: 'https://example.com/welcome' 42836 * } 42837 * }) 42838 * ``` 42839 * 42840 * @exampleResponse Sign in with email 42841 * ```json 42842 * { 42843 * "data": { 42844 * "user": null, 42845 * "session": null 42846 * }, 42847 * "error": null 42848 * } 42849 * ``` 42850 * 42851 * @exampleDescription Sign in with SMS OTP 42852 * The user will be sent a SMS which contains a OTP. By default, a given user can only request a OTP once every 60 seconds. 42853 * 42854 * @example Sign in with SMS OTP 42855 * ```js 42856 * const { data, error } = await supabase.auth.signInWithOtp({ 42857 * phone: '+13334445555', 42858 * }) 42859 * ``` 42860 * 42861 * @exampleDescription Sign in with WhatsApp OTP 42862 * The user will be sent a WhatsApp message which contains a OTP. By default, a given user can only request a OTP once every 60 seconds. Note that a user will need to have a valid WhatsApp account that is linked to Twilio in order to use this feature. 42863 * 42864 * @example Sign in with WhatsApp OTP 42865 * ```js 42866 * const { data, error } = await supabase.auth.signInWithOtp({ 42867 * phone: '+13334445555', 42868 * options: { 42869 * channel:'whatsapp', 42870 * } 42871 * }) 42872 * ``` 42873 */ 42874 async signInWithOtp(e) { 42875 var t, i, r, s, a; 42876 try { 42877 if ("email" in e) { 42878 const { email: l, options: o } = e; 42879 let c = null, u = null; 42880 this.flowType === "pkce" && ([c, u] = await _r(this.storage, this.storageKey)); 42881 const { error: h } = await He(this.fetch, "POST", `${this.url}/otp`, { 42882 headers: this.headers, 42883 body: { 42884 email: l, 42885 data: (t = o?.data) !== null && t !== void 0 ? t : {}, 42886 create_user: (i = o?.shouldCreateUser) !== null && i !== void 0 ? i : !0,
42887 gotrue_meta_security: { captcha_token: o?.captchaToken }, 42888 code_challenge: c, 42889 code_challenge_method: u 42890 }, 42891 redirectTo: o?.emailRedirectTo 42892 }); 42893 return this._returnResult({ data: { user: null, session: null }, error: h }); 42894 } 42895 if ("phone" in e) { 42896 const { phone: l, options: o } = e, { data: c, error: u } = await He(this.fetch, "POST", `${this.url}/otp`, { 42897 headers: this.headers, 42898 body: { 42899 phone: l, 42900 data: (r = o?.data) !== null && r !== void 0 ? r : {}, 42901 create_user: (s = o?.shouldCreateUser) !== null && s !== void 0 ? s : !0, 42902 gotrue_meta_security: { captcha_token: o?.captchaToken }, 42903 channel: (a = o?.channel) !== null && a !== void 0 ? a : "sms" 42904 } 42905 }); 42906 return this._returnResult({ 42907 data: { user: null, session: null, messageId: c?.message_id }, 42908 error: u 42909 }); 42910 } 42911 throw new lo("You must provide either an email or phone number."); 42912 } catch (l) { 42913 if (await $t(this.storage, `${this.storageKey}-code-verifier`), Re(l)) 42914 return this._returnResult({ data: { user: null, session: null }, error: l }); 42915 throw l; 42916 } 42917 } 42918 /** 42919 * Log in a user given a User supplied OTP or TokenHash received through mobile or email. 42920 * 42921 * @category Auth 42922 * 42923 * @remarks 42924 * - The `verifyOtp` method takes in different verification types. 42925 * - If a phone number is used, the type can either be: 42926 * 1. `sms` â Used when verifying a one-time password (OTP) sent via SMS during sign-up or sign-in. 42927 * 2. `phone_change` â Used when verifying an OTP sent to a new phone number during a phone number update process. 42928 * - If an email address is used, the type can be one of the following (note: `signup` and `magiclink` types are deprecated): 42929 * 1. `email` â Used when verifying an OTP sent to the user's email during sign-up or sign-in. 42930 * 2. `recovery` â Used when verifying an OTP sent for account recovery, typically after a password reset request. 42931 * 3. `invite` â Used when verifying an OTP sent as part of an invitation to join a project or organization. 42932 * 4. `email_change` â Used when verifying an OTP sent to a new email address during an email update process. 42933 * - The verification type used should be determined based on the corresponding auth method called before `verifyOtp` to sign up / sign-in a user. 42934 * - The `TokenHash` is contained in the [email templates](/docs/guides/auth/auth-email-templates) and can be used to sign in. You may wish to use the hash for the PKCE flow for Server Side Auth. Read [the Password-based Auth guide](/docs/guides/auth/passwords) for more details. 42935 * 42936 * @example Verify Signup One-Time Password (OTP) 42937 * ```js 42938 * const { data, error } = await supabase.auth.verifyOtp({ email, token, type: 'email'}) 42939 * ``` 42940 * 42941 * @exampleResponse Verify Signup One-Time Password (OTP) 42942 * ```json 42943 * { 42944 * "data": { 42945 * "user": { 42946 * "id": "11111111-1111-1111-1111-111111111111", 42947 * "aud": "authenticated", 42948 * "role": "authenticated", 42949 * "email": "[email protected]", 42950 * "email_confirmed_at": "2024-01-01T00:00:00Z", 42951 * "phone": "", 42952 * "confirmed_at": "2024-01-01T00:00:00Z", 42953 * "recovery_sent_at": "2024-01-01T00:00:00Z", 42954 * "last_sign_in_at": "2024-01-01T00:00:00Z", 42955 * "app_metadata": { 42956 * "provider": "email", 42957 * "providers": [ 42958 * "email" 42959 * ] 42960 * }, 42961 * "user_metadata": { 42962 * "email": "[email protected]", 42963 * "email_verified": false, 42964 * "phone_verified": false, 42965 * "sub": "11111111-1111-1111-1111-111111111111" 42966 * }, 42967 * "identities": [ 42968 * { 42969 * "identity_id": "22222222-2222-2222-2222-222222222222", 42970 * "id": "11111111-1111-1111-1111-111111111111", 42971 * "user_id": "11111111-1111-1111-1111-111111111111", 42972 * "identity_data": { 42973 * "email": "[email protected]", 42974 * "email_verified": false, 42975 * "phone_verified": false, 42976 * "sub": "11111111-1111-1111-1111-111111111111" 42977 * }, 42978 * "provider": "email", 42979 * "last_sign_in_at": "2024-01-01T00:00:00Z", 42980 * "created_at": "2024-01-01T00:00:00Z", 42981 * "updated_at": "2024-01-01T00:00:00Z", 42982 * "email": "[email protected]" 42983 * } 42984 * ], 42985 * "created_at": "2024-01-01T00:00:00Z", 42986 * "updated_at": "2024-01-01T00:00:00Z", 42987 * "is_anonymous": false 42988 * }, 42989 * "session": { 42990 * "access_token": "<ACCESS_TOKEN>", 42991 * "token_type": "bearer", 42992 * "expires_in": 3600, 42993 * "expires_at": 1700000000, 42994 * "refresh_token": "<REFRESH_TOKEN>", 42995 * "user": { 42996 * "id": "11111111-1111-1111-1111-111111111111", 42997 * "aud": "authenticated", 42998 * "role": "authenticated", 42999 * "email": "[email protected]", 43000 * "email_confirmed_at": "2024-01-01T00:00:00Z", 43001 * "phone": "", 43002 * "confirmed_at": "2024-01-01T00:00:00Z", 43003 * "recovery_sent_at": "2024-01-01T00:00:00Z", 43004 * "last_sign_in_at": "2024-01-01T00:00:00Z", 43005 * "app_metadata": { 43006 * "provider": "email", 43007 * "providers": [ 43008 * "email" 43009 * ] 43010 * }, 43011 * "user_metadata": { 43012 * "email": "[email protected]", 43013 * "email_verified": false, 43014 * "phone_verified": false, 43015 * "sub": "11111111-1111-1111-1111-111111111111" 43016 * }, 43017 * "identities": [ 43018 * { 43019 * "identity_id": "22222222-2222-2222-2222-222222222222", 43020 * "id": "11111111-1111-1111-1111-111111111111", 43021 * "user_id": "11111111-1111-1111-1111-111111111111", 43022 * "identity_data": { 43023 * "email": "[email protected]", 43024 * "email_verified": false, 43025 * "phone_verified": false, 43026 * "sub": "11111111-1111-1111-1111-111111111111" 43027 * }, 43028 * "provider": "email", 43029 * "last_sign_in_at": "2024-01-01T00:00:00Z", 43030 * "created_at": "2024-01-01T00:00:00Z", 43031 * "updated_at": "2024-01-01T00:00:00Z", 43032 * "email": "[email protected]" 43033 * } 43034 * ], 43035 * "created_at": "2024-01-01T00:00:00Z", 43036 * "updated_at": "2024-01-01T00:00:00Z", 43037 * "is_anonymous": false 43038 * } 43039 * } 43040 * }, 43041 * "error": null 43042 * } 43043 * ``` 43044 * 43045 * @example Verify SMS One-Time Password (OTP) 43046 * ```js 43047 * const { data, error } = await supabase.auth.verifyOtp({ phone, token, type: 'sms'}) 43048 * ``` 43049 * 43050 * @example Verify Email Auth (Token Hash) 43051 * ```js 43052 * const { data, error } = await supabase.auth.verifyOtp({ token_hash: tokenHash, type: 'email'}) 43053 * ``` 43054 */ 43055 async verifyOtp(e) { 43056 var t, i; 43057 try { 43058 let r, s; 43059 "options" in e && (r = (t = e.options) === null || t === void 0 ? void 0 : t.redirectTo, s = (i = e.options) === null || i === void 0 ? void 0 : i.captchaToken); 43060 const { data: a, error: l } = await He(this.fetch, "POST", `${this.url}/verify`, { 43061 headers: this.headers, 43062 body: Object.assign(Object.assign({}
43062, e), { gotrue_meta_security: { captcha_token: s } }), 43063 redirectTo: r, 43064 xform: Bn 43065 }); 43066 if (l) 43067 throw l; 43068 if (!a) 43069 throw new Error("An error occurred on token verification."); 43070 const o = a.session, c = a.user; 43071 return o?.access_token && (await this._saveSession(o), await this._notifyAllSubscribers(e.type == "recovery" ? "PASSWORD_RECOVERY" : "SIGNED_IN", o)), this._returnResult({ data: { user: c, session: o }, error: null }); 43072 } catch (r) { 43073 if (Re(r)) 43074 return this._returnResult({ data: { user: null, session: null }, error: r }); 43075 throw r; 43076 } 43077 } 43078 /** 43079 * Attempts a single-sign on using an enterprise Identity Provider. A 43080 * successful SSO attempt will redirect the current page to the identity 43081 * provider authorization page. The redirect URL is implementation and SSO 43082 * protocol specific. 43083 * 43084 * You can use it by providing a SSO domain. Typically you can extract this 43085 * domain by asking users for their email address. If this domain is 43086 * registered on the Auth instance the redirect will use that organization's 43087 * currently active SSO Identity Provider for the login. 43088 * 43089 * If you have built an organization-specific login page, you can use the 43090 * organization's SSO Identity Provider UUID directly instead. 43091 * 43092 * @category Auth 43093 * 43094 * @remarks 43095 * - Before you can call this method you need to [establish a connection](/docs/guides/auth/sso/auth-sso-saml#managing-saml-20-connections) to an identity provider. Use the [CLI commands](/docs/reference/cli/supabase-sso) to do this. 43096 * - If you've associated an email domain to the identity provider, you can use the `domain` property to start a sign-in flow. 43097 * - In case you need to use a different way to start the authentication flow with an identity provider, you can use the `providerId` property. For example: 43098 * - Mapping specific user email addresses with an identity provider. 43099 * - Using different hints to identity the identity provider to be used by the user, like a company-specific page, IP address or other tracking information. 43100 * 43101 * @example Sign in with email domain 43102 * ```js 43103 * // You can extract the user's email domain and use it to trigger the 43104 * // authentication flow with the correct identity provider. 43105 * 43106 * const { data, error } = await supabase.auth.signInWithSSO({ 43107 * domain: 'company.com' 43108 * }) 43109 * 43110 * if (data?.url) { 43111 * // redirect the user to the identity provider's authentication flow 43112 * window.location.href = data.url 43113 * } 43114 * ``` 43115 * 43116 * @example Sign in with provider UUID 43117 * ```js 43118 * // Useful when you need to map a user's sign in request according 43119 * // to different rules that can't use email domains. 43120 * 43121 * const { data, error } = await supabase.auth.signInWithSSO({ 43122 * providerId: '21648a9d-8d5a-4555-a9d1-d6375dc14e92' 43123 * }) 43124 * 43125 * if (data?.url) { 43126 * // redirect the user to the identity provider's authentication flow 43127 * window.location.href = data.url 43128 * } 43129 * ``` 43130 */ 43131 async signInWithSSO(e) { 43132 var t, i, r, s, a; 43133 try { 43134 let l = null, o = null; 43135 this.flowType === "pkce" && ([l, o] = await _r(this.storage, this.storageKey)); 43136 const c = await He(this.fetch, "POST", `${this.url}/sso`, { 43137 body: Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({}, "providerId" in e ? { provider_id: e.providerId } : null), "domain" in e ? { domain: e.domain } : null), { redirect_to: (i = (t = e.options) === null || t === void 0 ? void 0 : t.redirectTo) !== null && i !== void 0 ? i : void 0 }), !((r = e?.options) === null || r === void 0) && r.captchaToken ? { gotrue_meta_security: { captcha_token: e.options.captchaToken } } : null), { skip_http_redirect: !0, code_challenge: l, code_challenge_method: o }), 43138 headers: this.headers, 43139 xform: v1 43140 }); 43141 return !((s = c.data) === null || s === void 0) && s.url && hn() && !(!((a = e.options) === null || a === void 0) && a.skipBrowserRedirect) && window.location.assign(c.data.url), this._returnResult(c); 43142 } catch (l) { 43143 if (await $t(this.storage, `${this.storageKey}-code-verifier`), Re(l)) 43144 return this._returnResult({ data: null, error: l }); 43145 throw l; 43146 } 43147 } 43148 /** 43149 * Sends a reauthentication OTP to the user's email or phone number. 43150 * Requires the user to be signed-in. 43151 * 43152 * @category Auth 43153 * 43154 * @remarks 43155 * - This method is used together with `updateUser()` when a user's password needs to be updated. 43156 * - If you require your user to reauthenticate before updating their password, you need to enable the **Secure password change** option in your [project's email provider settings](/dashboard/project/_/auth/providers). 43157 * - A user is only require to reauthenticate before updating their password if **Secure password change** is enabled and the user **hasn't recently signed in**. A user is deemed recently signed in if the session was created in the last 24 hours. 43158 * - This method will send a nonce to the user's email. If the user doesn't have a confirmed email address, the method will send the nonce to the user's confirmed phone number instead. 43159 * - After receiving the OTP, include it as the `nonce` in your `updateUser()` call to finalize the password change. 43160 * 43161 * @exampleDescription Send reauthentication nonce 43162 * Sends a reauthentication nonce to the user's email or phone number. 43163 * 43164 * @example Send reauthentication nonce 43165 * ```js 43166 * const { error } = await supabase.auth.reauthenticate() 43167 * ``` 43168 */ 43169 async reauthenticate() { 43170 return await this.initializePromise, this.lock != null ? await this._acquireLock(this.lockAcquireTimeout, async () => await this._reauthenticate()) : await this._reauthenticate(); 43171 } 43172 async _reauthenticate() { 43173 try { 43174 return await this._useSession(async (e) => { 43175 const { data: { session: t }, error: i } = e; 43176 if (i) 43177 throw i; 43178 if (!t) 43179 throw new nn(); 43180 const { error: r }
43180 = await He(this.fetch, "GET", `${this.url}/reauthenticate`, { 43181 headers: this.headers, 43182 jwt: t.access_token 43183 }); 43184 return this._returnResult({ data: { user: null, session: null }, error: r }); 43185 }); 43186 } catch (e) { 43187 if (Re(e)) 43188 return this._returnResult({ data: { user: null, session: null }, error: e }); 43189 throw e; 43190 } 43191 } 43192 /** 43193 * Resends an existing signup confirmation email, email change email, SMS OTP or phone change OTP. 43194 * 43195 * @category Auth 43196 * 43197 * @remarks 43198 * - Resends a signup confirmation, email change or phone change email to the user. 43199 * - Passwordless sign-ins can be resent by calling the `signInWithOtp()` method again. 43200 * - Password recovery emails can be resent by calling the `resetPasswordForEmail()` method again. 43201 * - This method will only resend an email or phone OTP to the user if there was an initial signup, email change or phone change request being made(note: For existing users signing in with OTP, you should use `signInWithOtp()` again to resend the OTP). 43202 * - You can specify a redirect url when you resend an email link using the `emailRedirectTo` option. 43203 * 43204 * @exampleDescription Resend an email signup confirmation 43205 * Resends the email signup confirmation to the user 43206 * 43207 * @example Resend an email signup confirmation 43208 * ```js 43209 * const { error } = await supabase.auth.resend({ 43210 * type: 'signup', 43211 * email: '[email protected]', 43212 * options: { 43213 * emailRedirectTo: 'https://example.com/welcome' 43214 * } 43215 * }) 43216 * ``` 43217 * 43218 * @exampleDescription Resend a phone signup confirmation 43219 * Resends the phone signup confirmation email to the user 43220 * 43221 * @example Resend a phone signup confirmation 43222 * ```js 43223 * const { error } = await supabase.auth.resend({ 43224 * type: 'sms', 43225 * phone: '1234567890' 43226 * }) 43227 * ``` 43228 * 43229 * @exampleDescription Resend email change email 43230 * Resends the email change email to the user 43231 * 43232 * @example Resend email change email 43233 * ```js 43234 * const { error } = await supabase.auth.resend({ 43235 * type: 'email_change', 43236 * email: '[email protected]' 43237 * }) 43238 * ``` 43239 * 43240 * @exampleDescription Resend phone change OTP 43241 * Resends the phone change OTP to the user 43242 * 43243 * @example Resend phone change OTP 43244 * ```js 43245 * const { error } = await supabase.auth.resend({ 43246 * type: 'phone_change', 43247 * phone: '1234567890' 43248 * }) 43249 * ``` 43250 */ 43251 async resend(e) { 43252 try { 43253 const t = `${this.url}/resend`; 43254 if ("email" in e) { 43255 const { email: i, type: r, options: s } = e; 43256 let a = null, l = null; 43257 this.flowType === "pkce" && ([a, l] = await _r(this.storage, this.storageKey)); 43258 const { error: o } = await He(this.fetch, "POST", t, { 43259 headers: this.headers, 43260 body: { 43261 email: i, 43262 type: r, 43263 gotrue_meta_security: { captcha_token: s?.captchaToken }, 43264 code_challenge: a, 43265 code_challenge_method: l 43266 }, 43267 redirectTo: s?.emailRedirectTo 43268 }); 43269 return o && await $t(this.storage, `${this.storageKey}-code-verifier`), this._returnResult({ data: { user: null, session: null }, error: o }); 43270 } else if ("phone" in e) { 43271 const { phone: i, type: r, options: s } = e, { data: a, error: l } = await He(this.fetch, "POST", t, { 43272 headers: this.headers, 43273 body: { 43274 phone: i, 43275 type: r, 43276 gotrue_meta_security: { captcha_token: s?.captchaToken } 43277 } 43278 }); 43279 return this._returnResult({ 43280 data: { user: null, session: null, messageId: a?.message_id }, 43281 error: l 43282 }); 43283 } 43284 throw new lo("You must provide either an email or phone number and a type"); 43285 } catch (t) { 43286 if (await $t(this.storage, `${this.storageKey}-code-verifier`), Re(t)) 43287 return this._returnResult({ data: { user: null, session: null }, error: t }); 43288 throw t; 43289 } 43290 } 43291 /** 43292 * Returns the session, refreshing it if necessary. 43293 * 43294 * The session returned can be null if the session is not detected which can happen in the event a user is not signed-in or has logged out. 43295 * 43296 * **IMPORTANT:** This method loads values directly from the storage attached 43297 * to the client. If that storage is based on request cookies for example, 43298 * the values in it may not be authentic and therefore it's strongly advised 43299 * against using this method and its results in such circumstances. A warning 43300 * will be emitted if this is detected. Use {@link #getUser()} instead. 43301 * 43302 * @category Auth 43303 * 43304 * @remarks 43305 * - Since the introduction of [asymmetric JWT signing keys](/docs/guides/auth/signing-keys), this method is considered low-level and we encourage you to use `getClaims()` or `getUser()` instead. 43306 * - Retrieves the current [user session](/docs/guides/auth/sessions) from the storage medium (local storage, cookies). 43307 * - The session contains an access token (signed JWT), a refresh token and the user object. 43308 * - If the session's access token is expired or is about to expire, this method will use the refresh token to refresh the session. 43309 * - When using in a browser, or you've called `startAutoRefresh()` in your environment (React Native, etc.) this function always returns a valid access token without refreshing the session itself, as this is done in the background. This function returns very fast. 43310 * - **IMPORTANT SECURITY NOTICE:** If using an insecure storage medium, such as cookies or request headers, the user object returned by this function **must not be trusted**. Always verify the JWT using `getClaims()` or your own JWT verification library to securely establish the user's identity and access. You can also use `getUser()` to fetch the user object directly from the Auth server for this purpose. 43311 * - Cross-tab refresh races are handled by the GoTrue server (the rotated token from the first tab is returned to subsequent tabs via the parent-of-active mechanism), so no client-side serialization is needed. 43312 * 43313 * @example Get the session data 43314 * ```js 43315 * const { data, error } = await supabase.auth.getSession() 43316 * ``` 43317 * 43318 * @exampleResponse Get the session data 43319 * ```json 43320 * { 43321 * "data": { 43322 * "session": { 43323 * "access_token": "<ACCESS_TOKEN>", 43324 * "token_type": "bearer", 43325 * "expires_in": 3600, 43326 * "expires_at": 1700000000, 43327 * "refresh_token": "<REFRESH_TOKEN>", 43328 * "user": { 43329 * "id": "11111111-1111-1111-1111-111111111111", 43330 * "aud": "authenticated", 43331 * "role": "authenticated", 43332 * "email": "[email protected]", 43333 * "email_confirmed_at": "2024-01-01T00:00:00Z", 43334 * "phone": "", 43335 * "last_sign_in_at": "2024-01-01T00:00:00Z", 43336 * "app_metadata": { 43337 * "provider": "email", 43338 * "providers": [ 43339 * "email" 43340 * ] 43341 * }, 43342 * "user_metadata": { 43343 * "email": "[email protected]", 43344 * "email_verified": false, 43345 * "phone_verified": false, 43346 * "sub": "11111111-1111-1111-1111-111111111111" 43347 * }, 43348 * "identities": [ 43349 * { 43350 * "identity_id": "22222222-2222-2222-2222-222222222222", 43351 * "id": "11111111-1111-1111-1111-111111111111", 43352 * "user_id": "11111111-1111-1111-1111-111111111111", 43353 * "identity_data": { 43354 * "email": "[email protected]", 43355 * "email_verified": false, 43356 * "phone_verified": false, 43357 * "sub": "11111111-1111-1111-1111-111111111111" 43358 * }, 43359 * "provider": "email", 43360 * "last_sign_in_at": "2024-01-01T00:00:00Z", 43361 * "created_at": "2024-01-01T00:00:00Z", 43362 * "updated_at": "2024-01-01T00:00:00Z", 43363 * "email": "[email protected]" 43364 * } 43365 * ], 43366 * "created_at": "2024-01-01T00:00:00Z", 43367 * "updated_at": "2024-01-01T00:00:00Z", 43368 * "is_anonymous": false 43369 * } 43370 * } 43371 * }, 43372 * "error": null 43373 * } 43374 * ``` 43375 */ 43376 async getSession() { 43377 return await this.initializePromise, this.lock != null ? await this._acquireLock(this.lockAcquireTimeout, async () => this._useSession(async (e) => e)) : await this._useSession(async (e) => e); 43378 } 43379 /** 43380 * Acquires a global lock based on the storage key. 43381 * 43382 * TODO(v3): remove along with the legacy lock path. Only called when 43383 * `this.lock` is non-null (custom lock supplied via constructor). The 43384 * default lockless path bypasses this entirely. 43385 */ 43386 async _acquireLock(e, t) { 43387 this._debug("#_acquireLock", "begin", e); 43388 try { 43389 if (this.lockAcquired) { 43390 const i = this.pendingInLock.length ? this.pendingInLock[this.pendingInLock.length - 1] : Promise.resolve(), r = (async () => (await i, await t()))(); 43391 return this.pendingInLock.push((async () => { 43392 try { 43393 await r; 43394 } catch { 43395 } 43396 })()), r; 43397 } 43398 return await this.lock(`lock:${this.storageKey}`, e, async () => { 43399 this._debug("#_acquireLock", "lock acquired for storage key", this.storageKey); 43400 try { 43401 this.lockAcquired = !0; 43402 const i = t(); 43403 for (this.pendingInLock.push((async () => { 43404 try { 43405 await i; 43406 } catch { 43407 } 43408 })()), await i; this.pendingInLock.length; ) { 43409 const r = [...this.pendingInLock]; 43410 await Promise.all(r), this.pendingInLock.splice(0, r.length); 43411 } 43412 return await i; 43413 } finally { 43414 this._debug("#_acquireLock", "lock released for storage key", this.storageKey), this.lockAcquired = !1; 43415 } 43416 }); 43417 } finally { 43418 this._debug("#_acquireLock", "end"); 43419 } 43420 } 43421 /** 43422 * Use instead of {@link #getSession} inside the library. Loads the session 43423 * via `__loadSession` (which may trigger a refresh if the access token is 43424 * within the expiry margin) and runs `fn` with the result. 43425 */ 43426 async _useSession(e) { 43427 this._debug("#_useSession", "begin"); 43428 try { 43429 const t = await this.__loadSession(); 43430 return await e(t); 43431 } finally { 43432 this._debug("#_useSession", "end"); 43433 } 43434 } 43435 /** 43436 * NEVER USE DIRECTLY! 43437 * 43438 * Always use {@link #_useSession}. 43439 */ 43440 async __loadSession() { 43441 this._debug("#__loadSession()", "begin"), this.lock != null && !this.lockAcquired && this._debug("#__loadSession()", "used outside of an acquired lock!", new Error().stack); 43442 try { 43443 let e = null; 43444 const t = await Ai(this.storage, this.storageKey); 43445 if (this._debug("#getSession()", "session from storage", t), t !== null && (this._isValidSession(t) ? e = t : (this._debug("#getSession()", "session from storage is not val
43445id"), await this._removeSession())), !e) 43446 return { data: { session: null }, error: null }; 43447 const i = e.expires_at ? e.expires_at * 1e3 - Date.now() < jl : !1; 43448 if (this._debug("#__loadSession()", `session has${i ? "" : " not"} expired`, "expires_at", e.expires_at), !i) { 43449 if (this.userStorage) { 43450 const a = await Ai(this.userStorage, this.storageKey + "-user"); 43451 a?.user ? e.user = a.user : e.user = ql(); 43452 } 43453 if (this.storage.isServer && e.user && !e.user.__isUserNotAvailableProxy) { 43454 const a = { value: this.suppressGetSessionWarning }; 43455 e.user = f1(e.user, a), a.value && (this.suppressGetSessionWarning = !0); 43456 } 43457 return { data: { session: e }, error: null }; 43458 } 43459 const { data: r, error: s } = await this._callRefreshToken(e.refresh_token); 43460 return s ? this._returnResult({ data: { session: null }, error: s }) : this._returnResult({ data: { session: r }, error: null }); 43461 } finally { 43462 this._debug("#__loadSession()", "end"); 43463 } 43464 } 43465 /** 43466 * Gets the current user details if there is an existing session. This method 43467 * performs a network request to the Supabase Auth server, so the returned 43468 * value is authentic and can be used to base authorization rules on. 43469 * 43470 * @param jwt Takes in an optional access token JWT. If no JWT is provided, the JWT from the current session is used. 43471 * 43472 * @category Auth 43473 * 43474 * @remarks 43475 * - This method fetches the user object from the database instead of local session. 43476 * - This method is useful for checking if the user is authorized because it validates the user's access token JWT on the server. 43477 * - Should always be used when checking for user authorization on the server. On the client, you can instead use `getSession().session.user` for faster results. `getSession` is insecure on the server. 43478 * 43479 * @example Get the logged in user with the current existing session 43480 * ```js 43481 * const { data: { user } } = await supabase.auth.getUser() 43482 * ``` 43483 * 43484 * @exampleResponse Get the logged in user with the current existing session 43485 * ```json 43486 * { 43487 * "data": { 43488 * "user": { 43489 * "id": "11111111-1111-1111-1111-111111111111", 43490 * "aud": "authenticated", 43491 * "role": "authenticated", 43492 * "email": "[email protected]", 43493 * "email_confirmed_at": "2024-01-01T00:00:00Z", 43494 * "phone": "", 43495 * "confirmed_at": "2024-01-01T00:00:00Z", 43496 * "last_sign_in_at": "2024-01-01T00:00:00Z", 43497 * "app_metadata": { 43498 * "provider": "email", 43499 * "providers": [ 43500 * "email" 43501 * ] 43502 * }, 43503 * "user_metadata": { 43504 * "email": "[email protected]", 43505 * "email_verified": false, 43506 * "phone_verified": false, 43507 * "sub": "11111111-1111-1111-1111-111111111111" 43508 * }, 43509 * "identities": [ 43510 * { 43511 * "identity_id": "22222222-2222-2222-2222-222222222222", 43512 * "id": "11111111-1111-1111-1111-111111111111", 43513 * "user_id": "11111111-1111-1111-1111-111111111111", 43514 * "identity_data": { 43515 * "email": "[email protected]", 43516 * "email_verified": false, 43517 * "phone_verified": false, 43518 * "sub": "11111111-1111-1111-1111-111111111111" 43519 * }, 43520 * "provider": "email", 43521 * "last_sign_in_at": "2024-01-01T00:00:00Z", 43522 * "created_at": "2024-01-01T00:00:00Z", 43523 * "updated_at": "2024-01-01T00:00:00Z", 43524 * "email": "[email protected]" 43525 * } 43526 * ], 43527 * "created_at": "2024-01-01T00:00:00Z", 43528 * "updated_at": "2024-01-01T00:00:00Z", 43529 * "is_anonymous": false 43530 * } 43531 * }, 43532 * "error": null 43533 * } 43534 * ``` 43535 * 43536 * @example Get the logged in user with a custom access token jwt 43537 * ```js 43538 * const { data: { user } } = await supabase.auth.getUser(jwt) 43539 * ``` 43540 */ 43541 async getUser(e) { 43542 if (e) 43543 return await this._getUser(e); 43544 await this.initializePromise; 43545 let t; 43546 return this.lock != null ? t = await this._acquireLock(this.lockAcquireTimeout, async () => await this._getUser()) : t = await this._getUser(), t.data.user && (this.suppressGetSessionWarning = !0), t; 43547 } 43548 async _getUser(e) { 43549 try { 43550 return e ? await He(this.fetch, "GET", `${this.url}/user`, { 43551 headers: this.headers, 43552 jwt: e, 43553 xform: Qi 43554 }) : await this._useSession(async (t) => { 43555 var i, r, s; 43556 const { data: a, error: l } = t; 43557 if (l) 43558 throw l; 43559 return !(!((i = a.session) === null || i === void 0) && i.access_token) && !this.hasCustomAuthorizationHeader ? { data: { user: null }, error: new nn() } : await He(this.fetch, "GET", `${this.url}/user`, { 43560 headers: this.headers, 43561 jwt: (s = (r = a.session) === null || r === void 0 ? void 0 : r.access_token) !== null && s !== void 0 ? s : void 0, 43562 xform: Qi 43563 }); 43564 }); 43565 } catch (t) { 43566 if (Re(t)) 43567 return oo(t) && (await this._removeSession(), await $t(this.storage, `${this.storageKey}-code-verifier`)), this._returnResult({ data: { user: null }, error: t }); 43568 throw t; 43569 } 43570 } 43571 /** 43572 * Updates user data for a logged in user. 43573 * 43574 * @category Auth 43575 * 43576 * @remarks 43577 * - In order to use the `updateUser()` method, the user needs to be signed in first. 43578 * - By default, email updates sends a confirmation link to both the user's current and new email. 43579 * To only send a confirmation link to the user's new email, disable **Secure email change** in your project's [email auth provider settings](/dashboard/project/_/auth/providers). 43580 * 43581 * @exampleDescription Update the email for an authenticated user 43582 * Sends a "Confirm Email Change" email to the new address. If **Secure Email Change** is enabled (default), confirmation is also required from the **old email** before the change is applied. To skip dual confirmation and apply the change after only the new email is verified, disable **Secure Email Change** in the [Email Auth Provider settings](/dashboard/project/_/auth/providers?provider=Email). 43583 * 43584 * @example Update the email for an authenticated user 43585 * ```js 43586 * const { data, error } = await supabase.auth.updateUser({ 43587 * email: '[email protected]' 43588 * }) 43589 * ``` 43590 * 43591 * @exampleResponse Update the email for an authenticated user 43592 * ```json 43593 * { 43594 * "data": { 43595 * "user": { 43596 * "id": "11111111-1111-1111-1111-111111111111", 43597 * "aud": "authenticated", 43598 * "role": "authenticated", 43599 * "email": "[email protected]", 43600 * "email_confirmed_at": "2024-01-01T00:00:00Z", 43601 * "phone": "", 43602 * "confirmed_at": "2024-01-01T00:00:00Z", 43603 * "new_email": "[email protected]", 43604 * "email_change_sent_at": "2024-01-01T00:00:00Z", 43605 * "last_sign_in_at": "2024-01-01T00:00:00Z", 43606 * "app_metadata": { 43607 * "provider": "email", 43608 * "providers": [ 43609 * "email" 43610 * ] 43611 * }, 43612 * "user_metadata": { 43613 * "email": "[email protected]", 43614 * "email_verified": false, 43615 * "phone_verified": false, 43616 * "sub": "11111111-1111-1111-1111-111111111111" 43617 * }, 43618 * "identities": [ 43619 * { 43620 * "identity_id": "22222222-2222-2222-2222-222222222222", 43621 * "id": "11111111-1111-1111-1111-111111111111", 43622 * "user_id": "11111111-1111-1111-1111-111111111111", 43623 * "identity_data": { 43624 * "email": "[email protected]", 43625 * "email_verified": false, 43626 * "phone_verified": false, 43627 * "sub": "11111111-1111-1111-1111-111111111111" 43628 * }, 43629 * "provider": "email", 43630 * "last_sign_in_at": "2024-01-01T00:00:00Z", 43631 * "created_at": "2024-01-01T00:00:00Z", 43632 * "updated_at": "2024-01-01T00:00:00Z", 43633 * "email": "[email protected]" 43634 * } 43635 * ], 43636 * "created_at": "2024-01-01T00:00:00Z", 43637 * "updated_at": "2024-01-01T00:00:00Z", 43638 * "is_anonymous": false 43639 * } 43640 * }, 43641 * "error": null 43642 * } 43643 * ``` 43644 * 43645 * @exampleDescription Update the phone number for an authenticated user 43646 * Sends a one-time password (OTP) to the new phone number. 43647 * 43648 * @example Update the phone number for an authenticated user 43649 * ```js 43650 * const { data, error } = await supabase.auth.updateUser({ 43651 * phone: '123456789' 43652 * }) 43653 * ``` 43654 * 43655 * @example Update the password for an authenticated user 43656 * ```js 43657 * const { data, error } = await supabase.auth.updateUser({ 43658 * password: 'new password' 43659 * }) 43660 * ``` 43661 * 43662 * @exampleDescription Update the user's metadata 43663 * Updates the user's custom metadata. 43664 * 43665 * **Note**: The `data` field maps to the `auth.users.raw_user_meta_data` column in your Supabase database. When calling `getUser()`, the data will be available as `user.user_metadata`. 43666 * 43667 * @example Update the user's metadata 43668 * ```js 43669 * const { data, error } = await supabase.auth.updateUser({ 43670 * data: { hello: 'world' } 43671 * }) 43672 * ``` 43673 * 43674 * @exampleDescription Update the user's password with a nonce 43675 * If **Secure password change** is enabled in your [project's email provider settings](/dashboard/project/_/auth/providers), updating the user's password would require a nonce if the user **hasn't recently signed in**. The nonce is sent to the user's email or phone number. A user is deemed recently signed in if the session was created in the last 24 hours. 43676 * 43677 * @example Update the user's password with a nonce 43678 * ```js 43679 * const { data, error } = await supabase.auth.updateUser({ 43680 * password: 'new password', 43681 * nonce: '123456' 43682 * }) 43683 * ``` 43684 */ 43685 async updateUser(e, t = {}) { 43686 return await this.initializePromise, this.lock != null ? await this._acquireLock(this.lockAcquireTimeout, async () => await this._updateUser(e, t)) : await this._updateUser(e, t); 43687 } 43688 async _updateUser(e, t = {}) { 43689 try { 43690 return await this._useSession(async (i) => { 43691 const { data: r, error: s } = i; 43692 if (s) 43693 throw s; 43694 if (!r.session) 43695 throw new nn(); 43696 const a = r.session; 43697 let l = null, o = null; 43698 this.flowType === "pkce" && e.email != null && ([l, o] = await _r(this.storage, this.storageKey)); 43699 const { data: c, error: u } = await He(this.fetch, "PUT", `${this.url}/user`, { 43700 headers: this.headers, 43701 redirectTo: t?.emailRedirectTo, 43702 body: Object.assign(Object.assign({}, e), { code_challenge: l, code_challenge_method: o }), 43703 jwt: a.access_token, 43704 xform: Qi 43705 }); 43706 if (u) 43707 throw u; 43708 return a.user = c.user, await this._saveSession(a), await this._notifyAllSubscribers("USER_UPDATED", a), this._returnResult({ data: { user: a.user }, error: null }); 43709 }); 43710 } catch (i) { 43711 if (await $t(this.storage, `${this.storageKey}-code-verifier`), Re(i)) 43712 return this._returnResult({ data: { user: null }, error: i }); 43713 throw i; 43714 } 43715 } 43716 /** 43717 * Sets the session data from the current session. If the current session is expired, setSession will take care of refreshing it to obtain a new session. 43718 * If the refresh token or access token in the current session is invali
43718d, an error will be thrown. 43719 * @param currentSession The current session that minimally contains an access token and refresh token. 43720 * 43721 * @category Auth 43722 * 43723 * @remarks 43724 * - This method sets the session using an `access_token` and `refresh_token`. 43725 * - If successful, a `SIGNED_IN` event is emitted. 43726 * 43727 * @exampleDescription Set the session 43728 * Sets the session data from an access_token and refresh_token, then returns an auth response or error. 43729 * 43730 * @example Set the session 43731 * ```js 43732 * const { data, error } = await supabase.auth.setSession({ 43733 * access_token, 43734 * refresh_token 43735 * }) 43736 * ``` 43737 * 43738 * @exampleResponse Set the session 43739 * ```json 43740 * { 43741 * "data": { 43742 * "user": { 43743 * "id": "11111111-1111-1111-1111-111111111111", 43744 * "aud": "authenticated", 43745 * "role": "authenticated", 43746 * "email": "[email protected]", 43747 * "email_confirmed_at": "2024-01-01T00:00:00Z", 43748 * "phone": "", 43749 * "confirmed_at": "2024-01-01T00:00:00Z", 43750 * "last_sign_in_at": "2024-01-01T00:00:00Z", 43751 * "app_metadata": { 43752 * "provider": "email", 43753 * "providers": [ 43754 * "email" 43755 * ] 43756 * }, 43757 * "user_metadata": { 43758 * "email": "[email protected]", 43759 * "email_verified": false, 43760 * "phone_verified": false, 43761 * "sub": "11111111-1111-1111-1111-111111111111" 43762 * }, 43763 * "identities": [ 43764 * { 43765 * "identity_id": "22222222-2222-2222-2222-222222222222", 43766 * "id": "11111111-1111-1111-1111-111111111111", 43767 * "user_id": "11111111-1111-1111-1111-111111111111", 43768 * "identity_data": { 43769 * "email": "[email protected]", 43770 * "email_verified": false, 43771 * "phone_verified": false, 43772 * "sub": "11111111-1111-1111-1111-111111111111" 43773 * }, 43774 * "provider": "email", 43775 * "last_sign_in_at": "2024-01-01T00:00:00Z", 43776 * "created_at": "2024-01-01T00:00:00Z", 43777 * "updated_at": "2024-01-01T00:00:00Z", 43778 * "email": "[email protected]" 43779 * } 43780 * ], 43781 * "created_at": "2024-01-01T00:00:00Z", 43782 * "updated_at": "2024-01-01T00:00:00Z", 43783 * "is_anonymous": false 43784 * }, 43785 * "session": { 43786 * "access_token": "<ACCESS_TOKEN>", 43787 * "refresh_token": "<REFRESH_TOKEN>", 43788 * "user": { 43789 * "id": "11111111-1111-1111-1111-111111111111", 43790 * "aud": "authenticated", 43791 * "role": "authenticated", 43792 * "email": "[email protected]", 43793 * "email_confirmed_at": "2024-01-01T00:00:00Z", 43794 * "phone": "", 43795 * "confirmed_at": "2024-01-01T00:00:00Z", 43796 * "last_sign_in_at": "11111111-1111-1111-1111-111111111111", 43797 * "app_metadata": { 43798 * "provider": "email", 43799 * "providers": [ 43800 * "email" 43801 * ] 43802 * }, 43803 * "user_metadata": { 43804 * "email": "[email protected]", 43805 * "email_verified": false, 43806 * "phone_verified": false, 43807 * "sub": "11111111-1111-1111-1111-111111111111" 43808 * }, 43809 * "identities": [ 43810 * { 43811 * "identity_id": "2024-01-01T00:00:00Z", 43812 * "id": "11111111-1111-1111-1111-111111111111", 43813 * "user_id": "11111111-1111-1111-1111-111111111111", 43814 * "identity_data": { 43815 * "email": "[email protected]", 43816 * "email_verified": false, 43817 * "phone_verified": false, 43818 * "sub": "11111111-1111-1111-1111-111111111111" 43819 * }, 43820 * "provider": "email", 43821 * "last_sign_in_at": "2024-01-01T00:00:00Z", 43822 * "created_at": "2024-01-01T00:00:00Z", 43823 * "updated_at": "2024-01-01T00:00:00Z", 43824 * "email": "[email protected]" 43825 * } 43826 * ], 43827 * "created_at": "2024-01-01T00:00:00Z", 43828 * "updated_at": "2024-01-01T00:00:00Z", 43829 * "is_anonymous": false 43830 * }, 43831 * "token_type": "bearer", 43832 * "expires_in": 3500, 43833 * "expires_at": 1700000000 43834 * } 43835 * }, 43836 * "error": null 43837 * } 43838 * ``` 43839 */ 43840 async setSession(e) { 43841 return await this.initializePromise, this.lock != null ? await this._acquireLock(this.lockAcquireTimeout, async () => await this._setSession(e)) : await this._setSession(e); 43842 } 43843 async _setSession(e) { 43844 try { 43845 if (!e.access_token || !e.refresh_token) 43846 throw new nn(); 43847 const t = Date.now() / 1e3; 43848 let i = t, r = !0, s = null; 43849 const { payload: a } = uo(e.access_token); 43850 if (a.exp && (i = a.exp, r = i <= t), r) { 43851 const { data: l, error: o } = await this._callRefreshToken(e.refresh_token); 43852 if (o) 43853 return this._returnResult({ data: { user: null, session: null }, error: o }); 43854 if (!l) 43855 return { data: { user: null, session: null }, error: null }; 43856 s = l; 43857 } else { 43858 const { data: l, error: o } = await this._getUser(e.access_token); 43859 if (o) 43860 return this._returnResult({ data: { user: null, session: null }, error: o }); 43861 s = { 43862 access_token: e.access_token, 43863 refresh_token: e.refresh_token, 43864 user: l.user, 43865 token_type: "bearer", 43866 expires_in: i - t, 43867 expires_at: i 43868 }, await this._saveSession(s), await this._notifyAllSubscribers("SIGNED_IN", s); 43869 } 43870 return this._returnResult({ data: { user: s.user, session: s }, error: null }); 43871 } catch (t) { 43872 if (Re(t)) 43873 return this._returnResult({ data: { session: null, user: null }, error: t }); 43874 throw t; 43875 } 43876 } 43877 /** 43878 * Returns a new session, regardless of expiry status. 43879 * Takes in an optional current session. If not passed in, then refreshSession() will attempt to retrieve it from getSession().
43880 * If the current session's refresh token is invalid, an error will be thrown. 43881 * @param currentSession The current session. If passed in, it must contain a refresh token. 43882 * 43883 * @category Auth 43884 * 43885 * @remarks 43886 * - This method will refresh and return a new session whether the current one is expired or not. 43887 * 43888 * @example Refresh session using the current session 43889 * ```js 43890 * const { data, error } = await supabase.auth.refreshSession() 43891 * const { session, user } = data 43892 * ``` 43893 * 43894 * @exampleResponse Refresh session using the current session 43895 * ```json 43896 * { 43897 * "data": { 43898 * "user": { 43899 * "id": "11111111-1111-1111-1111-111111111111", 43900 * "aud": "authenticated", 43901 * "role": "authenticated", 43902 * "email": "[email protected]", 43903 * "email_confirmed_at": "2024-01-01T00:00:00Z", 43904 * "phone": "", 43905 * "confirmed_at": "2024-01-01T00:00:00Z", 43906 * "last_sign_in_at": "2024-01-01T00:00:00Z", 43907 * "app_metadata": { 43908 * "provider": "email", 43909 * "providers": [ 43910 * "email" 43911 * ] 43912 * }, 43913 * "user_metadata": { 43914 * "email": "[email protected]", 43915 * "email_verified": false, 43916 * "phone_verified": false, 43917 * "sub": "11111111-1111-1111-1111-111111111111" 43918 * }, 43919 * "identities": [ 43920 * { 43921 * "identity_id": "22222222-2222-2222-2222-222222222222", 43922 * "id": "11111111-1111-1111-1111-111111111111", 43923 * "user_id": "11111111-1111-1111-1111-111111111111", 43924 * "identity_data": { 43925 * "email": "[email protected]", 43926 * "email_verified": false, 43927 * "phone_verified": false, 43928 * "sub": "11111111-1111-1111-1111-111111111111" 43929 * }, 43930 * "provider": "email", 43931 * "last_sign_in_at": "2024-01-01T00:00:00Z", 43932 * "created_at": "2024-01-01T00:00:00Z", 43933 * "updated_at": "2024-01-01T00:00:00Z", 43934 * "email": "[email protected]" 43935 * } 43936 * ], 43937 * "created_at": "2024-01-01T00:00:00Z", 43938 * "updated_at": "2024-01-01T00:00:00Z", 43939 * "is_anonymous": false 43940 * }, 43941 * "session": { 43942 * "access_token": "<ACCESS_TOKEN>", 43943 * "token_type": "bearer", 43944 * "expires_in": 3600, 43945 * "expires_at": 1700000000, 43946 * "refresh_token": "<REFRESH_TOKEN>", 43947 * "user": { 43948 * "id": "11111111-1111-1111-1111-111111111111", 43949 * "aud": "authenticated", 43950 * "role": "authenticated", 43951 * "email": "[email protected]", 43952 * "email_confirmed_at": "2024-01-01T00:00:00Z", 43953 * "phone": "", 43954 * "confirmed_at": "2024-01-01T00:00:00Z", 43955 * "last_sign_in_at": "2024-01-01T00:00:00Z", 43956 * "app_metadata": { 43957 * "provider": "email", 43958 * "providers": [ 43959 * "email" 43960 * ] 43961 * }, 43962 * "user_metadata": { 43963 * "email": "[email protected]", 43964 * "email_verified": false, 43965 * "phone_verified": false, 43966 * "sub": "11111111-1111-1111-1111-111111111111" 43967 * }, 43968 * "identities": [ 43969 * { 43970 * "identity_id": "22222222-2222-2222-2222-222222222222", 43971 * "id": "11111111-1111-1111-1111-111111111111", 43972 * "user_id": "11111111-1111-1111-1111-111111111111", 43973 * "identity_data": { 43974 * "email": "[email protected]", 43975 * "email_verified": false, 43976 * "phone_verified": false, 43977 * "sub": "11111111-1111-1111-1111-111111111111" 43978 * }, 43979 * "provider": "email", 43980 * "last_sign_in_at": "2024-01-01T00:00:00Z", 43981 * "created_at": "2024-01-01T00:00:00Z", 43982 * "updated_at": "2024-01-01T00:00:00Z", 43983 * "email": "[email protected]" 43984 * } 43985 * ], 43986 * "created_at": "2024-01-01T00:00:00Z", 43987 * "updated_at": "2024-01-01T00:00:00Z", 43988 * "is_anonymous": false 43989 * } 43990 * } 43991 * }, 43992 * "error": null 43993 * } 43994 * ``` 43995 * 43996 * @example Refresh session using a refresh token 43997 * ```js 43998 * const { data, error } = await supabase.auth.refreshSession({ refresh_token }) 43999 * const { session, user } = data 44000 * ``` 44001 */ 44002 async refreshSession(e) { 44003 return await this.initializePromise, this.lock != null ? await this._acquireLock(this.lockAcquireTimeout, async () => await this._refreshSession(e)) : await this._refreshSession(e); 44004 } 44005 async _refreshSession(e) { 44006 try { 44007 return await this._useSession(async (t) => { 44008 var i; 44009 if (!e) { 44010 const { data: a, error: l } = t; 44011 if (l) 44012 throw l; 44013 e = (i = a.session) !== null && i !== void 0 ? i : void 0; 44014 } 44015 if (!e?.refresh_token) 44016 throw new nn(); 44017 const { data: r, error: s } = await this._callRefreshToken(e.refresh_token); 44018 return s ? this._returnResult({ data: { user: null, session: null }, error: s }) : r ? this._returnResult({ data: { user: r.user, session: r }, error: null }) : this._returnResult({ data: { user: null, session: null }, error: null }); 44019 }); 44020 } catch (t) { 44021 if (Re(t)) 44022 return this._returnResult({ data: { user: null, session: null }, error: t }); 44023 throw t; 44024 } 44025 } 44026 /** 44027 * Gets the session data from a URL string 44028 */ 44029 async _getSessionFromURL(e, t) { 44030 var i; 44031 try { 44032 if (!hn()) 44033 throw new co("No browser detected."); 44034 if (e.error || e.error_description || e.error_code) 44035 throw new co(e.error_description || "Error in URL with unspecified error_description", { 44036 error: e.error || "unspecified_error", 44037 code: e.error_code || "unspecified_code" 44038 }); 44039 switch (t) { 44040 case "implicit": 44041 if (this.flowType === "pkce") 44042 throw new ff("Not a valid PKCE flow url."); 44043 break; 44044 case "pkce": 44045 if (this.flowType === "implicit") 44046 throw new co("Not a valid implicit grant flow url."); 44047 break; 44048 default: 44049 } 44050 if (t === "pkce") { 44051 if (this._debug("#_initialize()", "begin", "is PKCE flow", !0), !e.code) 44052 throw new ff("No code detected."); 44053 const { data: x, error: E } = await this._exchangeCodeForSession(e.code); 44054 if (E) 44055 throw E; 44056 const R = new URL(window.location.href); 44057 return R.searchParams.delete("code"), window.history.replaceState(window.history.state, "", R.toString()), { 44058 data: { session: x.session, redirectType: (i = x.redirectType) !== null && i !== void 0 ? i : null }, 44059 error: null 44060 }; 44061 } 44062 const { provider_token: r, provider_refresh_token: s, access_token: a, refresh_token: l, expires_in: o, expires_at: c, token_type: u } = e; 44063 if (!a || !o || !l || !u) 44064 throw new co("No session defined in URL"); 44065 const h = Math.round(Date.now() / 1e3), d = parseInt(o); 44066 let f = h + d; 44067 c && (f = parseInt(c)); 44068 const p = f - h;
44069 p * 1e3 <= qi && console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${d}s`); 44070 const v = f - d; 44071 h - v >= 120 ? console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale", v, f, h) : h - v < 0 && console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew", v, f, h); 44072 const { data: m, error: g } = await this._getUser(a); 44073 if (g) 44074 throw g; 44075 const _ = { 44076 provider_token: r, 44077 provider_refresh_token: s, 44078 access_token: a, 44079 expires_in: d, 44080 expires_at: f, 44081 refresh_token: l, 44082 token_type: u, 44083 user: m.user 44084 }; 44085 return window.location.hash = "", this._debug("#_getSessionFromURL()", "clearing window.location.hash"), this._returnResult({ data: { session: _, redirectType: e.type }, error: null }); 44086 } catch (r) { 44087 if (Re(r)) 44088 return this._returnResult({ data: { session: null, redirectType: null }, error: r }); 44089 throw r; 44090 } 44091 } 44092 /** 44093 * Checks if the current URL contains parameters given by an implicit oauth grant flow (https://www.rfc-editor.org/rfc/rfc6749.html#section-4.2) 44094 * 44095 * If `detectSessionInUrl` is a function, it will be called with the URL and params to determine 44096 * if the URL should be processed as a Supabase auth callback. This allows users to exclude 44097 * URLs from other OAuth providers (e.g., Facebook Login) that also return access_token in the fragment. 44098 */ 44099 _isImplicitGrantCallback(e) { 44100 return typeof this.detectSessionInUrl == "function" ? this.detectSessionInUrl(new URL(window.location.href), e) : !!(e.access_token || e.error || e.error_description || e.error_code); 44101 } 44102 /** 44103 * Checks if the current URL and backing storage contain parameters given by a PKCE flow 44104 */ 44105 async _isPKCECallback(e) { 44106 const t = await Ai(this.storage, `${this.storageKey}-code-verifier`); 44107 return !!(e.code && t); 44108 } 44109 /** 44110 * Inside a browser context, `signOut()` will remove the logged in user from the browser session and log them out - removing all items from localstorage and then trigger a `"SIGNED_OUT"` event. 44111 * 44112 * For server-side management, you can revoke all refresh tokens for a user by passing a user's JWT through to `auth.api.signOut(JWT: string)`. 44113 * There is no way to revoke a user's access token jwt until it expires. It is recommended to set a shorter expiry on the jwt for this reason. 44114 * 44115 * If using `others` scope, no `SIGNED_OUT` event is fired! 44116 * 44117 * **Warning:** the default `scope` is `'global'`. This signs the user out of 44118 * **every device they are currently signed in on**, not just the current 44119 * tab/session. If you only want to sign the user out of the current session 44120 * (the behavior most other auth libraries default to), pass 44121 * `{ scope: 'local' }` explicitly. 44122 * 44123 * @category Auth 44124 * 44125 * @remarks 44126 * - In order to use the `signOut()` method, the user needs to be signed in first. 44127 * - By default, `signOut()` uses the **global** scope, which signs out the user 44128 * on every device they are signed in on (not just the current one). Pass 44129 * `{ scope: 'local' }` to only sign out the current session. This is 44130 * usually what apps want on a "Sign out" button, especially when users 44131 * sign in from multiple devices and do not expect signing out of one to 44132 * terminate the others. 44133 * - Since Supabase Auth uses JWTs for authentication, the access token JWT will be valid until it's expired. When the user signs out, Supabase revokes the refresh token and deletes the JWT from the client-side. This does not revoke the JWT and it will still be valid until it expires. 44134 * 44135 * @example Sign out of every device (global â default) 44136 * ```js 44137 * const { error } = await supabase.auth.signOut() 44138 * ``` 44139 * 44140 * @example Sign out only the current session (recommended for most apps) 44141 * ```js 44142 * const { error } = await supabase.auth.signOut({ scope: 'local' }) 44143 * ``` 44144 * 44145 * @example Sign out of all other sessions, keep the current one 44146 * ```js 44147 * const { error } = await supabase.auth.signOut({ scope: 'others' }) 44148 * ``` 44149 */ 44150 async signOut(e = { scope: "global" }) { 44151 return await this.initializePromise, this.lock != null ? await this._acquireLock(this.lockAcquireTimeout, async () => await this._signOut(e)) : await this._signOut(e); 44152 } 44153 async _signOut({ scope: e } = { scope: "global" }) { 44154 return await this._useSession(async (t) => { 44155 var i; 44156 const { data: r, error: s } = t; 44157 if (s && !oo(s)) 44158 return this._returnResult({ error: s }); 44159 const a = (i = r.session) === null || i === void 0 ? void 0 : i.access_token; 44160 if (a) { 44161 const { error: l } = await this.admin.signOut(a, e); 44162 if (l && !(VT(l) && (l.status === 404 || l.status === 401 || l.status === 403) || oo(l))) 44163 return this._returnResult({ error: l }); 44164 } 44165 return e !== "others" && (await this._removeSession(), await $t(this.storage, `${this.storageKey}-code-verifier`)), this._returnResult({ error: null }); 44166 }); 44167 } 44168 /** * 44169 * @category Auth 44170 * 44171 * @remarks 44172 * - Subscribes to important events occurring on the user's session. 44173 * - Use on the frontend/client. It is less useful on the server. 44174 * - Events are emitted across tabs to keep your application's UI up-to-date. Some events can fire very frequently, based on the number of tabs open. Use a quick and efficie
44174nt callback function, and defer or debounce as many operations as you can to be performed outside of the callback. 44175 * - Callbacks can be `async` and can safely call other Supabase auth methods (`getUser`, `setSession`, etc.) from inside the callback. 44176 * - Keep callbacks quick. Events are awaited in order, so a slow callback delays subsequent events to subscribers in this tab. 44177 * - Emitted events: 44178 * - `INITIAL_SESSION` 44179 * - Emitted right after the Supabase client is constructed and the initial session from storage is loaded. 44180 * - `SIGNED_IN` 44181 * - Emitted each time a user session is confirmed or re-established, including on user sign in and when refocusing a tab. 44182 * - Avoid making assumptions as to when this event is fired, this may occur even when the user is already signed in. Instead, check the user object attached to the event to see if a new user has signed in and update your application's UI. 44183 * - This event can fire very frequently depending on the number of tabs open in your application. 44184 * - `SIGNED_OUT` 44185 * - Emitted when the user signs out. This can be after: 44186 * - A call to `supabase.auth.signOut()`. 44187 * - After the user's session has expired for any reason: 44188 * - User has signed out on another device. 44189 * - The session has reached its timebox limit or inactivity timeout. 44190 * - User has signed in on another device with single session per user enabled. 44191 * - Check the [User Sessions](/docs/guides/auth/sessions) docs for more information. 44192 * - Use this to clean up any local storage your application has associated with the user. 44193 * - `TOKEN_REFRESHED` 44194 * - Emitted each time a new access and refresh token are fetched for the signed in user. 44195 * - It's best practice and highly recommended to extract the access token (JWT) and store it in memory for further use in your application. 44196 * - Avoid frequent calls to `supabase.auth.getSession()` for the same purpose. 44197 * - There is a background process that keeps track of when the session should be refreshed so you will always receive valid tokens by listening to this event. 44198 * - The frequency of this event is related to the JWT expiry limit configured on your project. 44199 * - `USER_UPDATED` 44200 * - Emitted each time the `supabase.auth.updateUser()` method finishes successfully. Listen to it to update your application's UI based on new profile information. 44201 * - `PASSWORD_RECOVERY` 44202 * - Emitted instead of the `SIGNED_IN` event when the user lands on a page that includes a password recovery link in the URL. 44203 * - Use it to show a UI to the user where they can [reset their password](/docs/guides/auth/passwords#resetting-a-users-password-forgot-password). 44204 * 44205 * @example Listen to auth changes 44206 * ```js 44207 * const { data } = supabase.auth.onAuthStateChange((event, session) => { 44208 * console.log(event, session) 44209 * 44210 * if (event === 'INITIAL_SESSION') { 44211 * // handle initial session 44212 * } else if (event === 'SIGNED_IN') { 44213 * // handle sign in event 44214 * } else if (event === 'SIGNED_OUT') { 44215 * // handle sign out event 44216 * } else if (event === 'PASSWORD_RECOVERY') { 44217 * // handle password recovery event 44218 * } else if (event === 'TOKEN_REFRESHED') { 44219 * // handle token refreshed event 44220 * } else if (event === 'USER_UPDATED') { 44221 * // handle user updated event 44222 * } 44223 * }) 44224 * 44225 * // call unsubscribe to remove the callback 44226 * data.subscription.unsubscribe() 44227 * ``` 44228 * 44229 * @exampleDescription Listen to sign out 44230 * Make sure you clear out any local data, such as local and session storage, after the client library has detected the user's sign out. 44231 * 44232 * @example Listen to sign out 44233 * ```js 44234 * supabase.auth.onAuthStateChange((event, session) => { 44235 * if (event === 'SIGNED_OUT') { 44236 * console.log('SIGNED_OUT', session) 44237 * 44238 * // clear local and session storage 44239 * [ 44240 * window.localStorage, 44241 * window.sessionStorage, 44242 * ].forEach((storage) => { 44243 * Object.entries(storage) 44244 * .forEach(([key]) => { 44245 * storage.removeItem(key) 44246 * }) 44247 * }) 44248 * } 44249 * }) 44250 * ``` 44251 * 44252 * @exampleDescription Store OAuth provider tokens on sign in 44253 * When using [OAuth (Social Login)](/docs/guides/auth/social-login) you sometimes wish to get access to the provider's access token and refresh token, in order to call provider APIs in the name of the user. 44254 * 44255 * For example, if you are using [Sign in with Google](/docs/guides/auth/social-login/auth-google) you may want to use the provider token to call Google APIs on behalf of the user. Supabase Auth does not keep track of the provider access and refresh token, but does return them for you once, immediately after sign in. You can use the `onAuthStateChange` method to listen for the presence of the provider tokens and store them in local storage. You can further send them to your server's APIs for use on the backend. 44256 * 44257 * Finally, make sure you remove them from local storage on the `SIGNED_OUT` event. If the OAuth provider supports token revocation, make sure you call those APIs either from the frontend or schedule them to be called on the backend. 44258 * 44259 * @example Store OAuth provider tokens on sign in 44260 * ```js 44261 * // Register this immediately after calling createClient! 44262 * // Because signInWithOAuth causes a redirect, you need to fetch the 44263 * // provider tokens from the callback. 44264 * supabase.auth.onAuthStateChange((event, session) => { 44265 * if (session && session.provider_token) { 44266 * window.localStorage.setItem('oauth_provider_token', session.provider_token) 44267 * } 44268 * 44269 * if (session && session.provider_refresh_token) { 44270 * window.localStorage.setItem('oauth_provider_refresh_token', session.provider_refresh_token) 44271 * } 44272 * 44273 * if (event === 'SIGNED_OUT') { 44274 * window.localStorage.removeItem('oauth_provider_token') 44275 * window.localStorage.removeItem('oauth_provider_refresh_token') 44276 * } 44277 * }) 44278 * ``` 44279 * 44280 * @exampleDescription Use React Context for the User's session 44281 * Instead of relying on `supabase.auth.getSession()` within your React components, you can use a [React Context](https://react.dev/reference/react/createContext) to store the latest session information from the `onAuthStateChange` c
44281allback and access it that way. 44282 * 44283 * @example Use React Context for the User's session 44284 * ```js 44285 * const SessionContext = React.createContext(null) 44286 * 44287 * function main() { 44288 * const [session, setSession] = React.useState(null) 44289 * 44290 * React.useEffect(() => { 44291 * const {data: { subscription }} = supabase.auth.onAuthStateChange( 44292 * (event, session) => { 44293 * if (event === 'SIGNED_OUT') { 44294 * setSession(null) 44295 * } else if (session) { 44296 * setSession(session) 44297 * } 44298 * }) 44299 * 44300 * return () => { 44301 * subscription.unsubscribe() 44302 * } 44303 * }, []) 44304 * 44305 * return ( 44306 * <SessionContext.Provider value={session}> 44307 * <App /> 44308 * </SessionContext.Provider> 44309 * ) 44310 * } 44311 * ``` 44312 * 44313 * @example Listen to password recovery events 44314 * ```js 44315 * supabase.auth.onAuthStateChange((event, session) => { 44316 * if (event === 'PASSWORD_RECOVERY') { 44317 * console.log('PASSWORD_RECOVERY', session) 44318 * // show screen to update user's password 44319 * showPasswordResetScreen(true) 44320 * } 44321 * }) 44322 * ``` 44323 * 44324 * @example Listen to sign in 44325 * ```js 44326 * supabase.auth.onAuthStateChange((event, session) => { 44327 * if (event === 'SIGNED_IN') console.log('SIGNED_IN', session) 44328 * }) 44329 * ``` 44330 * 44331 * @example Listen to token refresh 44332 * ```js 44333 * supabase.auth.onAuthStateChange((event, session) => { 44334 * if (event === 'TOKEN_REFRESHED') console.log('TOKEN_REFRESHED', session) 44335 * }) 44336 * ``` 44337 * 44338 * @example Listen to user updates 44339 * ```js 44340 * supabase.auth.onAuthStateChange((event, session) => { 44341 * if (event === 'USER_UPDATED') console.log('USER_UPDATED', session) 44342 * }) 44343 * ``` 44344 */ 44345 onAuthStateChange(e) { 44346 const t = QT(), i = { 44347 id: t, 44348 callback: e, 44349 unsubscribe: () => { 44350 this._debug("#unsubscribe()", "state change callback with id removed", t), this.stateChangeEmitters.delete(t); 44351 } 44352 }; 44353 return this._debug("#onAuthStateChange()", "registered callback with id", t), this.stateChangeEmitters.set(t, i), (async () => (await this.initializePromise, this.lock != null ? await this._acquireLock(this.lockAcquireTimeout, async () => { 44354 this._emitInitialSession(t); 44355 }) : await this._emitInitialSession(t)))(), { data: { subscription: i } }; 44356 } 44357 async _emitInitialSession(e) { 44358 return await this._useSession(async (t) => { 44359 var i, r; 44360 try { 44361 const { data: { session: s }, error: a } = t; 44362 if (a) 44363 throw a; 44364 await ((i = this.stateChangeEmitters.get(e)) === null || i === void 0 ? void 0 : i.callback("INITIAL_SESSION", s)), this._debug("INITIAL_SESSION", "callback id", e, "session", s); 44365 } catch (s) { 44366 await ((r = this.stateChangeEmitters.get(e)) === null || r === void 0 ? void 0 : r.callback("INITIAL_SESSION", null)), this._debug("INITIAL_SESSION", "callback id", e, "error", s), oo(s) ? console.warn(s) : console.error(s); 44367 } 44368 }); 44369 } 44370 /** 44371 * Sends a password reset request to an email address. This method supports the PKCE flow. 44372 * 44373 * @param email The email address of the user. 44374 * @param options.redirectTo The URL to send the user to after they click the password reset link. 44375 * @param options.captchaToken Verification token received when the user completes the captcha on the site. 44376 * 44377 * @category Auth 44378 * 44379 * @remarks 44380 * - The password reset flow consist of 2 broad steps: (i) Allow the user to login via the password reset link; (ii) Update the user's password. 44381 * - The `resetPasswordForEmail()` only sends a password reset link to the user's email. 44382 * To update the user's password, see [`updateUser()`](/docs/reference/javascript/auth-updateuser). 44383 * - A `PASSWORD_RECOVERY` event will be emitted when the password recovery link is clicked. 44384 * You can use [`onAuthStateChange()`](/docs/reference/javascript/auth-onauthstatechange) to listen and invoke a callback function on these events. 44385 * - When the user clicks the reset link in the email they are redirected back to your application. 44386 * You can configure the URL that the user is redirected to with the `redirectTo` parameter.
44387 * See [redirect URLs and wildcards](/docs/guides/auth/redirect-urls#use-wildcards-in-redirect-urls) to add additional redirect URLs to your project. 44388 * - After the user has been redirected successfully, prompt them for a new password and call `updateUser()`: 44389 * ```js 44390 * const { data, error } = await supabase.auth.updateUser({ 44391 * password: new_password 44392 * }) 44393 * ``` 44394 * 44395 * @example Reset password 44396 * ```js 44397 * const { data, error } = await supabase.auth.resetPasswordForEmail(email, { 44398 * redirectTo: 'https://example.com/update-password', 44399 * }) 44400 * ``` 44401 * 44402 * @exampleResponse Reset password 44403 * ```json 44404 * { 44405 * data: {} 44406 * error: null 44407 * } 44408 * ``` 44409 * 44410 * @example Reset password (React) 44411 * ```js 44412 * /** 44413 * * Step 1: Send the user an email to get a password reset token. 44414 * * This email contains a link which sends the user back to your application. 44415 * *\/ 44416 * const { data, error } = await supabase.auth 44417 * .resetPasswordForEmail('[email protected]') 44418 * 44419 * /** 44420 * * Step 2: Once the user is redirected back to your application, 44421 * * ask the user to reset their password. 44422 * *\/ 44423 * useEffect(() => { 44424 * supabase.auth.onAuthStateChange(async (event, session) => { 44425 * if (event == "PASSWORD_RECOVERY") { 44426 * const newPassword = prompt("What would you like your new password to be?"); 44427 * const { data, error } = await supabase.auth 44428 * .updateUser({ password: newPassword }) 44429 * 44430 * if (data) alert("Password updated successfully!") 44431 * if (error) alert("There was an error updating your password.") 44432 * } 44433 * }) 44434 * }, []) 44435 * ``` 44436 */ 44437 async resetPasswordForEmail(e, t = {}) { 44438 let i = null, r = null; 44439 this.flowType === "pkce" && ([i, r] = await _r( 44440 this.storage, 44441 this.storageKey, 44442 !0 44443 // isPasswordRecovery 44444 )); 44445 try { 44446 return await He(this.fetch, "POST", `${this.url}/recover`, { 44447 body: { 44448 email: e, 44449 code_challenge: i, 44450 code_challenge_method: r, 44451 gotrue_meta_security: { captcha_token: t.captchaToken } 44452 }, 44453 headers: this.headers, 44454 redirectTo: t.redirectTo 44455 }); 44456 } catch (s) { 44457 if (await $t(this.storage, `${this.storageKey}-code-verifier`), Re(s)) 44458 return this._returnResult({ data: null, error: s }); 44459 throw s; 44460 } 44461 } 44462 /** 44463 * Gets all the identities linked to a user. 44464 * 44465 * @category Auth 44466 * 44467 * @remarks 44468 * - The user needs to be signed in to call `getUserIdentities()`. 44469 * 44470 * @example Returns a list of identities linked to the user 44471 * ```js 44472 * const { data, error } = await supabase.auth.getUserIdentities() 44473 * ``` 44474 * 44475 * @exampleResponse Returns a list of identities linked to the user 44476 * ```json 44477 * { 44478 * "data": { 44479 * "identities": [ 44480 * { 44481 * "identity_id": "22222222-2222-2222-2222-222222222222", 44482 * "id": "2024-01-01T00:00:00Z", 44483 * "user_id": "2024-01-01T00:00:00Z", 44484 * "identity_data": { 44485 * "email": "[email protected]", 44486 * "email_verified": false, 44487 * "phone_verified": false, 44488 * "sub": "11111111-1111-1111-1111-111111111111" 44489 * }, 44490 * "provider": "email", 44491 * "last_sign_in_at": "2024-01-01T00:00:00Z", 44492 * "created_at": "2024-01-01T00:00:00Z", 44493 * "updated_at": "2024-01-01T00:00:00Z", 44494 * "email": "[email protected]" 44495 * } 44496 * ] 44497 * }, 44498 * "error": null 44499 * } 44500 * ``` 44501 */ 44502 async getUserIdentities() { 44503 var e; 44504 try { 44505 const { data: t, error: i } = await this.getUser(); 44506 if (i) 44507 throw i; 44508 return this._returnResult({ data: { identities: (e = t.user.identities) !== null && e !== void 0 ? e : [] }, error: null }); 44509 } catch (t) { 44510 if (Re(t)) 44511 return this._returnResult({ data: null, error: t }); 44512 throw t; 44513 } 44514 } 44515 /** * 44516 * @category Auth 44517 * 44518 * @remarks 44519 * - The **Enable Manual Linking** option must be enabled from your [project's authentication settings](/dashboard/project/_/auth/providers). 44520 * - The user needs to be signed in to call `linkIdentity()`. 44521 * - If the candidate identity is already linked to the existing user or another user, `linkIdentity()` will fail. 44522 * - If `linkIdentity` is run in the browser, the user is automatically redirected to the returned URL. On the server, you should handle the redirect. 44523 *
44524 * @example Link an identity to a user 44525 * ```js 44526 * const { data, error } = await supabase.auth.linkIdentity({ 44527 * provider: 'github' 44528 * }) 44529 * ``` 44530 * 44531 * @exampleResponse Link an identity to a user 44532 * ```json 44533 * { 44534 * data: { 44535 * provider: 'github', 44536 * url: <PROVIDER_URL_TO_REDIRECT_TO> 44537 * }, 44538 * error: null 44539 * } 44540 * ``` 44541 */ 44542 async linkIdentity(e) { 44543 return "token" in e ? this.linkIdentityIdToken(e) : this.linkIdentityOAuth(e); 44544 } 44545 async linkIdentityOAuth(e) { 44546 var t; 44547 try { 44548 const { data: i, error: r } = await this._useSession(async (s) => { 44549 var a, l, o, c, u; 44550 const { data: h, error: d } = s; 44551 if (d) 44552 throw d; 44553 const f = await this._getUrlForProvider(`${this.url}/user/identities/authorize`, e.provider, { 44554 redirectTo: (a = e.options) === null || a === void 0 ? void 0 : a.redirectTo, 44555 scopes: (l = e.options) === null || l === void 0 ? void 0 : l.scopes, 44556 queryParams: (o = e.options) === null || o === void 0 ? void 0 : o.queryParams, 44557 skipBrowserRedirect: !0 44558 }); 44559 return await He(this.fetch, "GET", f, { 44560 headers: this.headers, 44561 jwt: (u = (c = h.session) === null || c === void 0 ? void 0 : c.access_token) !== null && u !== void 0 ? u : void 0 44562 }); 44563 }); 44564 if (r) 44565 throw r; 44566 return hn() && !(!((t = e.options) === null || t === void 0) && t.skipBrowserRedirect) && window.location.assign(i?.url), this._returnResult({ 44567 data: { provider: e.provider, url: i?.url }, 44568 error: null 44569 }); 44570 } catch (i) { 44571 if (Re(i)) 44572 return this._returnResult({ data: { provider: e.provider, url: null }, error: i }); 44573 throw i; 44574 } 44575 } 44576 async linkIdentityIdToken(e) { 44577 return await this._useSession(async (t) => { 44578 var i; 44579 try { 44580 const { error: r, data: { session: s } } = t; 44581 if (r) 44582 throw r; 44583 const { options: a, provider: l, token: o, access_token: c, nonce: u } = e, h = await He(this.fetch, "POST", `${this.url}/token?grant_type=id_token`, { 44584 headers: this.headers, 44585 jwt: (i = s?.access_token) !== null && i !== void 0 ? i : void 0, 44586 body: { 44587 provider: l, 44588 id_token: o, 44589 access_token: c, 44590 nonce: u, 44591 link_identity: !0, 44592 gotrue_meta_security: { captcha_token: a?.captchaToken } 44593 }, 44594 xform: Bn 44595 }), { data: d, error: f } = h; 44596 return f ? this._returnResult({ data: { user: null, session: null }, error: f }) : !d || !d.session || !d.user ? this._returnResult({ 44597 data: { user: null, session: null }, 44598 error: new es() 44599 }) : (d.session && (await this._saveSession(d.session), await this._notifyAllSubscribers("USER_UPDATED", d.session)), this._returnResult({ data: d, error: f })); 44600 } catch (r) { 44601 if (await $t(this.storage, `${this.storageKey}-code-verifier`), Re(r)) 44602 return this._returnResult({ data: { user: null, session: null }, error: r }); 44603 throw r; 44604 } 44605 }); 44606 } 44607 /** 44608 * Unlinks an identity from a user by deleting it. The user will no longer be able to sign in with that identity once it's unlinked. 44609 * 44610 * @category Auth 44611 * 44612 * @remarks 44613 * - The **Enable Manual Linking** option must be enabled from your [project's authentication settings](/dashboard/project/_/auth/providers). 44614 * - The user needs to be signed in to call `unlinkIdentity()`. 44615 * - The user must have at least 2 identities in order to unlink an identity. 44616 * - The identity to be unlinked must belong to the user. 44617 * 44618 * @example Unlink an identity 44619 * ```js 44620 * // retrieve all identities linked to a user 44621 * const identities = await supabase.auth.getUserIdentities() 44622 * 44623 * // find the google identity 44624 * const googleIdentity = identities.find( 44625 * identity => identity.provider === 'google' 44626 * ) 44627 * 44628 * // unlink the google identity 44629 * const { error } = await supabase.auth.unlinkIdentity(googleIdentity) 44630 * ``` 44631 */ 44632 async unlinkIdentity(e) { 44633 try { 44634 return await this._useSession(async (t) => { 44635 var i, r; 44636 const { data: s, error: a } = t; 44637 if (a) 44638 throw a;
44639 return await He(this.fetch, "DELETE", `${this.url}/user/identities/${e.identity_id}`, { 44640 headers: this.headers, 44641 jwt: (r = (i = s.session) === null || i === void 0 ? void 0 : i.access_token) !== null && r !== void 0 ? r : void 0 44642 }); 44643 }); 44644 } catch (t) { 44645 if (Re(t)) 44646 return this._returnResult({ data: null, error: t }); 44647 throw t; 44648 } 44649 } 44650 /** 44651 * Generates a new JWT. 44652 * @param refreshToken A valid refresh token that was returned on login. 44653 */ 44654 async _refreshAccessToken(e) { 44655 const t = "#_refreshAccessToken()"; 44656 this._debug(t, "begin"); 44657 try { 44658 const i = Date.now(); 44659 return await i1(async (r) => (r > 0 && await n1(200 * Math.pow(2, r - 1)), this._debug(t, "refreshing attempt", r), await He(this.fetch, "POST", `${this.url}/token?grant_type=refresh_token`, { 44660 body: { refresh_token: e }, 44661 headers: this.headers, 44662 xform: Bn 44663 })), (r, s) => { 44664 const a = 200 * Math.pow(2, r); 44665 return s && Xl(s) && // retryable only if the request can be sent before the backoff overflows the tick duration 44666 Date.now() + a - i < qi; 44667 }); 44668 } catch (i) { 44669 if (this._debug(t, "error", i), Re(i)) 44670 return this._returnResult({ data: { session: null, user: null }, error: i }); 44671 throw i; 44672 } finally { 44673 this._debug(t, "end"); 44674 } 44675 } 44676 _isValidSession(e) { 44677 return typeof e == "object" && e !== null && "access_token" in e && "refresh_token" in e && "expires_at" in e; 44678 } 44679 async _handleProviderSignIn(e, t) { 44680 const i = await this._getUrlForProvider(`${this.url}/authorize`, e, { 44681 redirectTo: t.redirectTo, 44682 scopes: t.scopes, 44683 queryParams: t.queryParams 44684 }); 44685 return this._debug("#_handleProviderSignIn()", "provider", e, "options", t, "url", i), hn() && !t.skipBrowserRedirect && window.location.assign(i), { data: { provider: e, url: i }, error: null }; 44686 } 44687 /** 44688 * Recovers the session from LocalStorage and refreshes the token 44689 * Note: this method is async to accommodate for AsyncStorage e.g. in React native. 44690 */ 44691 async _recoverAndRefresh() { 44692 var e, t; 44693 const i = "#_recoverAndRefresh()"; 44694 this._debug(i, "begin"); 44695 try { 44696 const r = await Ai(this.storage, this.storageKey); 44697 if (r && this.userStorage) { 44698 let a = await Ai(this.userStorage, this.storageKey + "-user"); 44699 !this.storage.isServer && Object.is(this.storage, this.userStorage) && !a && (a = { user: r.user }, await as(this.userStorage, this.storageKey + "-user", a)), r.user = (e = a?.user) !== null && e !== void 0 ? e : ql(); 44700 } else if (r && !r.user && !r.user) { 44701 const a = await Ai(this.storage, this.storageKey + "-user"); 44702 a && a?.user ? (r.user = a.user, await $t(this.storage, this.storageKey + "-user"), await as(this.storage, this.storageKey, r)) : r.user = ql(); 44703 } 44704 if (this._debug(i, "session from storage", r), !this._isValidSession(r)) { 44705 this._debug(i, "session is not valid"), r !== null && await this._removeSession(); 44706 return; 44707 } 44708 const s = ((t = r.expires_at) !== null && t !== void 0 ? t : 1 / 0) * 1e3 - Date.now() < jl; 44709 if (this._debug(i, `session has${s ? "" : " not"} expired with margin of ${jl}s`), s) { 44710 if (this.autoRefreshToken && r.refresh_token) { 44711 const { error: a } = await this._callRefreshToken(r.refresh_token); 44712 a && (jT(a) ? this._debug(i, "refresh discarded by commit guard", a) : (this._debug(i, "refresh failed", a), Xl(a) || (this._debug(i, "refresh failed with a non-retryable error, removing the session", a), await this._removeSession()))); 44713 } 44714 } else if (r.user && r.user.__isUserNotAvailableProxy === !0) 44715 try { 44716 const { data: a, error: l } = await this._getUser(r.access_token); 44717 !l && a?.user ? (r.user = a.user, await this._saveSession(r), await this._notifyAllSubscribers("SIGNED_IN", r)) : this._debug(i, "could not get user data, skipping SIGNED_IN notification"); 44718 } catch (a) { 44719 console.error("Error getting user data:", a), this._debug(i, "error getting user data, skipping SIGNED_IN notification", a); 44720 } 44721 else 44722 await this._notifyAllSubscribers("SIGNED_IN", r); 44723 } catch (r) { 44724 this._debug(i, "error", r), console.error(r); 44725 return; 44726 } finally { 44727 this._debug(i, "end"); 44728 } 44729 } 44730 async _callRefreshToken(e) { 44731 var t, i; 44732 if (!e) 44733 throw new nn(); 44734 if (this.refreshingDeferred) 44735 return this.refreshingDeferred.promise; 44736 const r = "#_callRefreshToken()"; 44737 this._debug(r, "begin"); 44738 try { 44739 this.refreshingDeferred = new nl(); 44740 const s = await Ai(this.storage, this.storageKey), { data: a, error: l } = await this._refreshAccessToken(e); 44741 if (l) 44742 throw l; 44743 if (!a.session) 44744 throw new nn(); 44745 const o = await Ai(this.storage, this.storageKey); 44746 if (s !== null && (o === null || o.refresh_token !== s.refresh_token)) { 44747 this._debug(r, "commit guard: storage changed since refresh started, discarding rotated tokens", { 44748 // Presence indicators only â never log refresh token fragments, 44749 // even partial. Logs may be forwarded to third-party services. 44750 startedWith: "present", 44751 nowHolds: o ? "replaced" : "cleared" 44752 }); 44753 const d = { 44754 data: null,
44755 error: new pf() 44756 }; 44757 return this.refreshingDeferred.resolve(d), d; 44758 } 44759 const u = this._sessionRemovalEpoch; 44760 if (await this._saveSession(a.session), this._sessionRemovalEpoch !== u) { 44761 this._debug(r, "commit guard (post-save): _removeSession ran during _saveSession, undoing write"), await $t(this.storage, this.storageKey), this.userStorage && await $t(this.userStorage, this.storageKey + "-user"); 44762 const d = { 44763 data: null, 44764 error: new pf() 44765 }; 44766 return this.refreshingDeferred.resolve(d), d; 44767 } 44768 await this._notifyAllSubscribers("TOKEN_REFRESHED", a.session); 44769 const h = { data: a.session, error: null }; 44770 return this.refreshingDeferred.resolve(h), h; 44771 } catch (s) { 44772 if (this._debug(r, "error", s), Re(s)) { 44773 const a = { data: null, error: s }; 44774 return Xl(s) || await this._removeSession(), (t = this.refreshingDeferred) === null || t === void 0 || t.resolve(a), a; 44775 } 44776 throw (i = this.refreshingDeferred) === null || i === void 0 || i.reject(s), s; 44777 } finally { 44778 this.refreshingDeferred = null, this._debug(r, "end"); 44779 } 44780 } 44781 async _notifyAllSubscribers(e, t, i = !0) { 44782 const r = `#_notifyAllSubscribers(${e})`; 44783 this._debug(r, "begin", t, `broadcast = ${i}`); 44784 try { 44785 this.broadcastChannel && i && this.broadcastChannel.postMessage({ event: e, session: t }); 44786 const s = [], a = Array.from(this.stateChangeEmitters.values()).map(async (l) => { 44787 try { 44788 await l.callback(e, t); 44789 } catch (o) { 44790 s.push(o); 44791 } 44792 }); 44793 if (await Promise.all(a), s.length > 0) { 44794 for (let l = 0; l < s.length; l += 1) 44795 console.error(s[l]); 44796 throw s[0]; 44797 } 44798 } finally { 44799 this._debug(r, "end"); 44800 } 44801 } 44802 /** 44803 * set currentSession and currentUser 44804 * process to _startAutoRefreshToken if possible 44805 */ 44806 async _saveSession(e) { 44807 this._debug("#_saveSession()", e), this.suppressGetSessionWarning = !0, await $t(this.storage, `${this.storageKey}-code-verifier`); 44808 const t = Object.assign({}, e), i = t.user && t.user.__isUserNotAvailableProxy === !0; 44809 if (this.userStorage) { 44810 !i && t.user && await as(this.userStorage, this.storageKey + "-user", { 44811 user: t.user 44812 }); 44813 const r = Object.assign({}, t); 44814 delete r.user; 44815 const s = yf(r); 44816 await as(this.storage, this.storageKey, s); 44817 } else { 44818 const r = yf(t); 44819 await as(this.storage, this.storageKey, r); 44820 } 44821 } 44822 async _removeSession() { 44823 this._sessionRemovalEpoch += 1, this._debug("#_removeSession()"), this.suppressGetSessionWarning = !1, await $t(this.storage, this.storageKey), await $t(this.storage, this.storageKey + "-code-verifier"), await $t(this.storage, this.storageKey + "-user"), this.userStorage && await $t(this.userStorage, this.storageKey + "-user"), await this._notifyAllSubscribers("SIGNED_OUT", null); 44824 } 44825 /** 44826 * Removes any registered visibilitychange callback. 44827 * 44828 * {@see #startAutoRefresh} 44829 * {@see #stopAutoRefresh} 44830 */ 44831 _removeVisibilityChangedCallback() { 44832 this._debug("#_removeVisibilityChangedCallback()"); 44833 const e = this.visibilityChangedCallback; 44834 this.visibilityChangedCallback = null; 44835 try { 44836 e && hn() && window?.removeEventListener && window.removeEventListener("visibilitychange", e); 44837 } catch (t) { 44838 console.error("removing visibilitychange callback failed", t); 44839 } 44840 } 44841 /** 44842 * This is the private implementation of {@link #startAutoRefresh}. Use this 44843 * within the library. 44844 */ 44845 async _startAutoRefresh() { 44846 await this._stopAutoRefresh(), this._debug("#_startAutoRefresh()"); 44847 const e = setInterval(() => this._autoRefreshTokenTick(), qi); 44848 this.autoRefreshTicker = e, e && typeof e == "object" && typeof e.unref == "function" ? e.unref() : typeof Deno < "u" && typeof Deno.unrefTimer == "function" && Deno.unrefTimer(e); 44849 const t = setTimeout(async () => { 44850 await this.initializePromise, await this._autoRefreshTokenTick(); 44851 }, 0); 44852 this.autoRefreshTickTimeout = t, t && typeof t == "object" && typeof t.unref == "function" ? t.unref() : typeof Deno < "u" && typeof Deno.unrefTimer == "function" && Deno.unrefTimer(t); 44853 } 44854 /** 44855 * This is the private implementation of {@link #stopAutoRefresh}. Use this 44856 * within the library. 44857 */ 44858 async _stopAutoRefresh() { 44859 this._debug("#_stopAutoRefresh()"); 44860 const e = this.autoRefreshTicker; 44861 this.autoRefreshTicker = null, e && clearInterval(e); 44862 const t = this.autoRefreshTickTimeout; 44863 this.autoRefreshTickTimeout = null, t && clearTimeout(t); 44864 } 44865 /** 44866 * Starts an auto-refresh process in the background. The session is checked 44867 * every few seconds. Close to the time of expiration a process is started to 44868 * refresh the session. If refreshing fails it will be retried for as long as 44869 * necessary. 44870 * 44871 * If you set the {@link GoTrueClientOptions#autoRefreshToken} you don't need 44872 * to call this function, it will be called for you. 44873 * 44874 * On browsers the refresh process works only when the tab/window is in the 44875 * foreground to conserve resources as well as prevent race conditions and 44876 * flooding auth with requests. If you call this method any managed 44877 * visibility change callback will be removed and you must manage visibility 44878 * changes on your own. 44879 * 44880 * On non-browser platforms the refresh process works *continuously* in the 44881 * background, which may not be desirable. You should hook into your 44882 * platform's foreground indication mechanism and call these methods 44883 * appropriately to conserve resources. 44884 *
44885 * {@see #stopAutoRefresh} 44886 * 44887 * @category Auth 44888 * 44889 * @remarks 44890 * - Only useful in non-browser environments such as React Native or Electron. 44891 * - The Supabase Auth library automatically starts and stops proactively refreshing the session when a tab is focused or not. 44892 * - On non-browser platforms, such as mobile or desktop apps built with web technologies, the library is not able to effectively determine whether the application is _focused_ or not. 44893 * - To give this hint to the application, you should be calling this method when the app is in focus and calling `supabase.auth.stopAutoRefresh()` when it's out of focus. 44894 * 44895 * @example Start and stop auto refresh in React Native 44896 * ```js 44897 * import { AppState } from 'react-native' 44898 * 44899 * // make sure you register this only once! 44900 * AppState.addEventListener('change', (state) => { 44901 * if (state === 'active') { 44902 * supabase.auth.startAutoRefresh() 44903 * } else { 44904 * supabase.auth.stopAutoRefresh() 44905 * } 44906 * }) 44907 * ``` 44908 */ 44909 async startAutoRefresh() { 44910 this._removeVisibilityChangedCallback(), await this._startAutoRefresh(); 44911 } 44912 /** 44913 * Stops an active auto refresh process running in the background (if any). 44914 * 44915 * If you call this method any managed visibility change callback will be 44916 * removed and you must manage visibility changes on your own. 44917 * 44918 * See {@link #startAutoRefresh} for more details. 44919 * 44920 * @category Auth 44921 * 44922 * @remarks 44923 * - Only useful in non-browser environments such as React Native or Electron. 44924 * - The Supabase Auth library automatically starts and stops proactively refreshing the session when a tab is focused or not. 44925 * - On non-browser platforms, such as mobile or desktop apps built with web technologies, the library is not able to effectively determine whether the application is _focused_ or not. 44926 * - When your application goes in the background or out of focus, call this method to stop the proactive refreshing of the session. 44927 * 44928 * @example Start and stop auto refresh in React Native 44929 * ```js 44930 * import { AppState } from 'react-native' 44931 * 44932 * // make sure you register this only once! 44933 * AppState.addEventListener('change', (state) => { 44934 * if (state === 'active') { 44935 * supabase.auth.startAutoRefresh() 44936 * } else { 44937 * supabase.auth.stopAutoRefresh() 44938 * } 44939 * }) 44940 * ``` 44941 */ 44942 async stopAutoRefresh() { 44943 this._removeVisibilityChangedCallback(), await this._stopAutoRefresh(); 44944 } 44945 /** 44946 * Tears down the client's background work: stops the auto-refresh interval, 44947 * removes the `visibilitychange` listener, closes the cross-tab 44948 * `BroadcastChannel`, and clears registered `onAuthStateChange` subscribers. 44949 * 44950 * Call this from cleanup hooks when the client is being replaced before 44951 * its JS realm is destroyed. React Strict Mode and HMR are the common 44952 * cases. Any in-flight `fetch` calls continue to completion and may still 44953 * write to storage; dispose doesn't abort them or erase storage. 44954 * 44955 * Lifecycle caveat: because in-flight refreshes are not aborted, a 44956 * disposed instance can still persist a rotated session to storage after 44957 * `dispose()` returns. A subsequent `createClient` against the same 44958 * `storageKey` will pick up that session on its next read. If you need 44959 * strict isolation between client lifecycles, await any pending auth 44960 * operation before calling `dispose()` (or change the `storageKey` for 44961 * the replacement client). 44962 * 44963 * Safe to call repeatedly. 44964 * 44965 * @category Auth 44966 * 44967 * @example Cleanup on React unmount 44968 * ```ts 44969 * useEffect(() => { 44970 * const client = createClient(...) 44971 * return () => { client.auth.dispose() } 44972 * }, []) 44973 * ``` 44974 */ 44975 async dispose() { 44976 var e; 44977 this._removeVisibilityChangedCallback(), await this._stopAutoRefresh(), (e = this.broadcastChannel) === null || e === void 0 || e.close(), this.broadcastChannel = null, this.stateChangeEmitters.clear(); 44978 } 44979 /** 44980 * Runs the auto refresh token tick. 44981 */ 44982 async _autoRefreshTokenTick() { 44983 if (this._debug("#_autoRefreshTokenTick()", "begin"), this.lock != null) {
44984 try { 44985 await this._acquireLock(0, async () => { 44986 try { 44987 const e = Date.now(); 44988 try { 44989 return await this._useSession(async (t) => { 44990 const { data: { session: i } } = t; 44991 if (!i || !i.refresh_token || !i.expires_at) { 44992 this._debug("#_autoRefreshTokenTick()", "no session"); 44993 return; 44994 } 44995 const r = Math.floor((i.expires_at * 1e3 - e) / qi); 44996 this._debug("#_autoRefreshTokenTick()", `access token expires in ${r} ticks, a tick lasts ${qi}ms, refresh threshold is ${Ys} ticks`), r <= Ys && await this._callRefreshToken(i.refresh_token); 44997 }); 44998 } catch (t) { 44999 console.error("Auto refresh tick failed with error. This is likely a transient error.", t); 45000 } 45001 } finally { 45002 this._debug("#_autoRefreshTokenTick()", "end"); 45003 } 45004 }); 45005 } catch (e) { 45006 if (e instanceof b1) 45007 this._debug("auto refresh token tick lock not available"); 45008 else 45009 throw e; 45010 } 45011 return; 45012 } 45013 if (this.refreshingDeferred !== null) { 45014 this._debug("#_autoRefreshTokenTick()", "refresh already in flight, skipping"); 45015 return; 45016 } 45017 try { 45018 const e = Date.now(); 45019 try { 45020 await this._useSession(async (t) => { 45021 const { data: { session: i } } = t; 45022 if (!i || !i.refresh_token || !i.expires_at) { 45023 this._debug("#_autoRefreshTokenTick()", "no session"); 45024 return; 45025 } 45026 const r = Math.floor((i.expires_at * 1e3 - e) / qi); 45027 this._debug("#_autoRefreshTokenTick()", `access token expires in ${r} ticks, a tick lasts ${qi}ms, refresh threshold is ${Ys} ticks`), r <= Ys && await this._callRefreshToken(i.refresh_token); 45028 }); 45029 } catch (t) { 45030 console.error("Auto refresh tick failed with error. This is likely a transient error.", t); 45031 } 45032 } finally { 45033 this._debug("#_autoRefreshTokenTick()", "end"); 45034 } 45035 } 45036 /** 45037 * Registers callbacks on the browser / platform, which in-turn run 45038 * algorithms when the browser window/tab are in foreground. On non-browser 45039 * platforms it assumes always foreground. 45040 */ 45041 async _handleVisibilityChange() { 45042 if (this._debug("#_handleVisibilityChange()"), !hn() || !window?.addEventListener) 45043 return this.autoRefreshToken && this.startAutoRefresh(), !1; 45044 try { 45045 this.visibilityChangedCallback = async () => { 45046 try { 45047 await this._onVisibilityChanged(!1); 45048 } catch (e) { 45049 this._debug("#visibilityChangedCallback", "error", e); 45050 } 45051 }, window?.addEventListener("visibilitychange", this.visibilityChangedCallback), await this._onVisibilityChanged(!0); 45052 } catch (e) { 45053 console.error("_handleVisibilityChange", e); 45054 } 45055 } 45056 /** 45057 * Callback registered with `window.addEventListener('visibilitychange')`. 45058 */ 45059 async _onVisibilityChanged(e) { 45060 const t = `#_onVisibilityChanged(${e})`; 45061 if (this._debug(t, "visibilityState", document.visibilityState), document.visibilityState === "visible") { 45062 if (this.autoRefreshToken && this._startAutoRefresh(), !e) 45063 if (await this.initializePromise, this.lock != null) 45064 await this._acquireLock(this.lockAcquireTimeout, async () => { 45065 if (document.visibilityState !== "visible") { 45066 this._debug(t, "acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting"); 45067 return; 45068 } 45069 await this._recoverAndRefresh(); 45070 }); 45071 else { 45072 if (document.visibilityState !== "visible") { 45073 this._debug(t, "visibilityState is no longer visible, skipping recovery"); 45074 return; 45075 } 45076 await this._recoverAndRefresh(); 45077 } 45078 } else document.visibilityState === "hidden" && this.autoRefreshToken && this._stopAutoRefresh(); 45079 } 45080 /** 45081 * Generates the relevant login URL for a third-party provider. 45082 * @param options.redirectTo A URL or mobile address to send the user to after they are confirmed. 45083 * @param options.scopes A space-separated list of scopes granted to the OAuth application.
45084 * @param options.queryParams An object of key-value pairs containing query parameters granted to the OAuth application. 45085 */ 45086 async _getUrlForProvider(e, t, i) { 45087 const r = [`provider=${encodeURIComponent(t)}`]; 45088 if (i?.redirectTo && r.push(`redirect_to=${encodeURIComponent(i.redirectTo)}`), i?.scopes && r.push(`scopes=${encodeURIComponent(i.scopes)}`), this.flowType === "pkce") { 45089 const [s, a] = await _r(this.storage, this.storageKey), l = new URLSearchParams({ 45090 code_challenge: `${encodeURIComponent(s)}`, 45091 code_challenge_method: `${encodeURIComponent(a)}` 45092 }); 45093 r.push(l.toString()); 45094 } 45095 if (i?.queryParams) { 45096 const s = new URLSearchParams(i.queryParams); 45097 r.push(s.toString()); 45098 } 45099 return i?.skipBrowserRedirect && r.push(`skip_http_redirect=${i.skipBrowserRedirect}`), `${e}?${r.join("&")}`; 45100 } 45101 async _unenroll(e) { 45102 try { 45103 return await this._useSession(async (t) => { 45104 var i; 45105 const { data: r, error: s } = t; 45106 return s ? this._returnResult({ data: null, error: s }) : await He(this.fetch, "DELETE", `${this.url}/factors/${e.factorId}`, { 45107 headers: this.headers, 45108 jwt: (i = r?.session) === null || i === void 0 ? void 0 : i.access_token 45109 }); 45110 }); 45111 } catch (t) { 45112 if (Re(t)) 45113 return this._returnResult({ data: null, error: t }); 45114 throw t; 45115 } 45116 } 45117 async _enroll(e) { 45118 try { 45119 return await this._useSession(async (t) => { 45120 var i, r; 45121 const { data: s, error: a } = t; 45122 if (a) 45123 return this._returnResult({ data: null, error: a }); 45124 const l = Object.assign({ friendly_name: e.friendlyName, factor_type: e.factorType }, e.factorType === "phone" ? { phone: e.phone } : e.factorType === "totp" ? { issuer: e.issuer } : {}), { data: o, error: c } = await He(this.fetch, "POST", `${this.url}/factors`, { 45125 body: l, 45126 headers: this.headers, 45127 jwt: (i = s?.session) === null || i === void 0 ? void 0 : i.access_token 45128 }); 45129 return c ? this._returnResult({ data: null, error: c }) : (e.factorType === "totp" && o.type === "totp" && (!((r = o?.totp) === null || r === void 0) && r.qr_code) && (o.totp.qr_code = `data:image/svg+xml;utf-8,${o.totp.qr_code}`), this._returnResult({ data: o, error: null })); 45130 }); 45131 } catch (t) { 45132 if (Re(t)) 45133 return this._returnResult({ data: null, error: t }); 45134 throw t; 45135 } 45136 } 45137 async _verify(e) { 45138 const t = async () => { 45139 try { 45140 return await this._useSession(async (i) => { 45141 var r; 45142 const { data: s, error: a } = i; 45143 if (a) 45144 return this._returnResult({ data: null, error: a }); 45145 const l = Object.assign({ challenge_id: e.challengeId }, "webauthn" in e ? { 45146 webauthn: Object.assign(Object.assign({}, e.webauthn), { credential_response: e.webauthn.type === "create" ? Tf(e.webauthn.credential_response) : Af(e.webauthn.credential_response) }) 45147 } : { code: e.code }), { data: o, error: c } = await He(this.fetch, "POST", `${this.url}/factors/${e.factorId}/verify`, { 45148 body: l, 45149 headers: this.headers, 45150 jwt: (r = s?.session) === null || r === void 0 ? void 0 : r.access_token 45151 }); 45152 return c ? this._returnResult({ data: null, error: c }) : (await this._saveSession(Object.assign({ expires_at: Math.round(Date.now() / 1e3) + o.expires_in }, o)), await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED", o), this._returnResult({ data: o, error: c })); 45153 }); 45154 } catch (i) { 45155 if (Re(i)) 45156 return this._returnResult({ data: null, error: i }); 45157 throw i; 45158 } 45159 }; 45160 return this.lock != null ? this._acquireLock(this.lockAcquireTimeout, t) : t(); 45161 } 45162 async _challenge(e) { 45163 const t = async () => { 45164 try { 45165 return await this._useSession(async (i) => { 45166 var r; 45167 const { data: s, error: a } = i; 45168 if (a) 45169 return this._returnResult({ data: null, error: a }); 45170 const l = await He(this.fetch, "POST", `${this.url}/factors/${e.factorId}/challenge`, { 45171 body: e, 45172 headers: this.headers, 45173 jwt: (r = s?.session) === null || r === void 0 ? void 0 : r.access_token 45174 }); 45175 if (l.error) 45176 return l; 45177 const { data: o } = l; 45178 if (o.type !== "webauthn") 45179 return { data: o, error: null }; 45180 switch (o.webauthn.type) { 45181 case "create": 45182 return { 45183 data: Object.assign(Object.assign({}, o), { webauthn: Object.assign(Object.assign({}, o.webauthn), { credential_options: Object.assign(Object.assign({}, o.webauthn.credential_options), { publicKey: Ef(o.webauthn.credential_options.publicKey) }) }) }), 45184 error: null 45185 }; 45186 case "request": 45187 return { 45188 data: Object.assign(Object.assign({}, o), { webauthn: Object.assign(Object.assign({}, o.webauthn), { credential_options: Object.assign(Object.assign({}, o.webauthn.credential_options), { publicKey: Mf(o.webauthn.credential_options.publicKey) }) }) }), 45189 error: null 45190 }; 45191 } 45192 }); 45193 } catch (i) { 45194 if (Re(i)) 45195 return this._returnResult({ data: null, error: i }); 45196 throw i; 45197 } 45198 }; 45199 return this.lock != null ? this._acquireLock(this.lockAcquireTimeout, t) : t(); 45200 } 45201 /** 45202 * {@see GoTrueMFAApi#challengeAndVerify} 45203 */ 45204 async _challengeAndVerify(e) { 45205 const { data: t, error: i } = await this._challenge({ 45206 factorId: e.factorId 45207 }); 45208 return i ? this._returnResult({ data: null, error: i }) : await this._verify({ 45209 factorId: e.factorId, 45210 challengeId: t.id, 45211 code: e.code 45212 }); 45213 } 45214 /** 45215 * {@see GoTrueMFAApi#listFactors} 45216 */ 45217 async _listFactors() { 45218 var e; 45219 const { data: { user: t }, error: i } = await this.getUser(); 45220 if (i) 45221 return { data: null, error: i }; 45222 const r = { 45223 all: [], 45224 phone: [], 45225 totp: [], 45226 webauthn: [] 45227 }; 45228 for (const s of (e = t?.factors) !== null && e !== void 0 ? e : []) 45229 r.all.push(s), s.status === "verified" && r[s.factor_type].push(s); 45230 return { 45231 data: r, 45232 error: null 45233 }; 45234 } 45235 /** 45236 * {@see GoTrueMFAApi#getAuthenticatorAssuranceLevel} 45237 */ 45238 async _getAuthenticatorAssuranceLevel(e) { 45239 var t, i, r, s; 45240 if (e)
45241 try { 45242 const { payload: f } = uo(e); 45243 let p = null; 45244 f.aal && (p = f.aal); 45245 let v = p; 45246 const { data: { user: m }, error: g } = await this.getUser(e); 45247 if (g) 45248 return this._returnResult({ data: null, error: g }); 45249 ((i = (t = m?.factors) === null || t === void 0 ? void 0 : t.filter((E) => E.status === "verified")) !== null && i !== void 0 ? i : []).length > 0 && (v = "aal2"); 45250 const x = f.amr || []; 45251 return { data: { currentLevel: p, nextLevel: v, currentAuthenticationMethods: x }, error: null }; 45252 } catch (f) { 45253 if (Re(f)) 45254 return this._returnResult({ data: null, error: f }); 45255 throw f; 45256 } 45257 const { data: { session: a }, error: l } = await this.getSession(); 45258 if (l) 45259 return this._returnResult({ data: null, error: l }); 45260 if (!a) 45261 return { 45262 data: { currentLevel: null, nextLevel: null, currentAuthenticationMethods: [] }, 45263 error: null 45264 }; 45265 const { payload: o } = uo(a.access_token); 45266 let c = null; 45267 o.aal && (c = o.aal); 45268 let u = c; 45269 ((s = (r = a.user.factors) === null || r === void 0 ? void 0 : r.filter((f) => f.status === "verified")) !== null && s !== void 0 ? s : []).length > 0 && (u = "aal2"); 45270 const d = o.amr || []; 45271 return { data: { currentLevel: c, nextLevel: u, currentAuthenticationMethods: d }, error: null }; 45272 } 45273 /** 45274 * Retrieves details about an OAuth authorization request. 45275 * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. 45276 * 45277 * Returns authorization details including client info, scopes, and user information. 45278 * If the response includes only a redirect_url field, it means consent was already given - the caller 45279 * should handle the redirect manually if needed. 45280 */ 45281 async _getAuthorizationDetails(e) { 45282 try { 45283 return await this._useSession(async (t) => { 45284 const { data: { session: i }, error: r } = t; 45285 return r ? this._returnResult({ data: null, error: r }) : i ? await He(this.fetch, "GET", `${this.url}/oauth/authorizations/${e}`, { 45286 headers: this.headers, 45287 jwt: i.access_token, 45288 xform: (s) => ({ data: s, error: null }) 45289 }) : this._returnResult({ data: null, error: new nn() }); 45290 }); 45291 } catch (t) { 45292 if (Re(t)) 45293 return this._returnResult({ data: null, error: t }); 45294 throw t; 45295 } 45296 } 45297 /** 45298 * Approves an OAuth authorization request. 45299 * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. 45300 */ 45301 async _approveAuthorization(e, t) { 45302 try { 45303 return await this._useSession(async (i) => { 45304 const { data: { session: r }, error: s } = i; 45305 if (s) 45306 return this._returnResult({ data: null, error: s }); 45307 if (!r) 45308 return this._returnResult({ data: null, error: new nn() }); 45309 const a = await He(this.fetch, "POST", `${this.url}/oauth/authorizations/${e}/consent`, { 45310 headers: this.headers, 45311 jwt: r.access_token, 45312 body: { action: "approve" }, 45313 xform: (l) => ({ data: l, error: null }) 45314 }); 45315 return a.data && a.data.redirect_url && hn() && !t?.skipBrowserRedirect && window.location.assign(a.data.redirect_url), a; 45316 }); 45317 } catch (i) { 45318 if (Re(i)) 45319 return this._returnResult({ data: null, error: i }); 45320 throw i; 45321 } 45322 } 45323 /** 45324 * Denies an OAuth authorization request. 45325 * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. 45326 */ 45327 async _denyAuthorization(e, t) { 45328 try { 45329 return await this._useSession(async (i) => { 45330 const { data: { session: r }, error: s } = i; 45331 if (s) 45332 return this._returnResult({ data: null, error: s }); 45333 if (!r) 45334 return this._returnResult({ data: null, error: new nn() }); 45335 const a = await He(this.fetch, "POST", `${this.url}/oauth/authorizations/${e}/consent`, { 45336 headers: this.headers, 45337 jwt: r.access_token, 45338 body: { action: "deny" }, 45339 xform: (l) => ({ data: l, error: null }) 45340 }); 45341 return a.data && a.data.redirect_url && hn() && !t?.skipBrowserRedirect && window.location.assign(a.data.redirect_url), a; 45342 }); 45343 } catch (i) { 45344 if (Re(i)) 45345 return this._returnResult({ data: null, error: i }); 45346 throw i; 45347 } 45348 } 45349 /** 45350 * Lists all OAuth grants that the authenticated user has authorized. 45351 * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. 45352 */ 45353 async _listOAuthGrants() { 45354 try { 45355 return await this._useSession(async (e) => { 45356 const { data: { session: t }, error: i } = e; 45357 return i ? this._returnResult({ data: null, error: i }) : t ? await He(this.fetch, "GET", `${this.url}/user/oauth/grants`, { 45358 headers: this.headers, 45359 jwt: t.access_token, 45360 xform: (r) => ({ data: r, error: null }) 45361 }) : this._returnResult({ data: null, error: new nn() }); 45362 }); 45363 } catch (e) { 45364 if (Re(e)) 45365 return this._returnResult({ data: null, error: e }); 45366 throw e; 45367 } 45368 } 45369 /** 45370 * Revokes a user's OAuth grant for a specific client. 45371 * Only relevant when the OAuth 2.1 server is enabled in Supabase Auth. 45372 */ 45373 async _revokeOAuthGrant(e) { 45374 try { 45375 return await this._useSession(async (t) => { 45376 const { data: { session: i }, error: r }
45376 = t; 45377 return r ? this._returnResult({ data: null, error: r }) : i ? (await He(this.fetch, "DELETE", `${this.url}/user/oauth/grants`, { 45378 headers: this.headers, 45379 jwt: i.access_token, 45380 query: { client_id: e.clientId }, 45381 noResolveJson: !0 45382 }), { data: {}, error: null }) : this._returnResult({ data: null, error: new nn() }); 45383 }); 45384 } catch (t) { 45385 if (Re(t)) 45386 return this._returnResult({ data: null, error: t }); 45387 throw t; 45388 } 45389 } 45390 async fetchJwk(e, t = { keys: [] }) { 45391 let i = t.keys.find((l) => l.kid === e); 45392 if (i) 45393 return i; 45394 const r = Date.now(); 45395 if (i = this.jwks.keys.find((l) => l.kid === e), i && this.jwks_cached_at + HT > r) 45396 return i; 45397 const { data: s, error: a } = await He(this.fetch, "GET", `${this.url}/.well-known/jwks.json`, { 45398 headers: this.headers 45399 }); 45400 if (a) 45401 throw a; 45402 return !s.keys || s.keys.length === 0 || (this.jwks = s, this.jwks_cached_at = r, i = s.keys.find((l) => l.kid === e), !i) ? null : i; 45403 } 45404 /** 45405 * Extracts the JWT claims present in the access token by first verifying the 45406 * JWT against the server's JSON Web Key Set endpoint 45407 * `/.well-known/jwks.json` which is often cached, resulting in significantly 45408 * faster responses. Prefer this method over {@link #getUser} which always 45409 * sends a request to the Auth server for each JWT. 45410 * 45411 * If the project is not using an asymmetric JWT signing key (like ECC or 45412 * RSA) it always sends a request to the Auth server (similar to {@link 45413 * #getUser}) to verify the JWT. 45414 * 45415 * @param jwt An optional specific JWT you wish to verify, not the one you 45416 * can obtain from {@link #getSession}. 45417 * @param options Various additional options that allow you to customize the 45418 * behavior of this method. 45419 * 45420 * @category Auth 45421 * 45422 * @remarks 45423 * - Parses the user's [access token](/docs/guides/auth/sessions#access-token-jwt-claims) as a [JSON Web Token (JWT)](/docs/guides/auth/jwts) and returns its components if valid and not expired. 45424 * - If your project is using asymmetric JWT signing keys, then the verification is done locally usually without a network request using the [WebCrypto API](https://developer.mozilla.org/en-US/docs/Web/API/Web_Crypto_API). 45425 * - A network request is sent to your project's JWT signing key discovery endpoint `https://project-id.supabase.co/auth/v1/.well-known/jwks.json`, which is cached locally. If your environment is ephemeral, such as a Lambda function that is destroyed after every request, a network request will be sent for each new invocation. Supabase provides a network-edge cache providing fast responses for these situations. 45426 * - If the user's access token is about to expire when calling this function, the user's session will first be refreshed before validating the JWT. 45427 * - If your project is using a symmetric secret to sign the JWT, it always sends a request similar to `getUser()` to validate the JWT at the server before returning the decoded token. This is also used if the WebCrypto API is not available in the environment. Make sure you polyfill it in such situations. 45428 * - The returned claims can be customized per project using the [Custom Access Token Hook](/docs/guides/auth/auth-hooks/custom-access-token-hook). 45429 * 45430 * @example Get JWT claims, header and signature 45431 * ```js 45432 * const { data, error } = await supabase.auth.getClaims() 45433 * ``` 45434 * 45435 * @exampleResponse Get JWT claims, header and signature 45436 * ```json 45437 * { 45438 * "data": { 45439 * "claims": { 45440 * "aal": "aal1", 45441 * "amr": [{ 45442 * "method": "email", 45443 * "timestamp": 1715766000 45444 * }], 45445 * "app_metadata": {}, 45446 * "aud": "authenticated", 45447 * "email": "[email protected]", 45448 * "exp": 1715769600, 45449 * "iat": 1715766000, 45450 * "is_anonymous": false, 45451 * "iss": "https://project-id.supabase.co/auth/v1", 45452 * "phone": "+13334445555", 45453 * "role": "authenticated", 45454 * "session_id": "11111111-1111-1111-1111-111111111111", 45455 * "sub": "11111111-1111-1111-1111-111111111111", 45456 * "user_metadata": {} 45457 * }, 45458 * "header": { 45459 * "alg": "RS256", 45460 * "typ": "JWT", 45461 * "kid": "11111111-1111-1111-1111-111111111111" 45462 * }, 45463 * "signature": [/** Uint8Array *\/], 45464 * }, 45465 * "error": null 45466 * } 45467 * ``` 45468 */ 45469 async getClaims(e, t = {}) { 45470 try { 45471 let i = e; 45472 if (!i) { 45473 const { data: f, error: p }
45473 = await this.getSession(); 45474 if (p || !f.session) 45475 return this._returnResult({ data: null, error: p }); 45476 i = f.session.access_token; 45477 } 45478 const { header: r, payload: s, signature: a, raw: { header: l, payload: o } } = uo(i); 45479 if (!t?.allowExpired) 45480 try { 45481 u1(s.exp); 45482 } catch (f) { 45483 throw new Oo(f instanceof Error ? f.message : "JWT validation failed"); 45484 } 45485 const c = !r.alg || r.alg.startsWith("HS") || !r.kid || !("crypto" in globalThis && "subtle" in globalThis.crypto) ? null : await this.fetchJwk(r.kid, t?.keys ? { keys: t.keys } : t?.jwks); 45486 if (!c) { 45487 const { error: f } = await this.getUser(i); 45488 if (f) 45489 throw f; 45490 return { 45491 data: { 45492 claims: s, 45493 header: r, 45494 signature: a 45495 }, 45496 error: null 45497 }; 45498 } 45499 const u = h1(r.alg), h = await crypto.subtle.importKey("jwk", c, u, !0, [ 45500 "verify" 45501 ]); 45502 if (!await crypto.subtle.verify(u, h, a, JT(`${l}.${o}`))) 45503 throw new Oo("Invalid JWT signature"); 45504 return { 45505 data: { 45506 claims: s, 45507 header: r, 45508 signature: a 45509 }, 45510 error: null 45511 }; 45512 } catch (i) { 45513 if (Re(i)) 45514 return this._returnResult({ data: null, error: i }); 45515 throw i; 45516 } 45517 } 45518 // --- Passkey Methods --- 45519 /** 45520 * Sign in with a passkey. Handles the full WebAuthn ceremony: 45521 * 1. Fetches authentication challenge from server
45522 * 2. Prompts user via navigator.credentials.get() 45523 * 3. Verifies credential with server and creates session 45524 * 45525 * Requires `auth.experimental.passkey: true`. 45526 * 45527 * @category Auth 45528 */ 45529 async signInWithPasskey(e) { 45530 var t, i, r; 45531 Kn(this.experimental); 45532 try { 45533 if (!Bo()) 45534 return this._returnResult({ 45535 data: null, 45536 error: new ei("Browser does not support WebAuthn", null) 45537 }); 45538 const { data: s, error: a } = await this._startPasskeyAuthentication({ 45539 options: { captchaToken: (t = e?.options) === null || t === void 0 ? void 0 : t.captchaToken } 45540 }); 45541 if (a || !s) 45542 return this._returnResult({ data: null, error: a }); 45543 const l = Mf(s.options), o = (r = (i = e?.options) === null || i === void 0 ? void 0 : i.signal) !== null && r !== void 0 ? r : gu.createNewAbortSignal(), { data: c, error: u } = await Bm({ 45544 publicKey: l, 45545 signal: o 45546 }); 45547 if (u || !c) 45548 return this._returnResult({ 45549 data: null, 45550 error: u ?? new ei("WebAuthn ceremony failed", null) 45551 }); 45552 const h = Af(c); 45553 return this._verifyPasskeyAuthentication({ 45554 challengeId: s.challenge_id, 45555 credential: h 45556 }); 45557 } catch (s) { 45558 if (Re(s)) 45559 return this._returnResult({ data: null, error: s }); 45560 throw s; 45561 } 45562 } 45563 /** 45564 * Register a passkey for the current authenticated user. Handles the full WebAuthn ceremony: 45565 * 1. Fetches registration challenge from server
45566 * 2. Prompts user via navigator.credentials.create() 45567 * 3. Verifies credential with server 45568 * 45569 * Requires an active session. Requires `auth.experimental.passkey: true`. 45570 * 45571 * @category Auth 45572 */ 45573 async registerPasskey(e) { 45574 var t, i; 45575 Kn(this.experimental); 45576 try { 45577 if (!Bo()) 45578 return this._returnResult({ 45579 data: null, 45580 error: new ei("Browser does not support WebAuthn", null) 45581 }); 45582 const { data: r, error: s } = await this._startPasskeyRegistration(); 45583 if (s || !r) 45584 return this._returnResult({ data: null, error: s }); 45585 const a = Ef(r.options), l = (i = (t = e?.options) === null || t === void 0 ? void 0 : t.signal) !== null && i !== void 0 ? i : gu.createNewAbortSignal(), { data: o, error: c } = await Fm({ 45586 publicKey: a, 45587 signal: l 45588 }); 45589 if (c || !o) 45590 return this._returnResult({ 45591 data: null, 45592 error: c ?? new ei("WebAuthn ceremony failed", null) 45593 }); 45594 const u = Tf(o); 45595 return this._verifyPasskeyRegistration({ 45596 challengeId: r.challenge_id, 45597 credential: u 45598 }); 45599 } catch (r) { 45600 if (Re(r)) 45601 return this._returnResult({ data: null, error: r }); 45602 throw r; 45603 } 45604 } 45605 /** 45606 * Start passkey registration for the current authenticated user. 45607 * Returns WebAuthn credential creation options to pass to navigator.credentials.create(). 45608 */ 45609 async _startPasskeyRegistration() { 45610 Kn(this.experimental); 45611 try { 45612 return await this._useSession(async (e) => { 45613 const { data: { session: t }, error: i } = e; 45614 if (i) 45615 return this._returnResult({ data: null, error: i }); 45616 if (!t) 45617 return this._returnResult({ data: null, error: new nn() }); 45618 const { data: r, error: s } = await He(this.fetch, "POST", `${this.url}/passkeys/registration/options`, { 45619 headers: this.headers, 45620 jwt: t.access_token, 45621 body: {} 45622 }); 45623 return s ? this._returnResult({ data: null, error: s }) : this._returnResult({ data: r, error: null }); 45624 }); 45625 } catch (e) { 45626 if (Re(e)) 45627 return this._returnResult({ data: null, error: e }); 45628 throw e; 45629 } 45630 } 45631 /** 45632 * Verify passkey registration with the credential response. 45633 * The credentialResponse should be the serialized output of navigator.credentials.create(). 45634 */ 45635 async _verifyPasskeyRegistration(e) { 45636 Kn(this.experimental); 45637 try { 45638 return await this._useSession(async (t) => { 45639 const { data: { session: i }, error: r } = t; 45640 if (r) 45641 return this._returnResult({ data: null, error: r }); 45642 if (!i) 45643 return this._returnResult({ data: null, error: new nn() }); 45644 const { data: s, error: a } = await He(this.fetch, "POST", `${this.url}/passkeys/registration/verify`, { 45645 headers: this.headers, 45646 jwt: i.access_token, 45647 body: { 45648 challenge_id: e.challengeId, 45649 credential: e.credential 45650 } 45651 }); 45652 return a ? this._returnResult({ data: null, error: a }) : this._returnResult({ data: s, error: null }); 45653 }); 45654 } catch (t) { 45655 if (Re(t)) 45656 return this._returnResult({ data: null, error: t }); 45657 throw t; 45658 } 45659 } 45660 /** 45661 * Start passkey authentication. 45662 * Returns WebAuthn credential request options to pass to navigator.credentials.get(). 45663 */ 45664 async _startPasskeyAuthentication(e) { 45665 var t; 45666 Kn(this.experimental); 45667 try { 45668 const { data: i, error: r } = await He(this.fetch, "POST", `${this.url}/passkeys/authentication/options`, { 45669 headers: this.headers, 45670 body: { 45671 gotrue_meta_security: { captcha_token: (t = e?.options) === null || t === void 0 ? void 0 : t.captchaToken } 45672 } 45673 }); 45674 return r ? this._returnResult({ data: null, error: r }) : this._returnResult({ data: i, error: null }); 45675 } catch (i) { 45676 if (Re(i)) 45677 return this._returnResult({ data: null, error: i }); 45678 throw i; 45679 } 45680 } 45681 /** 45682 * Verify passkey authentication and create a session. 45683 * The credential should be the serialized output of navigator.credentials.get(). 45684 */ 45685 async _verifyPasskeyAuthentication(e) { 45686 Kn(this.experimental); 45687 try { 45688 const { data: t, error: i } = await He(this.fetch, "POST", `${this.url}/passkeys/authentication/verify`, { 45689 headers: this.headers, 45690 body: { 45691 challenge_id: e.challengeId, 45692 credential: e.credential 45693 }, 45694 xform: Bn 45695 }); 45696 return i ? this._returnResult({ data: null, error: i }) : (t.session && (await this._saveSession(t.session), await this._notifyAllSubscribers("SIGNED_IN", t.session)), this._returnResult({ data: t, error: null })); 45697 } catch (t) { 45698 if (Re(t)) 45699 return this._returnResult({ data: null, error: t }); 45700 throw t; 45701 } 45702 } 45703 /** 45704 * List all passkeys for the current user. 45705 */ 45706 async _listPasskeys() { 45707 Kn(this.experimental); 45708 try { 45709 return await this._useSession(async (e) => { 45710 const { data: { session: t }, error: i } = e; 45711 if (i) 45712 return this._returnResult({ data: null, error: i }); 45713 if (!t) 45714 return this._returnResult({ data: null, error: new nn() }); 45715 const { data: r, error: s } = await He(this.fetch, "GET", `${this.url}/passkeys`, { 45716 headers: this.headers, 45717 jwt: t.access_token, 45718 xform: (a) => ({ data: a, error: null }) 45719 }); 45720 return s ? this._returnResult({ data: null, error: s }) : this._returnResult({ data: r, error: null }); 45721 }); 45722 } catch (e) { 45723 if (Re(e)) 45724 return this._returnResult({ data: null, error: e }); 45725 throw e; 45726 } 45727 } 45728 /** 45729 * Update a passkey. 45730 */ 45731 async _updatePasskey(e) { 45732 Kn(this.experimental); 45733 try { 45734 return await this._useSession(async (t) => { 45735 const { data: { session: i }, error: r }
45735 = t; 45736 if (r) 45737 return this._returnResult({ data: null, error: r }); 45738 if (!i) 45739 return this._returnResult({ data: null, error: new nn() }); 45740 const { data: s, error: a } = await He(this.fetch, "PATCH", `${this.url}/passkeys/${e.passkeyId}`, { 45741 headers: this.headers, 45742 jwt: i.access_token, 45743 body: { friendly_name: e.friendlyName } 45744 }); 45745 return a ? this._returnResult({ data: null, error: a }) : this._returnResult({ data: s, error: null }); 45746 }); 45747 } catch (t) { 45748 if (Re(t)) 45749 return this._returnResult({ data: null, error: t }); 45750 throw t; 45751 } 45752 } 45753 /** 45754 * Delete a passkey. 45755 */ 45756 async _deletePasskey(e) { 45757 Kn(this.experimental); 45758 try { 45759 return await this._useSession(async (t) => { 45760 const { data: { session: i }, error: r } = t; 45761 if (r) 45762 return this._returnResult({ data: null, error: r }); 45763 if (!i) 45764 return this._returnResult({ data: null, error: new nn() }); 45765 const { error: s } = await He(this.fetch, "DELETE", `${this.url}/passkeys/${e.passkeyId}`, { 45766 headers: this.headers, 45767 jwt: i.access_token, 45768 noResolveJson: !0 45769 }); 45770 return s ? this._returnResult({ data: null, error: s }) : this._returnResult({ data: null, error: null }); 45771 }); 45772 } catch (t) { 45773 if (Re(t)) 45774 return this._returnResult({ data: null, error: t }); 45775 throw t; 45776 } 45777 } 45778} 45779ma.nextInstanceID = {}; 45780const U1 = ma, O1 = "2.108.1"; 45781let Ks = "", Ho; 45782if (typeof Deno < "u") { 45783 var Kl; 45784 Ks = "deno", Ho = (Kl = Deno.version) === null || Kl === void 0 ? void 0 : Kl.deno; 45785} else if (typeof document < "u") Ks = "web"; 45786else if (typeof navigator < "u" && navigator.product === "ReactNative") Ks = "react-native"; 45787else { 45788 var Jl; 45789 Ks = "node", Ho = typeof process < "u" ? (Jl = process.version) === null || Jl === void 0 ? void 0 : Jl.replace(/^v/, "") : void 0; 45790} 45791const zm = [`runtime=${Ks}`]; 45792Ho && zm.push(`runtime-version=${Ho}`); 45793const k1 = { "X-Client-Info": `supabase-js/${O1}; ${zm.join("; ")}` }, F1 = { headers: k1 }, B1 = { schema: "public" }, z1 = { 45794 autoRefreshToken: !0, 45795 persistSession: !0, 45796 detectSessionInUrl: !0, 45797 flowType: "implicit" 45798}, H1 = {}, G1 = { 45799 enabled: !1, 45800 respectSamplingDecision: !0 45801}; 45802function V1(n, e, t, i) { 45803 function r(s) { 45804 return s instanceof t ? s : new t(function(a) { 45805 a(s); 45806 }); 45807 } 45808 return new (t || (t = Promise))(function(s, a) { 45809 function l(u) { 45810 try { 45811 c(i.next(u)); 45812 } catch (h) { 45813 a(h); 45814 } 45815 } 45816 function o(u) { 45817 try { 45818 c(i.throw(u)); 45819 } catch (h) { 45820 a(h); 45821 } 45822 } 45823 function c(u) { 45824 u.done ? s(u.value) : r(u.value).then(l, o); 45825 } 45826 c((i = i.apply(n, [])).next()); 45827 }); 45828} 45829let Zl = null; 45830const W1 = "@opentelemetry/api"; 45831function $1() { 45832 return Zl === null && (Zl = import( 45833 /* webpackIgnore: true */ 45834 /* turbopackIgnore: true */ 45835 /* @vite-ignore */ 45836 W1 45837 ).catch(() => null)), Zl; 45838} 45839function j1() { 45840 return V1(this, void 0, void 0, function* () { 45841 try { 45842 const n = yield $1(); 45843 if (!n || !n.propagation || !n.context) return null; 45844 const e = {}; 45845 n.propagation.inject(n.context.active(), e); 45846 const t = e.traceparent; 45847 return t ? { 45848 traceparent: t, 45849 tracestate: e.tracestate, 45850 baggage: e.baggage 45851 } : null; 45852 } catch { 45853 return null; 45854 } 45855 }); 45856} 45857function X1(n) { 45858 if (!n || typeof n != "string") return null; 45859 const e = n.split("-"); 45860 if (e.length !== 4) return null; 45861 const [t, i, r, s] = e; 45862 if (t.length !== 2 || i.length !== 32 || r.length !== 16 || s.length !== 2) return null; 45863 const a = /^[0-9a-f]+$/i; 45864 return !a.test(t) || !a.test(i) || !a.test(r) || !a.test(s) || i === "00000000000000000000000000000000" || r === "0000000000000000" ? null : { 45865 version: t, 45866 traceId: i, 45867 parentId: r, 45868 traceFlags: s, 45869 isSampled: (parseInt(s, 16) & 1) === 1 45870 }; 45871} 45872function q1(n, e) { 45873 if (!n || !e || e.length === 0) return !1; 45874 let t; 45875 if (n instanceof URL) t = n; 45876 else try { 45877 t = new URL(n); 45878 } catch { 45879 return !1; 45880 } 45881 for (const i of e) try { 45882 if (typeof i == "string") { 45883 if (Y1(t.hostname, i)) return !0; 45884 } else if (i instanceof RegExp) { 45885 if (i.test(t.hostname)) return !0; 45886 } else if (typeof i == "function" && i(t)) 45887 return !0; 45888 } catch { 45889 continue; 45890 } 45891 return !1; 45892} 45893function Y1(n, e) { 45894 if (e === n) return !0; 45895 if (e.startsWith("*.")) { 45896 const t = e.slice(2); 45897 if (n.endsWith(t) && (n === t || n.endsWith("." + t))) 45898 return !0; 45899 } 45900 return !1; 45901} 45902function K1(n) { 45903 const e = []; 45904 try { 45905 const t = new URL(n); 45906 e.push(t.hostname); 45907 } catch { 45908 } 45909 return e.push("*.supabase.co", "*.supabase.in"), e.push("localhost", "127.0.0.1", "[::1]"), e; 45910} 45911function ga(n) { 45912 "@babel/helpers - typeof"; 45913 return ga = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(e) { 45914 return typeof e; 45915 }
45915 : function(e) { 45916 return e && typeof Symbol == "function" && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e; 45917 }, ga(n); 45918} 45919function J1(n, e) { 45920 if (ga(n) != "object" || !n) return n; 45921 var t = n[Symbol.toPrimitive]; 45922 if (t !== void 0) { 45923 var i = t.call(n, e); 45924 if (ga(i) != "object") return i; 45925 throw new TypeError("@@toPrimitive must return a primitive value."); 45926 } 45927 return (e === "string" ? String : Number)(n); 45928} 45929function Z1(n) { 45930 var e = J1(n, "string"); 45931 return ga(e) == "symbol" ? e : e + ""; 45932} 45933function Q1(n, e, t) { 45934 return (e = Z1(e)) in n ? Object.defineProperty(n, e, { 45935 value: t, 45936 enumerable: !0, 45937 configurable: !0, 45938 writable: !0 45939 }) : n[e] = t, n; 45940} 45941function Rf(n, e) { 45942 var t = Object.keys(n); 45943 if (Object.getOwnPropertySymbols) { 45944 var i = Object.getOwnPropertySymbols(n); 45945 e && (i = i.filter(function(r) { 45946 return Object.getOwnPropertyDescriptor(n, r).enumerable; 45947 })), t.push.apply(t, i); 45948 } 45949 return t; 45950} 45951function Ht(n) { 45952 for (var e = 1; e < arguments.length; e++) { 45953 var t = arguments[e] != null ? arguments[e] : {}; 45954 e % 2 ? Rf(Object(t), !0).forEach(function(i) { 45955 Q1(n, i, t[i]); 45956 }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(n, Object.getOwnPropertyDescriptors(t)) : Rf(Object(t)).forEach(function(i) { 45957 Object.defineProperty(n, i, Object.getOwnPropertyDescriptor(t, i)); 45958 }); 45959 } 45960 return n; 45961} 45962const eA = (n) => n ? (...e) => n(...e) : (...e) => fetch(...e), tA = () => Headers, nA = (n, e, t, i, r) => { 45963 const s = eA(i), a = tA(), l = r?.enabled === !0, o = r?.respectSamplingDecision !== !1, c = l ? K1(e) : null; 45964 return async (u, h) => { 45965 var d; 45966 const f = (d = await t()) !== null && d !== void 0 ? d : n; 45967 let p = new a(h?.headers); 45968 if (p.has("apikey") || p.set("apikey", n), p.has("Authorization") || p.set("Authorization", `Bearer ${f}`), c) { 45969 const v = await iA(u, c, o); 45970 v && (v.traceparent && !p.has("traceparent") && p.set("traceparent", v.traceparent), v.tracestate && !p.has("tracestate") && p.set("tracestate", v.tracestate), v.baggage && !p.has("baggage") && p.set("baggage", v.baggage)); 45971 } 45972 return s(u, Ht(Ht({}, h), {}, { headers: p })); 45973 }; 45974}; 45975async function iA(n, e, t) { 45976 if (!q1(typeof n == "string" || n instanceof URL ? n : n.url, e)) return null; 45977 const i = await j1(); 45978 if (!i || !i.traceparent) return null; 45979 if (t) { 45980 const r = X1(i.traceparent); 45981 if (r && !r.isSampled) return null; 45982 } 45983 return i; 45984} 45985function Cf(n) { 45986 return typeof n == "boolean" ? { enabled: n } : n; 45987} 45988function rA(n) { 45989 return n.endsWith("/") ? n : n + "/"; 45990} 45991function sA(n, e) { 45992 var t, i, r, s, a, l; 45993 const { db: o, auth: c, realtime: u, global: h } = n, { db: d, auth: f, realtime: p, global: v } = e, m = Cf(n.tracePropagation), g = Cf(e.tracePropagation), _ = { 45994 db: Ht(Ht({}, d), o), 45995 auth: Ht(Ht({}, f), c), 45996 realtime: Ht(Ht({}, p), u), 45997 storage: {}, 45998 global: Ht(Ht(Ht({}, v), h), {}, { headers: Ht(Ht({}, (t = v?.headers) !== null && t !== void 0 ? t : {}), (i = h?.headers) !== null && i !== void 0 ? i : {}) }), 45999 tracePropagation: { 46000 enabled: (r = (s = m?.enabled) !== null && s !== void 0 ? s : g?.enabled) !== null && r !== void 0 ? r : !1, 46001 respectSamplingDecision: (a = (l = m?.respectSamplingDecision) !== null && l !== void 0 ? l : g?.respectSamplingDecision) !== null && a !== void 0 ? a : !0 46002 }, 46003 accessToken: async () => "" 46004 }; 46005 return n.accessToken ? _.accessToken = n.accessToken : delete _.accessToken, _; 46006} 46007function aA(n) { 46008 const e = n?.trim(); 46009 if (!e) throw new Error("supabaseUrl is required."); 46010 if (!e.match(/^https?:\/\//i)) throw new Error("Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL."); 46011 try { 46012 return new URL(rA(e)); 46013 } catch { 46014 throw Error("Invalid supabaseUrl: Provided URL is malformed."); 46015 } 46016} 46017var oA = class extends U1 { 46018 constructor(n) { 46019 super(n); 46020 } 46021}, lA = class { 46022 /** 46023 * Create a new client for use in the browser. 46024 * 46025 * @category Initializing 46026 * 46027 * @param supabaseUrl The unique Supabase URL which is supplied when you create a new project in your project dashboard.
46028 * @param supabaseKey The unique Supabase Key which is supplied when you create a new project in your project dashboard. 46029 * @param options.db.schema You can switch in between schemas. The schema needs to be on the list of exposed schemas inside Supabase. 46030 * @param options.auth.autoRefreshToken Set to "true" if you want to automatically refresh the token before expiring. 46031 * @param options.auth.persistSession Set to "true" if you want to automatically save the user session into local storage. 46032 * @param options.auth.detectSessionInUrl Set to "true" if you want to automatically detects OAuth grants in the URL and signs in the user. 46033 * @param options.realtime Options passed along to realtime-js constructor. 46034 * @param options.storage Options passed along to the storage-js constructor. 46035 * @param options.global.fetch A custom fetch implementation. 46036 * @param options.global.headers Any additional headers to send with each network request. 46037 * 46038 * @example Creating a client 46039 * ```js 46040 * import { createClient } from '@supabase/supabase-js' 46041 * 46042 * // Create a single supabase client for interacting with your database 46043 * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key') 46044 * ``` 46045 * 46046 * @example With a custom domain 46047 * ```js 46048 * import { createClient } from '@supabase/supabase-js' 46049 * 46050 * // Use a custom domain as the supabase URL 46051 * const supabase = createClient('https://my-custom-domain.com', 'your-publishable-key') 46052 * ``` 46053 * 46054 * @example With additional parameters 46055 * ```js 46056 * import { createClient } from '@supabase/supabase-js' 46057 * 46058 * const options = { 46059 * db: { 46060 * schema: 'public', 46061 * }, 46062 * auth: { 46063 * autoRefreshToken: true, 46064 * persistSession: true, 46065 * detectSessionInUrl: true 46066 * }, 46067 * global: { 46068 * headers: { 'x-my-custom-header': 'my-app-name' }, 46069 * }, 46070 * } 46071 * const supabase = createClient("https://xyzcompany.supabase.co", "your-publishable-key", options) 46072 * ``` 46073 * 46074 * @exampleDescription With custom schemas 46075 * By default the API server points to the `public` schema. You can enable other database schemas within the Dashboard. 46076 * Go to [Settings > API > Exposed schemas](/dashboard/project/_/settings/api) and add the schema which you want to expose to the API. 46077 * 46078 * Note: each client connection can only access a single schema, so the code above can access the `other_schema` schema but cannot access the `public` schema. 46079 * 46080 * @example With custom schemas 46081 * ```js 46082 * import { createClient } from '@supabase/supabase-js' 46083 * 46084 * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key', { 46085 * // Provide a custom schema. Defaults to "public". 46086 * db: { schema: 'other_schema' } 46087 * }) 46088 * ``` 46089 * 46090 * @exampleDescription Custom fetch implementation 46091 * `supabase-js` uses the [`cross-fetch`](https://www.npmjs.com/package/cross-fetch) library to make HTTP requests, 46092 * but an alternative `fetch` implementation can be provided as an option. 46093 * This is most useful in environments where `cross-fetch` is not compatible (for instance Cloudflare Workers). 46094 * 46095 * @example Custom fetch implementation 46096 * ```js 46097 * import { createClient } from '@supabase/supabase-js' 46098 * 46099 * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key', { 46100 * global: { fetch: fetch.bind(globalThis) } 46101 * }) 46102 * ``` 46103 * 46104 * @exampleDescription React Native options with AsyncStorage 46105 * For React Native we recommend using `AsyncStorage` as the storage implementation for Supabase Auth. 46106 * 46107 * @example React Native options with AsyncStorage 46108 * ```js 46109 * import 'react-native-url-polyfill/auto' 46110 * import { createClient } from '@supabase/supabase-js' 46111 * import AsyncStorage from "@react-native-async-storage/async-storage"; 46112 * 46113 * const supabase = createClient("https://xyzcompany.supabase.co", "your-publishable-key", { 46114 * auth: { 46115 * storage: AsyncStorage, 46116 * autoRefreshToken: true, 46117 * persistSession: true, 46118 * detectSessionInUrl: false, 46119 * }, 46120 * }); 46121 * ``` 46122 * 46123 * @exampleDescription React Native options with Expo SecureStore 46124 * If you wish to encrypt the user's session information, you can use `aes-js` and store the encryption key in Expo SecureStore. 46125 * The `aes-js` library, a reputable JavaScript-only implementation of the AES encryption algorithm in CTR mode. 46126 * A new 256-bit encryption key is generated using the `react-native-get-random-values` library. 46127 * This key is stored inside Expo's SecureStore, while the value is encrypted and placed inside AsyncStorage. 46128 * 46129 * Please make sure that: 46130 * - You keep the `expo-secure-store`, `aes-js` and `react-native-get-random-values` libraries up-to-date. 46131 * - Choose the correct [`SecureStoreOptions`](https://docs.expo.dev/versions/latest/sdk/securestore/#securestoreoptions) for your app's needs. 46132 * E.g. [`SecureStore.WHEN_UNLOCKED`](https://docs.expo.dev/versions/latest/sdk/securestore/#securestorewhen_unlocked) regulates when the data can be accessed. 46133 * - Carefully consider optimizations or other modifications to the above example, as those can lead to introducing subtle security vulnerabilities. 46134 * 46135 * @example React Native options with Expo SecureStore 46136 * ```ts 46137 * import 'react-native-url-polyfill/auto' 46138 * import { createClient } from '@supabase/supabase-js' 46139 * import AsyncStorage from '@react-native-async-storage/async-storage'; 46140 * import * as SecureStore from 'expo-secure-store';
46141 * import * as aesjs from 'aes-js'; 46142 * import 'react-native-get-random-values'; 46143 * 46144 * // As Expo's SecureStore does not support values larger than 2048 46145 * // bytes, an AES-256 key is generated and stored in SecureStore, while 46146 * // it is used to encrypt/decrypt values stored in AsyncStorage. 46147 * class LargeSecureStore { 46148 * private async _encrypt(key: string, value: string) { 46149 * const encryptionKey = crypto.getRandomValues(new Uint8Array(256 / 8)); 46150 * 46151 * const cipher = new aesjs.ModeOfOperation.ctr(encryptionKey, new aesjs.Counter(1)); 46152 * const encryptedBytes = cipher.encrypt(aesjs.utils.utf8.toBytes(value)); 46153 * 46154 * await SecureStore.setItemAsync(key, aesjs.utils.hex.fromBytes(encryptionKey)); 46155 * 46156 * return aesjs.utils.hex.fromBytes(encryptedBytes); 46157 * } 46158 * 46159 * private async _decrypt(key: string, value: string) { 46160 * const encryptionKeyHex = await SecureStore.getItemAsync(key); 46161 * if (!encryptionKeyHex) { 46162 * return encryptionKeyHex; 46163 * } 46164 * 46165 * const cipher = new aesjs.ModeOfOperation.ctr(aesjs.utils.hex.toBytes(encryptionKeyHex), new aesjs.Counter(1)); 46166 * const decryptedBytes = cipher.decrypt(aesjs.utils.hex.toBytes(value)); 46167 * 46168 * return aesjs.utils.utf8.fromBytes(decryptedBytes); 46169 * } 46170 * 46171 * async getItem(key: string) { 46172 * const encrypted = await AsyncStorage.getItem(key); 46173 * if (!encrypted) { return encrypted; } 46174 * 46175 * return await this._decrypt(key, encrypted); 46176 * } 46177 * 46178 * async removeItem(key: string) { 46179 * await AsyncStorage.removeItem(key); 46180 * await SecureStore.deleteItemAsync(key); 46181 * } 46182 * 46183 * async setItem(key: string, value: string) { 46184 * const encrypted = await this._encrypt(key, value); 46185 * 46186 * await AsyncStorage.setItem(key, encrypted); 46187 * } 46188 * } 46189 * 46190 * const supabase = createClient("https://xyzcompany.supabase.co", "your-publishable-key", { 46191 * auth: { 46192 * storage: new LargeSecureStore(), 46193 * autoRefreshToken: true, 46194 * persistSession: true, 46195 * detectSessionInUrl: false, 46196 * }, 46197 * }); 46198 * ``` 46199 * 46200 * @example With a database query 46201 * ```ts 46202 * import { createClient } from '@supabase/supabase-js' 46203 * 46204 * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key') 46205 * 46206 * const { data } = await supabase.from('profiles').select('*') 46207 * ``` 46208 * 46209 * @exampleDescription With OpenTelemetry tracing 46210 * Opt in to W3C trace context propagation so the `trace_id` from your 46211 * client-side spans is attached to Supabase requests and appears in API 46212 * Gateway and Edge Function logs. Requires `@opentelemetry/api` to be 46213 * installed in your application. See [Tracing with the JS SDK](https://supabase.com/docs/guides/telemetry/client-side-tracing). 46214 * 46215 * @example With OpenTelemetry tracing 46216 * ```ts 46217 * import { createClient } from '@supabase/supabase-js' 46218 * import { trace } from '@opentelemetry/api' 46219 * 46220 * const supabase = createClient('https://xyzcompany.supabase.co', 'your-publishable-key', { 46221 * tracePropagation: true, 46222 * }) 46223 * 46224 * const tracer = trace.getTracer('my-app') 46225 * 46226 * await tracer.startActiveSpan('fetch-users', async (span) => { 46227 * // Outgoing request carries the active trace context. 46228 * const { data, error } = await supabase.from('users').select('*') 46229 * span.end() 46230 * }) 46231 * ``` 46232 */ 46233 constructor(n, e, t) { 46234 var i, r; 46235 this.supabaseUrl = n, this.supabaseKey = e; 46236 const s = aA(n); 46237 if (!e) throw new Error("supabaseKey is required."); 46238 this.realtimeUrl = new URL("realtime/v1", s), this.realtimeUrl.protocol = this.realtimeUrl.protocol.replace("http", "ws"), this.authUrl = new URL("auth/v1", s), this.storageUrl = new URL("storage/v1", s), this.functionsUrl = new URL("functions/v1", s); 46239 const a = `sb-${s.hostname.split(".")[0]}-auth-token`, l = { 46240 db: B1, 46241 realtime: H1, 46242 auth: Ht(Ht({}, z1), {}, { storageKey: a }), 46243 global: F1, 46244 tracePropagation: G1 46245 }, o = sA(t ?? {}, l); 46246 if (this.settings = o, this.storageKey = (i = o.auth.storageKey) !== null && i !== void 0 ? i : "", this.headers = (r = o.global.headers) !== null && r !== void 0 ? r : {}, o.accessToken) 46247 this.accessToken = o.accessToken, this.auth = new Proxy({}, { get: (u, h) => { 46248 throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(h)} is not possible`); 46249 } }); 46250 else { 46251 var c; 46252 this.auth = this._initSupabaseAuthClient((c = o.auth) !== null && c !== void 0 ? c : {}, this.headers, o.global.fetch); 46253 } 46254 this.fetch = nA(e, n, this._getAccessToken.bind(this), o.global.fetch, o.tracePropagation), this.realtime = this._initRealtimeClient(Ht({ 46255 headers: this.headers, 46256 accessToken: this._getAccessToken.bind(this), 46257 fetch: this.fetch 46258 }, o.realtime)), this.accessToken && Promise.resolve(this.accessToken()).then((u) => this.realtime.setAuth(u)).catch((u) => console.warn("Failed to set initial Realtime auth token:", u)), this.rest = new SM(new URL("rest/v1", s).href, { 46259 headers: this.headers, 46260 schema: o.db.schema, 46261 fetch: this.fetch, 46262 timeout: o.db.timeout, 46263 urlLengthLimit: o.db.urlLengthLimit 46264 }), this.storage = new OT(this.storageUrl.href, this.headers, this.fetch, t?.storage), o.accessToken || this._listenForAuthEvents(); 46265 } 46266 /** 46267 * Supabase Functions allows you to deploy and invoke edge functions. 46268 */ 46269 get functions() { 46270 return new pM(this.functionsUrl.href, { 46271 headers: this.headers, 46272 customFetch: this.fetch 46273 }); 46274 } 46275 /** 46276 * Perform a query on a table or a view. 46277 * 46278 * @param relation - The table or view name to query 46279 */ 46280 from(n) { 46281 return this.rest.from(n); 46282 } 46283 /** 46284 * Select a schema to query or perform an function (rpc) call. 46285 * 46286 * The schema needs to be on the list of exposed schemas inside Supabase. 46287 * 46288 * @param schema - The schema to query 46289 */ 46290 schema(n) { 46291 return this.rest.schema(n); 46292 } 46293 /** 46294 * Perform a function call. 46295 * 46296 * @param fn - The function name to call 46297 * @param args - The arguments to pass to the function call
46298 * @param options - Named parameters 46299 * @param options.head - When set to `true`, `data` will not be returned. 46300 * Useful if you only need the count. 46301 * @param options.get - When set to `true`, the function will be called with 46302 * read-only access mode. 46303 * @param options.count - Count algorithm to use to count rows returned by the 46304 * function. Only applicable for [set-returning 46305 * functions](https://www.postgresql.org/docs/current/functions-srf.html). 46306 * 46307 * `"exact"`: Exact but slow count algorithm. Performs a `COUNT(*)` under the 46308 * hood. 46309 * 46310 * `"planned"`: Approximated but fast count algorithm. Uses the Postgres 46311 * statistics under the hood. 46312 * 46313 * `"estimated"`: Uses exact count for low numbers and planned count for high 46314 * numbers. 46315 */ 46316 rpc(n, e = {}, t = { 46317 head: !1, 46318 get: !1, 46319 count: void 0 46320 }) { 46321 return this.rest.rpc(n, e, t); 46322 } 46323 /** 46324 * Creates a Realtime channel with Broadcast, Presence, and Postgres Changes. 46325 * 46326 * @param {string} name - The name of the Realtime channel. 46327 * @param {Object} opts - The options to pass to the Realtime channel. 46328 * 46329 * @category Realtime 46330 */ 46331 channel(n, e = { config: {} }) { 46332 return this.realtime.channel(n, e); 46333 } 46334 /** 46335 * Returns all Realtime channels. 46336 * 46337 * @category Realtime 46338 * 46339 * @example Get all channels 46340 * ```js 46341 * const channels = supabase.getChannels() 46342 * ``` 46343 */ 46344 getChannels() { 46345 return this.realtime.getChannels(); 46346 } 46347 /** 46348 * Unsubscribes and removes Realtime channel from Realtime client. 46349 * 46350 * @param {RealtimeChannel} channel - The name of the Realtime channel. 46351 * 46352 * 46353 * @category Realtime 46354 * 46355 * @remarks 46356 * - Removing a channel is a great way to maintain the performance of your project's Realtime service as well as your database if you're listening to Postgres changes. Supabase will automatically handle cleanup 30 seconds after a client is disconnected, but unused channels may cause degradation as more clients are simultaneously subscribed. 46357 * 46358 * @example Removes a channel 46359 * ```js 46360 * supabase.removeChannel(myChannel) 46361 * ``` 46362 */ 46363 removeChannel(n) { 46364 return this.realtime.removeChannel(n); 46365 } 46366 /** 46367 * Unsubscribes and removes all Realtime channels from Realtime client. 46368 * 46369 * @category Realtime 46370 * 46371 * @remarks 46372 * - Removing channels is a great way to maintain the performance of your project's Realtime service as well as your database if you're listening to Postgres changes. Supabase will automatically handle cleanup 30 seconds after a client is disconnected, but unused channels may cause degradation as more clients are simultaneously subscribed. 46373 * 46374 * @example Remove all channels 46375 * ```js 46376 * supabase.removeAllChannels() 46377 * ``` 46378 */ 46379 removeAllChannels() { 46380 return this.realtime.removeAllChannels(); 46381 } 46382 async _getAccessToken() { 46383 var n = this, e, t; 46384 if (n.accessToken) return await n.accessToken(); 46385 const { data: i } = await n.auth.getSession(); 46386 return (e = (t = i.session) === null || t === void 0 ? void 0 : t.access_token) !== null && e !== void 0 ? e : n.supabaseKey; 46387 } 46388 _initSupabaseAuthClient({ autoRefreshToken: n, persistSession: e, detectSessionInUrl: t, storage: i, userStorage: r, storageKey: s, flowType: a, lock: l, debug: o, throwOnError: c, experimental: u, lockAcquireTimeout: h, skipAutoInitialize: d }, f, p) { 46389 const v = { 46390 Authorization: `Bearer ${this.supabaseKey}`, 46391 apikey: `${this.supabaseKey}` 46392 }; 46393 return new oA({ 46394 url: this.authUrl.href, 46395 headers: Ht(Ht({}, v), f), 46396 storageKey: s, 46397 autoRefreshToken: n, 46398 persistSession: e, 46399 detectSessionInUrl: t, 46400 storage: i, 46401 userStorage: r, 46402 flowType: a, 46403 lock: l, 46404 debug: o, 46405 throwOnError: c, 46406 experimental: u, 46407 fetch: p, 46408 lockAcquireTimeout: h, 46409 skipAutoInitialize: d, 46410 hasCustomAuthorizationHeader: Object.keys(this.headers).some((m) => m.toLowerCase() === "authorization") 46411 }); 46412 } 46413 _initRealtimeClient(n) { 46414 return new sT(this.realtimeUrl.href, Ht(Ht({}, n), {}, { params: Ht(Ht({}, { apikey: this.supabaseKey }), n?.params) })); 46415 } 46416 _listenForAuthEvents() { 46417 return this.auth.onAuthStateChange((n, e) => { 46418 this._handleTokenChanged(n, "CLIENT", e?.access_token); 46419 }); 46420 } 46421 _handleTokenChanged(n, e, t) { 46422 (n === "TOKEN_REFRESHED" || n === "SIGNED_IN") && this.changedAccessToken !== t ? (this.changedAccessToken = t, this.realtime.setAuth(t)) : n === "SIGNED_OUT" && (this.realtime.setAuth(), e == "STORAGE" && this.auth.signOut(), this.changedAccessToken = void 0); 46423 } 46424}; 46425const cA = (n, e, t) => new lA(n, e, t); 46426function uA() { 46427 if (typeof window < "u") return !1; 46428 const n = globalThis.process; 46429 if (!n) return !1; 46430 const e = n.version; 46431 if (e == null) return !1; 46432 const t = e.match(/^v(\d+)\./); 46433 return t ? parseInt(t[1], 10) <= 18 : !1; 46434} 46435uA() && console.warn("â ï¸ Node.js 18 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to N
46435ode.js 20 or later. For more information, visit: https://github.com/orgs/supabase/discussions/37217"); 46436const Hm = "tmvxwjrknslzzoszedfs", $n = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InRtdnh3anJrbnNsenpvc3plZGZzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3ODA3NTQ3NzIsImV4cCI6MjA5NjMzMDc3Mn0.eBuoLruUevjc4nacS-Ics8o2tV8JEkkhDx438yoKOsk"; 46437cA( 46438 `https://${Hm}.supabase.co`, 46439 $n 46440); 46441const Dn = `https://${Hm}.supabase.co/functions/v1/make-server-0aee2dc5`, Ql = "tg_pair_code", ec = "tg_pair_expires", Pf = 2500; 46442function Gm() { 46443 const [n, e] = Xe({ 46444 code: null, 46445 status: "loading", 46446 previewUrl: null, 46447 expiresAt: null, 46448 error: null 46449 }), t = mt(null), i = mt(null), r = Gn(() => { 46450 t.current && (clearInterval(t.current), t.current = null); 46451 }, []), s = Gn(async (o) => { 46452 try { 46453 const c = await fetch(`${Dn}/pair/status/${o}`, { 46454 headers: { Authorization: `Bearer ${$n}` } 46455 }), u = await c.json(); 46456 if (!c.ok) { 46457 r(), e((d) => ({ ...d, status: "expired", error: u.error ?? "Pair session error" })); 46458 return; 46459 } 46460 const h = u.status === "uploaded" ? "uploaded" : u.status === "claimed" ? "claimed" : u.status === "expired" ? "expired" : "pending"; 46461 e((d) => ({ 46462 ...d, 46463 status: h, 46464 previewUrl: u.previewUrl ?? d.previewUrl, 46465 expiresAt: u.expiresAt ?? d.expiresAt 46466 })), h !== "pending" && r(); 46467 } catch (c) { 46468 console.log("Pair poll error:", c); 46469 } 46470 }, [r]), a = Gn(async () => { 46471 r(), e({ code: null, status: "loading", previewUrl: null, expiresAt: null, error: null }); 46472 try { 46473 const o = await fetch(`${Dn}/pair/create`, { 46474 method: "POST", 46475 headers: { Authorization: `Bearer ${$n}` } 46476 }), c = await o.json(); 46477 if (!o.ok) { 46478 e((d) => ({ ...d, status: "expired", error: c.error ?? "Failed to create pair" })); 46479 return; 46480 } 46481 const { code: u, expiresAt: h } = c; 46482 i.current = u, sessionStorage.setItem(Ql, u), sessionStorage.setItem(ec, h), e({ code: u, status: "pending", previewUrl: null, expiresAt: h, error: null }), await s(u), t.current = setInterval(() => s(u), Pf); 46483 } catch (o) { 46484 e((c) => ({ ...c, status: "expired", error: `Network error: ${o}` })); 46485 } 46486 }, [r, s]), l = Gn(() => { 46487 sessionStorage.removeItem(Ql), sessionStorage.removeItem(ec), a(); 46488 }, [a]); 46489 return bt(() => { 46490 const o = sessionStorage.getItem(Ql), c = sessionStorage.getItem(ec); 46491 return o && c && new Date(c) > /* @__PURE__ */ new Date() ? (i.current = o, e({ code: o, status: "pending", previewUrl: null, expiresAt: c, error: null }), s(o), t.current = setInterval(() => s(o), Pf)) : a(), r; 46492 }, []), { ...n, reset: l }; 46493} 46494const ih = "tg_session"; 46495function bs() { 46496 try { 46497 const n = localStorage.getItem(ih); 46498 return n ? JSON.parse(n) : null; 46499 } catch { 46500 return null; 46501 } 46502} 46503function Vm(n) { 46504 localStorage.setItem(ih, JSON.stringify(n)); 46505} 46506function hA() { 46507 localStorage.removeItem(ih); 46508} 46509/** 46510 * @license lucide-react v0.487.0 - ISC 46511 * 46512 * This source code is licensed under the ISC license. 46513 * See the LICENSE file in the root directory of this source tree. 46514 */ 46515const dA = (n) => n.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase(), fA = (n) => n.replace( 46516 /^([A-Z])|[\s-_]+(\w)/g, 46517 (e, t, i) => i ? i.toUpperCase() : t.toLowerCase() 46518), Lf = (n) => { 46519 const e = fA(n); 46520 return e.charAt(0).toUpperCase() + e.slice(1); 46521}, Wm = (...n) => n.filter((e, t, i) => !!e && e.trim() !== "" && i.indexOf(e) === t).join(" ").trim(); 46522/** 46523 * @license lucide-react v0.487.0 - ISC 46524 * 46525 * This source code is licensed under the ISC license. 46526 * See the LICENSE file in the root directory of this source tree. 46527 */ 46528var pA = { 46529 xmlns: "http://www.w3.org/2000/svg", 46530 width: 24, 46531 height: 24, 46532 viewBox: "0 0 24 24", 46533 fill: "none", 46534 stroke: "currentColor", 46535 strokeWidth: 2, 46536 strokeLinecap: "round", 46537 strokeLinejoin: "round" 46538}; 46539/** 46540 * @license lucide-react v0.487.0 - ISC 46541 * 46542 * This source code is licensed under the ISC license. 46543 * See the LICENSE file in the root directory of this source tree. 46544 */ 46545const mA = ws( 46546 ({ 46547 color: n = "currentColor", 46548 size: e = 24, 46549 strokeWidth: t = 2, 46550 absoluteStrokeWidth: i, 46551 className: r = "", 46552 children: s, 46553 iconNode: a, 46554 ...l 46555 }, o) => st( 46556 "svg", 46557 { 46558 ref: o, 46559 ...pA, 46560 width: e, 46561 height: e, 46562 stroke: n, 46563 strokeWidth: i ? Number(t) * 24 / Number(e) : t, 46564 className: Wm("lucide", r), 46565 ...l 46566 }, 46567 [ 46568 ...a.map(([c, u]) => st(c, u)), 46569 ...Array.isArray(s) ? s : [s] 46570 ] 46571 ) 46572); 46573/** 46574 * @license lucide-react v0.487.0 - ISC 46575 * 46576 * This source code is licensed under the ISC license. 46577 * See the LICENSE file in the root directory of this source tree. 46578 */ 46579const xi = (n, e) => { 46580 const t = ws( 46581 ({ className: i, ...r }, s) => st(mA, { 46582 ref: s, 46583 iconNode: e, 46584 className: Wm( 46585 `lucide-${dA(Lf(n))}`, 46586 `lucide-${n}`, 46587 i 46588 ), 46589 ...r 46590 }) 46591 ); 46592 return t.displayName = Lf(n), t; 46593}; 46594/** 46595 * @license lucide-react v0.487.0 - ISC 46596 * 46597 * This source code is licensed under the ISC license. 46598 * See the LICENSE file in the root directory of this source tree. 46599 */ 46600const gA = [ 46601 ["circle", { cx: "12", cy: "12", r: "10", key: "1mglay" }], 46602 ["line", { x1: "12", x2: "12", y1: "8", y2: "12", key: "1pkeuh" }], 46603 ["line", { x1: "12", x2: "12.01", y1: "16", y2: "16", key: "4dfq90" }] 46604], vA = xi("circle-alert", gA); 46605/** 46606 * @license lucide-react v0.487.0 - ISC 46607 * 46608 * This source code is licensed under the ISC license. 46609 * See the LICENSE file in the root directory of this source tree. 46610 */ 46611const _A = [ 46612 ["path", { d: "M21.801 10A10 10 0 1 1 17 3.335", key: "yps3ct" }], 46613 ["path", { d: "m9 11 3 3L22 4", key: "1pflzl" }] 46614], yA = xi("circle-check-big", _A); 46615/** 46616 * @license lucide-react v0.487.0 - ISC 46617 * 46618 * This source code is licensed under the ISC license. 46619 * See the LICENSE file in the root directory of this source tree. 46620 */ 46621const xA = [ 46622 ["path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4", key: "ih7n3h" }], 46623 ["polyline", { points: "7 10 12 15 17 10", key: "2ggqvy" }], 46624 ["line", { x1: "12", x2: "12", y1: "15", y2: "3", key: "1vk2je" }] 46625], $m = xi("download", xA); 46626/** 46627 * @license lucide-react v0.487.0 - ISC 46628 * 46629 * This source code is licensed under the ISC license. 46630 * See the LICENSE file in the root directory of this source tree. 46631 */ 46632const bA = [ 46633 [ 46634 "path", 46635 { 46636 d: "M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z", 46637 key: "96xj49" 46638 } 46639 ] 46640], wA = xi("flame", bA); 46641/** 46642 * @license lucide-react v0.487.0 - ISC 46643 * 46644 * This source code is licensed under the ISC license. 46645 * See the LICENSE file in the root directory of this source tree. 46646 */ 46647const SA = [["path", { d: "M21 12a9 9 0 1 1-6.219-8.56", key: "13zald" }]], Ta = xi("loader-circle", SA); 46648/** 46649 * @license lucide-react v0.487.0 - ISC 46650 * 46651 * This source code is licensed under the ISC license. 46652 * See the LICENSE file in the root directory of this source tree. 46653 */ 46654const EA = [ 46655 ["path", { d: "M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4", key: "1uf3rs" }], 46656 ["polyline", { points: "16 17 21 12 16 7", key: "1gabdz" }], 46657 ["line", { x1: "21", x2: "9", y1: "12", y2: "12", key: "1uyos4" }] 46658], MA = xi("log-out", EA); 46659/** 46660 * @license lucide-react v0.487.0 - ISC 46661 * 46662 * This source code is licensed under the ISC license. 46663 * See the LICENSE file in the root directory of this source tree. 46664 */ 46665const TA = [ 46666 ["path", { d: "M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8", key: "v9h5vc" }], 46667 ["path", { d: "M21 3v5h-5", key: "1q7to0" }], 46668 ["path", { d: "M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16", key: "3uifl3" }], 46669 ["path", { d: "M8 16H3v5", key: "1cv678" }] 46670], AA = xi("refresh-cw", TA); 46671/** 46672 * @license lucide-react v0.487.0 - ISC 46673 * 46674 * This source code is licensed under the ISC license. 46675 * See the LICENSE file in the root directory of this source tree. 46676 */ 46677const RA = [ 46678 ["path", { d: "M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4", key: "ih7n3h" }], 46679 ["polyline", { points: "17 8 12 3 7 8", key: "t8dd8p" }], 46680 ["line", { x1: "12", x2: "12", y1: "3", y2: "15", key: "widbto" }] 46681], CA = xi("upload", RA); 46682/** 46683 * @license lucide-react v0.487.0 - ISC 46684 * 46685 * This source code is licensed under the ISC license. 46686 * See the LICENSE file in the root directory of this source tree. 46687 */ 46688const PA = [ 46689 ["path", { d: "M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2", key: "1yyitq" }], 46690 ["circle", { cx: "9", cy: "7", r: "4", key: "nufk8" }], 46691 ["path", { d: "M22 21v-2a4 4 0 0 0-3-3.87", key: "kshegd" }], 46692 ["path", { d: "M16 3.13a4 4 0 0 1 0 7.75", key: "1da9ce" }] 46693], LA = xi("users", PA); 46694/** 46695 * @license lucide-react v0.487.0 - ISC 46696 * 46697 * This source code is licensed under the ISC license. 46698 * See the LICENSE file in the root directory of this source tree. 46699 */ 46700const NA = [ 46701 ["path", { d: "M18 6 6 18", key: "1bl5f8" }], 46702 ["path", { d: "m6 6 12 12", key: "d8bk6v" }] 46703], Aa = xi("x", NA), IA = 1600, DA = 0.82; 46704function UA(n) { 46705 return new Promise((e, t) => { 46706 const i = URL.createObjectURL(n), r = new Image(); 46707 r.onload = () => { 46708 URL.revokeObjectURL(i), e(r); 46709 }, r.onerror = (s) => { 46710 URL.revokeObjectURL(i), t(s); 46711 }, r.src = i; 46712 }); 46713} 46714async function jm(n, e = {}) { 46715 const t = e.maxEdge ?? IA, i = e.quality ?? DA; 46716 if (!n.type.startsWith("image/") || n.size < 400 * 1024) return n; 46717 try { 46718 const r = await UA(n), s = Math.min(1, t / Math.max(r.width, r.height)), a = Math.round(r.width * s), l = Math.round(r.height * s), o = document.createElement("canvas"); 46719 o.width = a, o.height = l; 46720 const c = o.getContext("2d"); 46721 if (!c) return n; 46722 c.drawImage(r, 0, 0, a, l); 46723 const u = await new Promise( 46724 (d) => o.toBlob(d, "image/jpeg", i) 46725 ); 46726 if (!u || u.size >= n.size) return n; 46727 const h = n.name.replace(/\.[^.]+$/, "") + ".jpg"; 46728 return new File([u], h, { type: "image/jpeg", lastModified: Date.now() }); 46729 } catch { 46730 return n; 46731 } 46732} 46733function Xm({ code: n, disabled: e, label: t = "Upload from this device", tone: i = "dar
46733k" }) { 46734 const r = mt(null), [s, a] = Xe(!1), [l, o] = Xe(null); 46735 async function c(d) { 46736 if (n) { 46737 a(!0), o(null); 46738 try { 46739 const f = await jm(d), p = new FormData(); 46740 p.append("code", n), p.append("photo", f); 46741 const v = await fetch(`${Dn}/pair/submit`, { 46742 method: "POST", 46743 headers: { Authorization: `Bearer ${$n}` }, 46744 body: p 46745 }), m = await v.json(); 46746 v.ok || (o(m.error ?? "Upload failed"), console.log("Browser upload error:", m)); 46747 } catch (f) { 46748 console.log("Browser upload network error:", f), o(`Network error: ${f}`); 46749 } finally { 46750 a(!1); 46751 } 46752 } 46753 } 46754 const u = i === "dark" ? "text-black/70 hover:text-black" : "text-white/65 hover:text-white", h = i === "dark" ? "decoration-black/30" : "decoration-white/30"; 46755 return /* @__PURE__ */ re(rr, { children: [ 46756 /* @__PURE__ */ P( 46757 "input", 46758 { 46759 ref: r, 46760 type: "file", 46761 accept: "image/*", 46762 capture: "environment", 46763 className: "hidden", 46764 onChange: (d) => { 46765 const f = d.target.files?.[0]; 46766 f && c(f), d.target.value = ""; 46767 } 46768 } 46769 ), 46770 /* @__PURE__ */ re( 46771 "button", 46772 { 46773 type: "button", 46774 onClick: () => r.current?.click(), 46775 disabled: e || s || !n, 46776 className: `inline-flex items-center gap-1.5 ${u} disabled:opacity-40 transition-colors`, 46777 children: [ 46778 s ? /* @__PURE__ */ P(Ta, { size: 12, className: "animate-spin" }) : /* @__PURE__ */ P(CA, { size: 12 }),
46779 /* @__PURE__ */ P("span", { className: `font-['Fira_Mono:Regular',sans-serif] text-[12px] underline underline-offset-2 ${h}`, children: s ? "Uploadingâ¦" : t }) 46780 ] 46781 } 46782 ), 46783 l && /* @__PURE__ */ P( 46784 "p", 46785 { 46786 role: "alert", 46787 className: "font-['Fira_Mono:Regular',sans-serif] text-[11px] text-red-700 bg-red-100 border border-red-300 rounded-md px-2 py-1 mt-2 max-w-[260px] text-center", 46788 children: l 46789 } 46790 ) 46791 ] }); 46792} 46793function OA(n) { 46794 if (!n) return ""; 46795 const e = new Date(n).getTime() - Date.now(); 46796 if (e <= 0) return "Expired"; 46797 const t = Math.floor(e / 6e4), i = Math.floor(e % 6e4 / 1e3); 46798 return `${t}:${i.toString().padStart(2, "0")}`; 46799} 46800function kA() { 46801 const n = hr(), e = Gm(), t = new URLSearchParams(window.location.search).get("dev"), i = t === "uploaded" || t === "pending" || t === "expired" || t === "claimed" || t === "loading" || t === "split", r = t === "split" ? "pending" : t, { code: s, status: a, previewUrl: l, expiresAt: o, error: c, reset: u } = i ? { 46802 code: "ABC123", 46803 status: r, 46804 previewUrl: "https://images.unsplash.com/photo-1464295440335-ee082a75ccca?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&q=80&w=600", 46805 expiresAt: new Date(Date.now() + 540 * 1e3).toISOString(), 46806 error: t === "expired" ? "Your pair code expired." : null, 46807 reset: () => { 46808 } 46809 } : e; 46810 bt(() => { 46811 bs() && n("/planet", { replace: !0 }); 46812 }, [n]); 46813 const h = s ? `${window.location.origin}/u/${s}` : ""; 46814 return /* @__PURE__ */ re("div", { className: "size-full relative overflow-hidden bg-black", children: [ 46815 /* @__PURE__ */ P("div", { className: "absolute inset-0", children: /* @__PURE__ */ P(As, { mode: "single", health: a === "uploaded" ? 1 : a === "expired" || a === "claimed" ? 0.15 : 0.3, splitHealth: a === "pending" ? { alive: 0.95, dead: 0.1 } : null }) }), 46816 /* @__PURE__ */ P(uM, {}), 46817 /* @__PURE__ */ P("div", { className: "absolute inset-0 flex items-center justify-center pointer-events-none p-6", style: { zIndex: 10 }, children: /* @__PURE__ */ re(am, { className: "pointer-events-auto flex flex-col gap-8 items-center w-full max-w-[400px]", children: [ 46818 a === "loading" && /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[16px] text-[#121212] text-center py-4", children: "Generating your pair codeâ¦" }), 46819 (a === "pending" || a === "uploaded") && s && /* @__PURE__ */ re(rr, { children: [
46820 /* @__PURE__ */ re("div", { className: "flex flex-col gap-4 items-center text-center", children: [ 46821 /* @__PURE__ */ P("p", { className: "font-['Boldonse:Regular',sans-serif] text-[32px] text-black", children: "Get Started" }), 46822 /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[16px] text-[#121212] text-center", children: a === "uploaded" ? "Photo received! Create your account below." : "Upload a photo you've taken of grass, trees, parks, trails, flowers, or any piece of nature." }) 46823 ] }), 46824 a === "pending" && /* @__PURE__ */ P("div", { className: "bg-white p-3 rounded-[14px]", children: /* @__PURE__ */ P(eh, { value: h, size: 140 }) }), 46825 a === "uploaded" && l && /* @__PURE__ */ P("div", { className: "bg-white p-3 rounded-[14px]", children: /* @__PURE__ */ P( 46826 "img", 46827 { 46828 src: l, 46829 alt: "Your outdoor photo", 46830 className: "w-[140px] h-[140px] object-cover rounded-[8px]" 46831 } 46832 ) }), 46833 a === "pending" && /* @__PURE__ */ re(rr, { children: [
46834 /* @__PURE__ */ re("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[13px] text-[#121212] opacity-60", children: [ 46835 "Expires in ", 46836 OA(o) 46837 ] }), 46838 /* @__PURE__ */ P(Xm, { code: s, tone: "dark" }) 46839 ] }), 46840 a === "uploaded" && /* @__PURE__ */ P(or, { onClick: () => n(`/signup?pair=${s}`), className: "w-full", children: "Create account â" }) 46841 ] }), 46842 (a === "expired" || a === "claimed") && /* @__PURE__ */ re("div", { className: "flex flex-col items-center gap-5 py-4", children: [ 46843 /* @__PURE__ */ P("p", { className: "font-['Boldonse:Regular',sans-serif] text-[28px] text-black text-center", children: a === "claimed" ? "Already used!" : "Code expired" }), 46844 /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[16px] text-[#121212] text-center", children: c ?? "Your pair code is no longer valid." }), 46845 /* @__PURE__ */ P(or, { onClick: u, children: "Get a new code" }) 46846 ] }) 46847 ] }) }) 46848 ] }); 46849} 46850function FA(n) { 46851 const e = Date.now() - new Date(n).getTime(), t = Math.floor(e / 6e4); 46852 if (t < 1) return "just now"; 46853 if (t < 60) return `${t}m ago`; 46854 const i = Math.floor(t / 60); 46855 if (i < 24) return `${i}h ago`; 46856 const r = Math.floor(i / 24); 46857 return r < 7 ? `${r}d ago` : new Date(n).toLocaleDateString(); 46858} 46859function Nf({ onSelect: n }) { 46860 const [e, t] = Xe([]), [i, r] = Xe(!0); 46861 return bt(() => { 46862 (async () => { 46863 try { 46864 const s = await fetch(`${Dn}/community?limit=30`, { 46865 headers: { Authorization: `Bearer ${$n}` } 46866 }), a = await s.json(); 46867 if (s.ok) { 46868 const l = bs()?.username?.toLowerCase() ?? null, o = a.entries ?? []; 46869 t(l ? o.filter((c) => c.username?.toLowerCase() !== l) : o); 46870 } 46871 } catch (s) { 46872 console.log("CommunityFeed fetch error:", s); 46873 } finally { 46874 r(!1); 46875 } 46876 })(); 46877 }, []), i ? /* @__PURE__ */ P("div", { className: "flex items-center justify-center py-8", children: /* @__PURE__ */ P("span", { className: "font-['Fira_Mono:Regular',sans-serif] text-[#121212] opacity-60 text-sm", children: "Loading..." }) }) : e.length === 0 ? /* @__PURE__ */ P("div", { className: "flex items-center justify-center py-8 px-3", children: /* @__PURE__ */ re("span", { className: "font-['Fira_Mono:Regular',sans-serif] text-[#121212] opacity-60 text-[13px] text-center leading-relaxed", children: [ 46878 "No one else has touched grass yet.", 46879 /* @__PURE__ */ P("br", {}), 46880 "Check back soon, or invite a friend." 46881 ] }) }) : /* @__PURE__ */ P( 46882 "div", 46883 { 46884 className: "flex flex-col gap-5 flex-1 min-h-0 overflow-y-auto pr-1 -mr-1", 46885 style: { 46886 scrollbarWidth: "thin", 46887 scrollbarColor: "rgba(0,0,0,0.25) transparent", 46888 overscrollBehavior: "contain" 46889 }, 46890 children: e.map((s, a) => /* @__PURE__ */ re("article", { className: "flex flex-col shrink-0", children: [
46891 /* @__PURE__ */ re("div", { className: "flex items-center justify-between pb-2", children: [ 46892 /* @__PURE__ */ re("div", { className: "flex items-center gap-2 min-w-0", children: [ 46893 /* @__PURE__ */ P( 46894 "div", 46895 { 46896 className: "w-7 h-7 rounded-full bg-black/15 flex items-center justify-center shrink-0", 46897 "aria-hidden": "true", 46898 children: /* @__PURE__ */ P("span", { className: "font-['Boldonse:Regular',sans-serif] text-[11px] text-black", children: s.username.slice(0, 1).toUpperCase() }) 46899 } 46900 ), 46901 /* @__PURE__ */ re("p", { className: "font-['Boldonse:Regular',sans-serif] text-[13px] text-black truncate", children: [ 46902 "@", 46903 s.username 46904 ] }) 46905 ] }), 46906 /* @__PURE__ */ P("span", { className: "font-['Fira_Mono:Regular',sans-serif] text-[10px] text-black/55 shrink-0", children: FA(s.uploadedAt) }) 46907 ] }), 46908 /* @__PURE__ */ re( 46909 "button", 46910 { 46911 onClick: () => n(s.username), 46912 className: "group block w-full overflow-hidden rounded-[14px] bg-black/10 relative", 46913 style: { aspectRatio: "1 / 1", boxShadow: "0 4px 14px rgba(0,0,0,0.18)" }, 46914 "aria-label": `View @${s.username}'s planet`, 46915 children: [
46916 s.photoUrl ? /* @__PURE__ */ P( 46917 "img", 46918 { 46919 src: s.photoUrl, 46920 alt: `${s.username}'s outdoor photo`, 46921 loading: "lazy", 46922 decoding: "async", 46923 className: "w-full h-full object-cover transition-transform duration-500 group-hover:scale-[1.04]" 46924 } 46925 ) : /* @__PURE__ */ P("div", { className: "w-full h-full bg-black/15" }), 46926 /* @__PURE__ */ P( 46927 "div", 46928 { 46929 className: "absolute inset-x-0 bottom-0 opacity-0 group-hover:opacity-100 transition-opacity", 46930 style: { 46931 background: "linear-gradient(to top, rgba(0,0,0,0.55), rgba(0,0,0,0))", 46932 paddingTop: 28 46933 }, 46934 children: /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-white text-[11px] text-center pb-2", children: "Tap to view their planet" }) 46935 } 46936 ) 46937 ] 46938 } 46939 ),
46940 /* @__PURE__ */ re( 46941 "button", 46942 { 46943 onClick: () => n(s.username), 46944 className: "self-start mt-2 inline-flex items-center gap-1 text-black/65 hover:text-black transition-colors", 46945 children: [ 46946 /* @__PURE__ */ P("span", { className: "font-['Fira_Mono:Regular',sans-serif] text-[11px] underline underline-offset-2 decoration-black/30", children: "View their planet" }), 46947 /* @__PURE__ */ P("span", { "aria-hidden": "true", className: "text-[11px] transition-transform group-hover:translate-x-0.5", children: "â" }) 46948 ] 46949 } 46950 ) 46951 ] }, a)) 46952 } 46953 ); 46954} 46955const BA = 1440 * 60 * 1e3; 46956function zA(n) { 46957 const [e, t] = Xe({ 46958 username: null, 46959 health: 0, 46960 photoUrl: null, 46961 history: [], 46962 loading: !1, 46963 error: null 46964 }); 46965 return bt(() => { 46966 if (!n) { 46967 t({ username: null, health: 0, photoUrl: null, history: [], loading: !1, error: null }); 46968 return; 46969 } 46970 let i = !1; 46971 return t((r) => ({ ...r, loading: !0, error: null })), (async () => { 46972 try { 46973 const r = await fetch(`${Dn}/planet/${n}`, { 46974 headers: { Authorization: `Bearer ${$n}` } 46975 }), s = await r.json(); 46976 if (i) return; 46977 if (!r.ok) { 46978 t({ username: n, health: 0, photoUrl: null, history: [], loading: !1, error: s.error ?? "Failed to load" }); 46979 return; 46980 } 46981 const a = Date.now() - new Date(s.lastRestoredAt).getTime(), l = Math.max(0, Math.min(1, 1 - a / BA)); 46982 t({ 46983 username: s.username, 46984 health: l, 46985 photoUrl: s.photoUrl ?? null, 46986 history: s.history ?? [], 46987 loading: !1, 46988 error: null 46989 }); 46990 } catch (r) { 46991 i || t({ username: n, health: 0, photoUrl: null, history: [], loading: !1, error: `Network error: ${r}` }); 46992 } 46993 })(), () => { 46994 i = !0; 46995 }; 46996 }, [n]), e; 46997} 46998function If(n) { 46999 return `${n.getFullYear()}-${n.getMonth()}-${n.getDate()}`; 47000} 47001function HA() { 47002 const n = [], e = /* @__PURE__ */ new Date(); 47003 for (let t = 6; t >= 0; t--) { 47004 const i = new Date(e); 47005 i.setDate(e.getDate() - t), n.push(i); 47006 } 47007 return n; 47008} 47009const GA = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; 47010function VA({ username: n, onClose: e }) { 47011 const { health: t, photoUrl: i, history: r, loading: s, error: a } = zA(n), l = HA(), o = /* @__PURE__ */ new Map(); 47012 for (const u of r) { 47013 const h = If(new Date(u.uploadedAt)); 47014 o.has(h) || o.set(h, u.photoUrl); 47015 } 47016 const c = Math.round(t * 100); 47017 return /* @__PURE__ */ re("div", { className: "absolute inset-0 bg-black flex flex-col overflow-hidden", children: [ 47018 /* @__PURE__ */ P("div", { className: "absolute inset-0", children: /* @__PURE__ */ P(As, { mode: "single", health: t }) }), 47019 /* @__PURE__ */ re("div", { className: "relative flex flex-col h-full pointer-events-none", children: [
47020 /* @__PURE__ */ re("div", { className: "flex items-start justify-between px-6 pt-6 shrink-0 gap-4", children: [ 47021 /* @__PURE__ */ re( 47022 "button", 47023 { 47024 onClick: e, 47025 className: "pointer-events-auto flex items-center gap-1.5 text-white/70 hover:text-white transition-colors", 47026 children: [ 47027 /* @__PURE__ */ P(Aa, { size: 14 }), 47028 /* @__PURE__ */ P("span", { className: "font-['Fira_Mono:Regular',sans-serif] text-[12px]", children: "Back to your planet" }) 47029 ] 47030 } 47031 ), 47032 /* @__PURE__ */ re("div", { className: "flex flex-col items-center gap-4 min-w-0", children: [ 47033 /* @__PURE__ */ re( 47034 "p", 47035 { 47036 className: "font-['Boldonse:Regular',sans-serif] text-white leading-tight text-center truncate", 47037 style: { fontSize: "clamp(20px, 2.6vw, 30px)", maxWidth: "50vw" }, 47038 children: [ 47039 "@", 47040 n, 47041 "'s planet" 47042 ] 47043 } 47044 ),
47045 /* @__PURE__ */ re("div", { className: "flex items-center gap-2.5 w-[260px] max-w-[60vw]", children: [ 47046 /* @__PURE__ */ P("div", { className: "flex-1 bg-white/15 rounded-full p-[2px] overflow-hidden", children: /* @__PURE__ */ P( 47047 "div", 47048 { 47049 className: "bg-[#32bb29] rounded-full transition-all duration-1000", 47050 style: { width: `${c}%`, height: 6 } 47051 } 47052 ) }), 47053 /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-white/70 text-[11px] shrink-0 tabular-nums", children: s ? "â¦" : `${c}%` }) 47054 ] }) 47055 ] }), 47056 /* @__PURE__ */ P("div", { style: { width: 140 } }) 47057 ] }), 47058 i && /* @__PURE__ */ P("div", { className: "absolute pointer-events-none", style: { right: 24, top: 88 }, children: /* @__PURE__ */ P( 47059 "div", 47060 { 47061 className: "bg-white", 47062 style: { 47063 padding: "6px 6px 18px 6px", 47064 transform: "rotate(-4deg)", 47065 boxShadow: "0 10px 24px rgba(0,0,0,0.4), 0 2px 6px rgba(0,0,0,0.35)" 47066 }, 47067 children: /* @__PURE__ */ P( 47068 "img", 47069 { 47070 src: i, 47071 alt: `@${n}'s latest photo`, 47072 className: "block object-cover", 47073 style: { width: 92, height: 116 } 47074 } 47075 ) 47076 } 47077 ) }),
47078 /* @__PURE__ */ P("div", { className: "flex-1" }), 47079 /* @__PURE__ */ P("div", { className: "flex flex-col items-center gap-3 pb-6 px-6 shrink-0", children: /* @__PURE__ */ P("div", { className: "flex items-end gap-1.5", children: l.map((u, h) => { 47080 const d = o.get(If(u)) ?? null, f = d !== null; 47081 return /* @__PURE__ */ re("div", { className: "flex flex-col items-center gap-1", children: [ 47082 /* @__PURE__ */ P( 47083 "div", 47084 { 47085 className: "relative", 47086 style: { 47087 width: 32, 47088 height: 40, 47089 background: f ? "#fff" : "rgba(255,255,255,0.05)", 47090 padding: 2, 47091 border: f ? "none" : "1px dashed rgba(255,255,255,0.22)" 47092 }, 47093 children: d && /* @__PURE__ */ P( 47094 "div", 47095 { 47096 className: "w-full h-full", 47097 style: { backgroundImage: `url(${d})`, backgroundSize: "cover", backgroundPosition: "center" } 47098 } 47099 ) 47100 } 47101 ),
47102 /* @__PURE__ */ P("span", { className: "font-['Fira_Mono:Regular',sans-serif] text-white/45 text-[9px] leading-none", children: GA[u.getDay()] }) 47103 ] }, h); 47104 }) }) }) 47105 ] }) 47106 ] }); 47107} 47108const yr = 1080, Fn = 1350; 47109function WA(n) { 47110 return new Promise((e, t) => { 47111 const i = new Image(); 47112 i.crossOrigin = "anonymous", i.onload = () => e(i), i.onerror = t, i.src = n; 47113 }); 47114} 47115function $A(n) { 47116 const e = new Date(n), t = /* @__PURE__ */ new Date(); 47117 return e.getFullYear() === t.getFullYear() && e.getMonth() === t.getMonth() && e.getDate() === t.getDate(); 47118} 47119let ho = null; 47120const jA = 6e4; 47121async function XA() { 47122 if (ho && Date.now() - ho.at < jA) 47123 return ho.value; 47124 try { 47125 const n = await fetch(`${Dn}/community?limit=50`, { 47126 headers: { Authorization: `Bearer ${$n}` } 47127 }), e = await n.json(); 47128 if (!n.ok) return 0; 47129 const i = (e.entries ?? []).filter((r) => $A(r.uploadedAt)).length; 47130 return ho = { value: i, at: Date.now() }, i; 47131 } catch { 47132 return 0; 47133 } 47134} 47135const Mo = /* @__PURE__ */ new Map(); 47136function qm(n) { 47137 return `${n.username}|${n.streak}|${n.photoUrl}`; 47138} 47139const fo = /* @__PURE__ */ new Map(); 47140async function Ym(n) { 47141 const e = qm(n); 47142 if (Mo.has(e)) return Mo.get(e); 47143 if (fo.has(e)) return fo.get(e); 47144 const t = (async () => { 47145 const i = await XA(), r = await qA({ ...n, todayCount: i }), s = URL.createObjectURL(r), a = { blob: r, url: s }; 47146 return Mo.set(e, a), fo.delete(e), a; 47147 })(); 47148 return fo.set(e, t), t; 47149} 47150async function qA(n) { 47151 const e = document.createElement("canvas"); 47152 e.width = yr, e.height = Fn; 47153 const t = e.getContext("2d"); 47154 t.fillStyle = "#0b0b0b", t.fillRect(0, 0, yr, Fn); 47155 try { 47156 const o = await WA(n.photoUrl), c = Math.max(yr / o.width, Fn / o.height), u = o.width * c, h = o.height * c; 47157 t.drawImage(o, (yr - u) / 2, (Fn - h) / 2, u, h); 47158 } catch { 47159 } 47160 const i = t.createLinearGradient(0, Fn * 0.35, 0, Fn); 47161 i.addColorStop(0, "rgba(0,0,0,0)"), i.addColorStop(0.55, "rgba(0,0,0,0.55)"), i.addColorStop(1, "rgba(0,0,0,0.92)"), t.fillStyle = i, t.fillRect(0, 0, yr, Fn), t.fillStyle = "#ffffff", t.textBaseline = "top", t.font = "600 36px 'Fira Mono', ui-monospace, monospace", t.fillText("â touch grass", 56, 56), t.textAlign = "right", t.fillStyle = "rgba(255,255,255,0.7)", t.font = "400 32px 'Fira Mono', ui-monospace, monospace", t.fillText(`@${n.username}`, yr - 56, 60), t.textAlign = "left", t.fillStyle = "#ffffff", t.font = "700 320px 'Boldonse', 'Inter', system-ui, sans-serif", t.textBaseline = "alphabetic"; 47162 const r = String(n.streak); 47163 t.fillText(r, 56, Fn - 260), t.font = "500 44px 'Fira Mono', ui-monospace, monospace", t.fillStyle = "rgba(255,255,255,0.85)"; 47164 const s = (n.streak === 1, "day streak"); 47165 t.fillText(s, 56, Fn - 200), t.fillStyle = "rgba(255,255,255,0.2)", t.fillRect(56, Fn - 160, yr - 112, 2), t.font = "400 36px 'Fira Mono', ui-monospace, monospace", t.fillStyle = "rgba(255,255,255,0.78)"; 47166 const a = n.todayCount > 1 ? n.todayCount - 1 : n.todayCount, l = a > 0 ? `joined ${a} other grass-toucher${a === 1 ? "" : "s"} today` : "first grass-toucher today"; 47167 return t.fillText(l, 56, Fn - 110), t.fillStyle = "#32bb29", t.fillRect(56, Fn - 70, 84, 6), new Promise((o, c) => { 47168 e.toBlob((u) => u ? o(u) : c(new Error("toBlob failed")), "image/png"); 47169 }); 47170} 47171function YA({ photoUrl: n, username: e, streak: t, onClose: i }) { 47172 const r = Mo.get(qm({ photoUrl: n, username: e, streak: t })), [s, a] = Xe(r?.url ?? null), [l, o] = Xe(r?.blob ?? null), [c, u] = Xe(!r); 47173 bt(() => { 47174 if (r) return; 47175 let d = !1; 47176 return (async () => { 47177 u(!0); 47178 try { 47179 const f = await Ym({ photoUrl: n, username: e, streak: t }); 47180 if (d) return; 47181 o(f.blob), a(f.url); 47182 } catch (f) { 47183 console.log("ShareCard render error:", f); 47184 } finally { 47185 d || u(!1); 47186 } 47187 })(), () => { 47188 d = !0; 47189 }; 47190 }, [n, e, t, r]); 47191 function h() { 47192 if (!s) return; 47193 const d = document.createElement("a"); 47194 d.href = s, d.download = `touch-grass-${e}.png`, d.click(); 47195 } 47196 return /* @__PURE__ */ P("div", { className: "fixed inset-0 z-50 flex items-center justify-center bg-black/70 backdrop-blur-sm p-4", children: /* @__PURE__ */ re("div", { className: "bg-[#121212] flex flex-col items-center gap-4 w-full max-w-[420px] rounded-[28px] p-6 relative border border-white/10", children: [
47197 /* @__PURE__ */ P("button", { onClick: i, className: "absolute top-4 right-4 text-white/60 hover:text-white", children: /* @__PURE__ */ P(Aa, { size: 18 }) }), 47198 /* @__PURE__ */ P("p", { className: "font-['Boldonse:Regular',sans-serif] text-white text-[18px] self-start", children: "Share your streak" }), 47199 /* @__PURE__ */ P( 47200 "div", 47201 { 47202 className: "w-full bg-black rounded-[16px] overflow-hidden flex items-center justify-center", 47203 style: { aspectRatio: "4 / 5" }, 47204 children: c || !s ? /* @__PURE__ */ P(Ta, { size: 28, className: "text-white/60 animate-spin" }) : /* @__PURE__ */ P("img", { src: s, alt: "Share preview", className: "w-full h-full object-contain" }) 47205 } 47206 ), 47207 /* @__PURE__ */ re( 47208 "button", 47209 { 47210 onClick: h, 47211 disabled: !l, 47212 className: "w-full flex items-center justify-center gap-2 bg-[#32bb29] hover:brightness-110 disabled:opacity-40 text-black rounded-full py-3 transition-all", 47213 children: [ 47214 /* @__PURE__ */ P($m, { size: 14 }),
47215 /* @__PURE__ */ P("span", { className: "font-['Fira_Mono:Regular',sans-serif] text-[13px]", children: "Download image" }) 47216 ] 47217 } 47218 ) 47219 ] }) }); 47220} 47221const KA = 1440 * 60 * 1e3; 47222function JA(n) { 47223 const e = Date.now() - new Date(n).getTime(); 47224 return Math.max(0, Math.min(1, 1 - e / KA)); 47225} 47226function ZA(n = 100) { 47227 const [e, t] = Xe({ planets: [], loading: !0, error: null }); 47228 return bt(() => { 47229 let i = !1; 47230 return (async () => { 47231 try { 47232 const r = await fetch(`${Dn}/planets/sample?limit=${n}`, { 47233 headers: { Authorization: `Bearer ${$n}` } 47234 }), s = await r.json(); 47235 if (i) return; 47236 if (!r.ok) { 47237 t({ planets: [], loading: !1, error: s.error ?? "Failed to load galaxy" }); 47238 return; 47239 } 47240 const l = (s.planets ?? []).filter((o) => o.username && o.lastRestoredAt).map((o) => ({ username: o.username, health: JA(o.lastRestoredAt) })); 47241 t({ planets: l, loading: !1, error: null }); 47242 } catch (r) { 47243 i || t({ planets: [], loading: !1, error: `Network error: ${r}` }); 47244 } 47245 })(), () => { 47246 i = !0; 47247 }; 47248 }, [n]), e; 47249} 47250function QA(n) { 47251 let e = 2166136261; 47252 for (let t = 0; t < n.length; t++) 47253 e ^= n.charCodeAt(t), e = Math.imul(e, 16777619); 47254 return e >>> 0; 47255} 47256function eR(n, e, t) { 47257 const i = Math.PI * (3 - Math.sqrt(5)), r = (e + 0.5) / Math.max(t, 1), s = Math.sqrt(r) * 0.46, a = e * i + QA(n) % 360 * (Math.PI / 180) * 1e-3; 47258 return { x: 0.5 + s * Math.cos(a), y: 0.5 + s * Math.sin(a) }; 47259} 47260function tR(n) { 47261 return n > 0.7 ? "#32bb29" : n > 0.4 ? "#9fbf3a" : n > 0.15 ? "#a37844" : "#5a4034"; 47262} 47263function nR(n, e, t) { 47264 return t + (e - t) * (0.55 + n * 0.45); 47265} 47266const iR = [ 47267 { r: 0, angle: 0, color: "#32bb29", size: 4 }, 47268 { r: 6, angle: 35, color: "#9fbf3a", size: 3 }, 47269 { r: 6, angle: 200, color: "#a37844", size: 3 }, 47270 { r: 10, angle: 80, color: "#32bb29", size: 3 }, 47271 { r: 10, angle: 165, color: "#9fbf3a", size: 3 }, 47272 { r: 10, angle: 270, color: "#5a4034", size: 3 }, 47273 { r: 10, angle: 320, color: "#32bb29", size: 3 } 47274]; 47275function rR({ onOpen: n }) { 47276 return /* @__PURE__ */ re( 47277 "button", 47278 { 47279 onClick: n, 47280 className: "pointer-events-auto group flex items-center gap-2 text-white/70 hover:text-white transition-colors", 47281 "aria-label": "Open touch grass galaxy", 47282 children: [
47283 /* @__PURE__ */ P("style", { children: "@keyframes tg-galaxy-spin { to { transform: rotate(360deg); } }" }), 47284 /* @__PURE__ */ re( 47285 "span", 47286 { 47287 className: "relative inline-block", 47288 style: { 47289 width: 26, 47290 height: 26, 47291 animation: "tg-galaxy-spin 18s linear infinite" 47292 }, 47293 "aria-hidden": "true", 47294 children: [ 47295 /* @__PURE__ */ P( 47296 "span", 47297 { 47298 className: "absolute inset-0 rounded-full", 47299 style: { 47300 background: "radial-gradient(circle, rgba(120,160,255,0.35), rgba(120,160,255,0) 65%)" 47301 } 47302 } 47303 ), 47304 iR.map((e, t) => { 47305 const i = e.angle * Math.PI / 180, r = 13 + Math.cos(i) * e.r, s = 13 + Math.sin(i) * e.r; 47306 return /* @__PURE__ */ P( 47307 "span", 47308 { 47309 className: "absolute rounded-full", 47310 style: { 47311 left: r - e.size / 2, 47312 top: s - e.size / 2, 47313 width: e.size, 47314 height: e.size, 47315 background: e.color, 47316 boxShadow: `0 0 5px ${e.color}cc` 47317 } 47318 }, 47319 t 47320 ); 47321 }) 47322 ] 47323 } 47324 ),
47325 /* @__PURE__ */ P("span", { className: "font-['Fira_Mono:Regular',sans-serif] text-[12px]", children: "Galaxy" }) 47326 ] 47327 } 47328 ); 47329} 47330function sR({ onClose: n, onSelect: e }) { 47331 const { planets: t, loading: i, error: r } = ZA(150), s = t.length, a = mt(null), l = mt(null), [o, c] = Xe(null), u = Nn(() => t.map((h, d) => ({ 47332 planet: h, 47333 pos: eR(h.username, d, s) 47334 })), [t, s]); 47335 return bt(() => { 47336 let h = 0, d = 0, f = 0, p = !1; 47337 function v() { 47338 h = 0, p = !1, l.current && (l.current.style.transform = `translate(${d * -12}px, ${f * -10}px)`); 47339 } 47340 function m(g) { 47341 d = g.clientX / window.innerWidth * 2 - 1, f = g.clientY / window.innerHeight * 2 - 1, p || (p = !0, h = requestAnimationFrame(v)); 47342 } 47343 return window.addEventListener("pointermove", m, { passive: !0 }), () => { 47344 window.removeEventListener("pointermove", m), h && cancelAnimationFrame(h); 47345 }; 47346 }, []), /* @__PURE__ */ re("div", { className: "absolute inset-0 overflow-hidden bg-[#03060f] flex flex-col", children: [ 47347 /* @__PURE__ */ P("div", { className: "absolute inset-0 pointer-events-none", style: { 47348 backgroundImage: [ 47349 "radial-gradient(circle at 12% 18%, rgba(255,255,255,0.7) 0.6px, transparent 1px)", 47350 "radial-gradient(circle at 78% 22%, rgba(255,255,255,0.5) 0.5px, transparent 1px)", 47351 "radial-gradient(circle at 33% 70%, rgba(255,255,255,0.6) 0.6px, transparent 1px)", 47352 "radial-gradient(circle at 65% 80%, rgba(255,255,255,0.45) 0.5px, transparent 1px)", 47353 "radial-gradient(circle at 50% 50%, rgba(120,160,255,0.18), transparent 60%)" 47354 ].join(","), 47355 backgroundSize: "320px 320px, 280px 280px, 360px 360px, 340px 340px, 100% 100%" 47356 } }), 47357 /* @__PURE__ */ re("div", { className: "relative flex items-start justify-between px-6 pt-6 shrink-0 gap-4 pointer-events-none", children: [
47358 /* @__PURE__ */ re( 47359 "button", 47360 { 47361 onClick: n, 47362 className: "pointer-events-auto flex items-center gap-1.5 text-white/70 hover:text-white transition-colors", 47363 children: [ 47364 /* @__PURE__ */ P(Aa, { size: 14 }), 47365 /* @__PURE__ */ P("span", { className: "font-['Fira_Mono:Regular',sans-serif] text-[12px]", children: "Back to your planet" }) 47366 ] 47367 } 47368 ), 47369 /* @__PURE__ */ re("div", { className: "flex flex-col items-center gap-1 min-w-0", children: [ 47370 /* @__PURE__ */ P( 47371 "p", 47372 { 47373 className: "font-['Boldonse:Regular',sans-serif] text-white leading-tight text-center", 47374 style: { fontSize: "clamp(20px, 2.6vw, 30px)" }, 47375 children: "Touch Grass Galaxy" 47376 } 47377 ), 47378 /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-white/45 text-[11px]", children: i ? "Loadingâ¦" : r ? "Couldn't load" : `${s} planet${s === 1 ? "" : "s"} · tap one` }) 47379 ] }),
47380 /* @__PURE__ */ P("div", { style: { width: 160 } }) 47381 ] }), 47382 /* @__PURE__ */ re("div", { ref: a, className: "relative flex-1", children: [ 47383 /* @__PURE__ */ P( 47384 "div", 47385 { 47386 ref: l, 47387 className: "absolute inset-0", 47388 style: { transition: "transform 220ms ease-out" }, 47389 children: u.map(({ planet: h, pos: d }) => { 47390 const f = nR(h.health, 44, 16), p = tR(h.health), v = o === h.username; 47391 return /* @__PURE__ */ P( 47392 "button", 47393 { 47394 onClick: () => e(h.username), 47395 onMouseEnter: () => c(h.username), 47396 onMouseLeave: () => c((m) => m === h.username ? null : m), 47397 className: "absolute group rounded-full", 47398 style: { 47399 left: `${d.x * 100}%`, 47400 top: `${d.y * 100}%`, 47401 width: f, 47402 height: f, 47403 transform: `translate(-50%, -50%) scale(${v ? 1.18 : 1})`, 47404 background: `radial-gradient(circle at 30% 30%, ${p}, ${p}aa 60%, ${p}40)`, 47405 boxShadow: `0 0 ${f * 0.6}px ${p}66, inset -2px -3px 6px rgba(0,0,0,0.35)`, 47406 transition: "transform 200ms cubic-bezier(.2,.9,.2,1)" 47407 }, 47408 "aria-label": `View @${h.username}'s planet`, 47409 children: v && /* @__PURE__ */ re( 47410 "span", 47411 { 47412 className: "absolute left-1/2 -translate-x-1/2 font-['Fira_Mono:Regular',sans-serif] text-white text-[11px] whitespace-nowrap pointer-events-none", 47413 style: { top: "calc(100% + 6px)", textShadow: "0 1px 4px rgba(0,0,0,0.8)" }, 47414 children: [ 47415 "@", 47416 h.username 47417 ] 47418 } 47419 ) 47420 }, 47421 h.username 47422 ); 47423 }) 47424 } 47425 ), 47426 !i && s === 0 && /* @__PURE__ */ P("div", { className: "absolute inset-0 flex items-center justify-center", children: /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-white/55 text-[13px]", children: "No planets yet â invite a friend." }) }) 47427 ] }) 47428 ] }); 47429} 47430const Km = 1440 * 60 * 1e3; 47431function Df(n) { 47432 const e = Date.now() - new Date(n).getTime(); 47433 return Math.max(0, Math.min(1, 1 - e / Km)); 47434} 47435function tc(n) { 47436 return `${n.getFullYear()}-${n.getMonth()}-${n.getDate()}`; 47437} 47438function aR(n) { 47439 if (!n.length) return { streak: 0, doneToday: !1 }; 47440 const e = new Set(n.map((a) => tc(new Date(a.uploadedAt)))), t = /* @__PURE__ */ new Date(), i = e.has(tc(t)), r = new Date(t); 47441 i || r.setDate(r.getDate() - 1); 47442 let s = 0; 47443 for (; e.has(tc(r)); ) 47444 s++, r.setDate(r.getDate() - 1); 47445 return { streak: s, doneToday: i }; 47446} 47447function oR() { 47448 const [n, e] = Xe({ 47449 health: 0, 47450 lastRestoredAt: null, 47451 nextResetAt: null, 47452 history: [], 47453 photoUrl: null, 47454 username: null, 47455 streak: 0, 47456 doneToday: !1, 47457 loading: !0, 47458 error: null 47459 }), t = mt(null), i = Gn(async () => { 47460 const r = bs(); 47461 if (!r) { 47462 e((s) => ({ ...s, loading: !1, error: "Not logged in" })); 47463 return; 47464 } 47465 try { 47466 const s = await fetch(`${Dn}/planet/me`, { 47467 headers: { Authorization: `Bearer ${r.accessToken}` } 47468 }), a = await s.json(); 47469 if (!s.ok) { 47470 e((p) => ({ ...p, loading: !1, error: a.error ?? "Failed to fetch planet" })); 47471 return; 47472 } 47473 const { username: l, lastRestoredAt: o, photoUrl: c, history: u } = a; 47474 t.current = o; 47475 const h = u ?? [], { streak: d, doneToday: f } = aR(h); 47476 e({ 47477 health: Df(o), 47478 lastRestoredAt: o, 47479 nextResetAt: new Date(new Date(o).getTime() + Km), 47480 history: h, 47481 photoUrl: c ?? null, 47482 username: l, 47483 streak: d, 47484 doneToday: f, 47485 loading: !1, 47486 error: null 47487 }); 47488 } catch (s) { 47489 e((a) => ({ ...a, loading: !1, error: `Network error: ${s}` })); 47490 } 47491 }, []); 47492 return bt(() => { 47493 const r = setInterval(() => { 47494 t.current && e((s) => ({ 47495 ...s, 47496 health: Df(t.current) 47497 })); 47498 }, 1e3); 47499 return () => clearInterval(r); 47500 }, []), bt(() => { 47501 i(); 47502 }, [i]), { ...n, refetch: i }; 47503} 47504function lR(n) { 47505 if (!n) return "â"; 47506 const e = n.getTime() - Date.now(); 47507 if (e <= 0) return "Now!"; 47508 const t = Math.floor(e / 36e5), i = Math.floor(e % 36e5 / 6e4); 47509 return `${t}h ${i}m`; 47510} 47511function cR({ onClose: n, onUploaded: e }) { 47512 const { code: t, status: i, expiresAt: r, error: s, reset: a } = Gm(), l = t ? `${window.location.origin}/u/${t}` : "", o = r ? Math.max(0, Math.floor((new Date(r).getTime() - Date.now()) / 6e4)) : 0, c = r ? Math.max(0, Math.floor((new Date(r).getTime() - Date.now()) % 6e4 / 1e3)) : 0, [u, h] = Xe(null); 47513 return bt(() => { 47514 if (i !== "uploaded" || !t) return; 47515 let d = !1; 47516 return (async () => { 47517 const f = bs(); 47518 if (!f) { 47519 h("You're not logged in."); 47520 return; 47521 }
47522 try { 47523 const p = await fetch(`${Dn}/planet/claim-pair`, { 47524 method: "POST", 47525 headers: { 47526 Authorization: `Bearer ${f.accessToken}`, 47527 "Content-Type": "application/json" 47528 }, 47529 body: JSON.stringify({ code: t }) 47530 }), v = await p.json(); 47531 if (d) return; 47532 if (!p.ok) { 47533 h(v.error ?? "Failed to save your photo."); 47534 return; 47535 } 47536 e(), window.setTimeout(() => { 47537 d || n(); 47538 }, 1200); 47539 } catch (p) { 47540 d || h(`Network error: ${p}`); 47541 } 47542 })(), () => { 47543 d = !0; 47544 }; 47545 }, [i, t, e, n]), /* @__PURE__ */ P("div", { className: "fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm p-4", children: /* @__PURE__ */ re("div", { className: "bg-[#32bb29] flex flex-col gap-5 items-center w-full max-w-[360px] rounded-[36px] p-8 relative", children: [ 47546 /* @__PURE__ */ P( 47547 "button", 47548 { 47549 onClick: n, 47550 "aria-label": "Close", 47551 className: "absolute top-3 right-3 w-9 h-9 rounded-full flex items-center justify-center text-black/70 hover:text-black hover:bg-black/10 transition-colors", 47552 children: /* @__PURE__ */ P(Aa, { size: 18 }) 47553 } 47554 ), 47555 /* @__PURE__ */ P("p", { className: "font-['Boldonse:Regular',sans-serif] text-black text-[20px]", children: "Upload photo" }), 47556 i === "loading" && /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-black text-[14px]", children: "Generating codeâ¦" }), 47557 i === "pending" && t && /* @__PURE__ */ re(rr, { children: [
47558 /* @__PURE__ */ P("div", { className: "bg-white p-3 rounded-[14px]", children: /* @__PURE__ */ P(eh, { value: l, size: 140 }) }), 47559 /* @__PURE__ */ re("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[#121212] opacity-70 text-[12px]", children: [ 47560 "Expires in ", 47561 o, 47562 ":", 47563 c.toString().padStart(2, "0") 47564 ] }), 47565 /* @__PURE__ */ P(Xm, { code: t, tone: "dark" }) 47566 ] }), 47567 i === "uploaded" && /* @__PURE__ */ re("div", { className: "flex flex-col items-center gap-3", children: [ 47568 /* @__PURE__ */ P("div", { className: "w-12 h-12 rounded-full bg-white/30 flex items-center justify-center", children: /* @__PURE__ */ P("span", { className: "text-xl", children: "â" }) }), 47569 /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-black text-center text-[14px]", children: u ? "Photo uploaded, butâ¦" : "Photo uploaded! Your planet is being restored." }), 47570 u && /* @__PURE__ */ P("p", { role: "alert", className: "font-['Fira_Mono:Regular',sans-serif] text-[12px] text-red-700 bg-red-100 border border-red-300 rounded-md px-2 py-1 text-center", children: u }) 47571 ] }),
47572 (i === "expired" || i === "claimed") && /* @__PURE__ */ re(rr, { children: [ 47573 /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[#121212] text-center text-[14px]", children: s ?? "Code expired." }), 47574 /* @__PURE__ */ P(or, { onClick: a, children: "New code" }) 47575 ] }) 47576 ] }) }); 47577} 47578const po = "https://images.unsplash.com/photo-1464295440335-ee082a75ccca?crop=entropy&cs=tinysrgb&fit=max&fm=jpg&q=80&w=600", uR = { 47579 todo: { label: "Needs upload", doneToday: !1, health: 0.18, hoursLeft: 0, streak: 3, daysTouched: 4 }, 47580 fresh: { label: "Just uploaded", doneToday: !0, health: 1, hoursLeft: 24, streak: 5, daysTouched: 4 }, 47581 done: { label: "Mid-day", doneToday: !0, health: 0.78, hoursLeft: 18, streak: 4, daysTouched: 4 }, 47582 wilting: { label: "Wilting", doneToday: !0, health: 0.4, hoursLeft: 9, streak: 4, daysTouched: 4 }, 47583 dying: { label: "Almost dead", doneToday: !1, health: 0.06, hoursLeft: 0, streak: 0, daysTouched: 1 } 47584}, hR = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; 47585function To(n) { 47586 return `${n.getFullYear()}-${n.getMonth()}-${n.getDate()}`; 47587} 47588function Jm() { 47589 const n = [], e = /* @__PURE__ */ new Date(); 47590 for (let t = 6; t >= 0; t--) { 47591 const i = new Date(e); 47592 i.setDate(e.getDate() - t), n.push(i); 47593 } 47594 return n; 47595} 47596function dR({ streak: n }) { 47597 return /* @__PURE__ */ re("div", { className: "flex items-center gap-1.5 bg-white/10 backdrop-blur-md rounded-full px-2.5 py-1.5 border border-white/15", children: [ 47598 /* @__PURE__ */ P(wA, { size: 12, className: "text-[#ffb627]" }), 47599 /* @__PURE__ */ re("span", { className: "font-['Fira_Mono:Regular',sans-serif] text-white text-[12px] leading-none", children: [ 47600 n, 47601 " day", 47602 n === 1 ? "" : "s" 47603 ] }) 47604 ] }); 47605} 47606function fR({ url: n, onShare: e, prewarm: t }) { 47607 return /* @__PURE__ */ re( 47608 "button", 47609 { 47610 onClick: e, 47611 className: "pointer-events-auto relative group block", 47612 style: { 47613 animation: "tg-drop 700ms cubic-bezier(.2,.9,.2,1) both", 47614 transform: "rotate(-4deg)", 47615 transition: "transform 200ms cubic-bezier(.2,.9,.2,1)" 47616 }, 47617 onMouseEnter: (i) => { 47618 i.currentTarget.style.transform = "rotate(-2deg) scale(1.04)", t(); 47619 }, 47620 onFocus: t, 47621 onMouseLeave: (i) => i.currentTarget.style.transform = "rotate(-4deg)", 47622 title: "Download your streak card", 47623 "aria-label": "Download your streak card", 47624 children: [
47625 /* @__PURE__ */ re( 47626 "div", 47627 { 47628 className: "bg-white relative", 47629 style: { 47630 padding: "10px 10px 28px 10px", 47631 boxShadow: "0 14px 32px rgba(0,0,0,0.5), 0 2px 6px rgba(0,0,0,0.35)" 47632 }, 47633 children: [ 47634 /* @__PURE__ */ P("img", { src: n, alt: "Today's outdoor photo", className: "block object-cover", style: { width: 168, height: 210 } }), 47635 /* @__PURE__ */ P("span", { className: "absolute bottom-[6px] left-0 right-0 text-center font-['Fira_Mono:Regular',sans-serif] text-[10px] text-black/55 tracking-wide", children: "tap to download" }) 47636 ] 47637 } 47638 ), 47639 /* @__PURE__ */ P( 47640 "span", 47641 { 47642 className: "absolute -top-2 -right-2 w-8 h-8 rounded-full bg-[#32bb29] text-black flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity", 47643 style: { boxShadow: "0 6px 16px rgba(0,0,0,0.35)" }, 47644 "aria-hidden": "true", 47645 children: /* @__PURE__ */ P($m, { size: 14 }) 47646 } 47647 ) 47648 ] 47649 } 47650 ); 47651} 47652function pR({ byDay: n }) { 47653 const e = Jm(); 47654 return /* @__PURE__ */ P("div", { className: "flex items-end gap-1.5", children: e.map((t, i) => { 47655 const r = n.get(To(t)) ?? null, s = r !== null; 47656 return /* @__PURE__ */ re("div", { className: "flex flex-col items-center gap-1", children: [
47657 /* @__PURE__ */ P( 47658 "div", 47659 { 47660 className: "relative", 47661 style: { 47662 width: 32, 47663 height: 40, 47664 background: s ? "#fff" : "rgba(255,255,255,0.05)", 47665 padding: 2, 47666 border: s ? "none" : "1px dashed rgba(255,255,255,0.22)" 47667 }, 47668 children: r && /* @__PURE__ */ P( 47669 "div", 47670 { 47671 className: "w-full h-full", 47672 style: { backgroundImage: `url(${r})`, backgroundSize: "cover", backgroundPosition: "center" } 47673 } 47674 ) 47675 } 47676 ), 47677 /* @__PURE__ */ P("span", { className: "font-['Fira_Mono:Regular',sans-serif] text-white/45 text-[9px] leading-none", children: hR[t.getDay()] }) 47678 ] }, i); 47679 }) }); 47680} 47681const Uf = "clamp(280px, 28vw, 380px)", Of = 1e3; 47682function mR() { 47683 const n = hr(), [e, t] = Xe(!1), [i, r] = Xe(!1), [s, a] = Xe(!1), [l, o] = Xe(null), [c, u] = Xe(null), [h, d] = Xe(!1), [f, p] = Xe(!1), [v, m] = Xe(!0); 47684 bt(() => { 47685 if (!(!!l || h)) { 47686 m(!0); 47687 return; 47688 } 47689 const te = window.setTimeout(() => m(!1), 500); 47690 return () => window.clearTimeout(te); 47691 }, [l, h]); 47692 function g() { 47693 p(!0), requestAnimationFrame(() => { 47694 requestAnimationFrame(() => d(!0)); 47695 }); 47696 } 47697 function _() { 47698 d(!1), window.setTimeout(() => p(!1), 500); 47699 } 47700 function x(le) { 47701 u(le), a(!1), requestAnimationFrame(() => { 47702 requestAnimationFrame(() => o(le)); 47703 }); 47704 } 47705 function E() { 47706 o(null), window.setTimeout(() => u(null), 500); 47707 } 47708 const [R, T] = Xe( 47709 typeof window < "u" ? window.innerWidth < Of : !1 47710 ); 47711 bt(() => { 47712 const le = () => T(window.innerWidth < Of); 47713 return window.addEventListener("resize", le, { passive: !0 }), () => window.removeEventListener("resize", le); 47714 }, []); 47715 const w = new URLSearchParams(window.location.search), y = w.get("dev") === "1", [M, L] = Xe(() => { 47716 const le = w.get("state"); 47717 return le === "todo" ? "todo" : le === "fresh" ? "fresh" : le === "wilting" ? "wilting" : le === "dying" ? "dying" : "done"; 47718 }), C = uR[M]; 47719 bt(() => { 47720 !y && !bs() && n("/", { replace: !0 }); 47721 }, [n, y]); 47722 const U = oR(), V = y ? po : U.photoUrl ?? po, F = /* @__PURE__ */ new Map(); 47723 if (y)
47724 Jm().slice(0, C.daysTouched).forEach((te) => F.set(To(te), po)), C.doneToday && F.set(To(/* @__PURE__ */ new Date()), po); 47725 else 47726 for (const le of U.history) { 47727 const te = To(new Date(le.uploadedAt)); 47728 F.has(te) || F.set(te, le.photoUrl); 47729 } 47730 const { health: I, nextResetAt: k, loading: H, error: X, streak: K, doneToday: ae } = y ? { 47731 health: C.health, 47732 nextResetAt: new Date(Date.now() + C.hoursLeft * 3600 * 1e3), 47733 loading: !1, 47734 error: null, 47735 streak: C.streak, 47736 doneToday: C.doneToday 47737 } : U, se = y ? { username: "demo" } : bs(); 47738 function he() { 47739 hA(), n("/"); 47740 } 47741 const Ce = Math.round(I * 100), Ie = ae ? "Touch grass tomorrow or your planet wilts." : "Miss today and your planet wilts.", Ee = !R, J = Ee ? Uf : "0"; 47742 return /* @__PURE__ */ re("div", { className: "size-full relative overflow-hidden bg-black", children: [ 47743 /* @__PURE__ */ P("style", { children: ` 47744 @keyframes tg-drop { from { opacity: 0; transform: translateY(-10px) rotate(-10deg); } to { opacity: 1; } } 47745 ` }), 47746 /* @__PURE__ */ re("div", { className: "absolute inset-0 overflow-hidden", style: { right: J }, children: [
47747 /* @__PURE__ */ P( 47748 "div", 47749 { 47750 className: "absolute inset-0", 47751 style: { 47752 transform: l ? "translateX(-100%)" : "translateX(0)", 47753 transition: "transform 450ms cubic-bezier(.2,.9,.2,1)" 47754 }, 47755 children: /* @__PURE__ */ P("div", { className: "absolute inset-0", children: v && /* @__PURE__ */ P(As, { mode: "single", health: I }) }) 47756 } 47757 ), 47758 c && /* @__PURE__ */ P( 47759 "div", 47760 { 47761 className: "absolute inset-0", 47762 style: { 47763 transform: l ? "translateX(0)" : "translateX(100%)", 47764 transition: "transform 450ms cubic-bezier(.2,.9,.2,1)" 47765 }, 47766 children: /* @__PURE__ */ P(VA, { username: c, onClose: E }) 47767 } 47768 ), 47769 f && /* @__PURE__ */ P( 47770 "div", 47771 { 47772 className: "absolute inset-0", 47773 style: { 47774 transform: h ? "translateX(0)" : "translateX(100%)", 47775 transition: "transform 450ms cubic-bezier(.2,.9,.2,1)", 47776 zIndex: 10 47777 }, 47778 children: /* @__PURE__ */ P( 47779 sR, 47780 { 47781 onClose: _, 47782 onSelect: (le) => { 47783 _(), x(le); 47784 } 47785 } 47786 ) 47787 } 47788 ) 47789 ] }), 47790 Ee && /* @__PURE__ */ re( 47791 "div", 47792 { 47793 className: "absolute top-0 bottom-0 right-0 bg-[#32bb29] flex flex-col overflow-hidden", 47794 style: { 47795 width: Uf, 47796 borderTopLeftRadius: "36px", 47797 borderBottomLeftRadius: "36px", 47798 padding: "24px 22px", 47799 gap: "16px" 47800 }, 47801 children: [
47802 /* @__PURE__ */ P("p", { className: "font-['Boldonse:Regular',sans-serif] text-black text-[20px] shrink-0", children: "Community" }), 47803 /* @__PURE__ */ P(Nf, { onSelect: x }) 47804 ] 47805 } 47806 ), 47807 /* @__PURE__ */ re( 47808 "div", 47809 { 47810 className: "absolute inset-0 flex flex-col pointer-events-none overflow-hidden", 47811 style: { 47812 right: J, 47813 transform: l ? "translateX(-100%)" : "translateX(0)", 47814 transition: "transform 450ms cubic-bezier(.2,.9,.2,1)" 47815 }, 47816 children: [ 47817 /* @__PURE__ */ re("div", { className: "flex items-start justify-between px-6 pt-6 shrink-0 gap-4", children: [ 47818 /* @__PURE__ */ re("div", { className: "flex flex-col items-start gap-6", children: [ 47819 /* @__PURE__ */ re( 47820 "button", 47821 { 47822 onClick: he, 47823 className: "pointer-events-auto flex items-center gap-1.5 text-white/70 hover:text-white transition-colors", 47824 children: [
47825 /* @__PURE__ */ P(MA, { size: 14 }), 47826 /* @__PURE__ */ P("span", { className: "font-['Fira_Mono:Regular',sans-serif] text-[12px]", children: "Log out" }) 47827 ] 47828 } 47829 ), 47830 /* @__PURE__ */ P(rR, { onOpen: g }) 47831 ] }), 47832 /* @__PURE__ */ re("div", { className: "flex flex-col items-center gap-4 min-w-0", children: [ 47833 /* @__PURE__ */ re( 47834 "p", 47835 { 47836 className: "font-['Boldonse:Regular',sans-serif] text-white leading-tight text-center truncate", 47837 style: { fontSize: "clamp(20px, 2.6vw, 30px)", maxWidth: "50vw" }, 47838 children: [ 47839 "@", 47840 se?.username ?? "demo", 47841 "'s planet" 47842 ] 47843 } 47844 ), 47845 /* @__PURE__ */ re("div", { className: "flex flex-col items-center gap-1", children: [ 47846 /* @__PURE__ */ re("div", { className: "flex items-center gap-2.5 w-[260px] max-w-[60vw]", children: [
47847 /* @__PURE__ */ P("div", { className: "flex-1 bg-white/15 rounded-full p-[2px] overflow-hidden", children: /* @__PURE__ */ P( 47848 "div", 47849 { 47850 className: "bg-[#32bb29] rounded-full transition-all duration-1000", 47851 style: { width: `${Ce}%`, height: 6 } 47852 } 47853 ) }), 47854 /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-white/70 text-[11px] shrink-0 tabular-nums", children: H ? "â¦" : X ? "â" : `${Ce}%` }) 47855 ] }), 47856 /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-white/40 text-[11px] text-center whitespace-nowrap", children: Ie }) 47857 ] }) 47858 ] }), 47859 /* @__PURE__ */ re("div", { className: "pointer-events-auto flex items-center gap-2", children: [ 47860 /* @__PURE__ */ P(dR, { streak: K }), 47861 R && /* @__PURE__ */ re( 47862 "button", 47863 { 47864 onClick: () => a(!0), 47865 className: "flex items-center gap-1.5 bg-white/10 backdrop-blur-md rounded-full px-2.5 py-1.5 border border-white/15 text-white hover:bg-white/15 transition-colors", 47866 "aria-label": "Open community", 47867 children: [
47868 /* @__PURE__ */ P(LA, { size: 12 }), 47869 /* @__PURE__ */ P("span", { className: "font-['Fira_Mono:Regular',sans-serif] text-[12px]", children: "Community" }) 47870 ] 47871 } 47872 ) 47873 ] }) 47874 ] }), 47875 ae && /* @__PURE__ */ P("div", { className: "absolute", style: { right: 28, top: 120 }, children: /* @__PURE__ */ P( 47876 fR, 47877 { 47878 url: V, 47879 onShare: () => r(!0), 47880 prewarm: () => { 47881 Ym({ 47882 photoUrl: V, 47883 username: se?.username ?? "demo", 47884 streak: K 47885 }).catch(() => { 47886 }); 47887 } 47888 } 47889 ) }), 47890 /* @__PURE__ */ P("div", { className: "flex-1" }), 47891 /* @__PURE__ */ re("div", { className: "flex flex-col items-center gap-3 pb-6 px-6 shrink-0", children: [ 47892 /* @__PURE__ */ P(pR, { byDay: F }), 47893 ae ? /* @__PURE__ */ re("div", { className: "pointer-events-auto flex items-center gap-2.5 bg-white/8 border border-white/12 rounded-full pl-1.5 pr-4 py-1.5", children: [
47894 /* @__PURE__ */ P("span", { className: "flex items-center justify-center w-7 h-7 rounded-full bg-[#32bb29]", children: /* @__PURE__ */ P("span", { className: "text-black text-sm leading-none", children: "â" }) }), 47895 /* @__PURE__ */ re("span", { className: "font-['Fira_Mono:Regular',sans-serif] text-white text-[12px]", children: [ 47896 "Done · back in ", 47897 lR(k) 47898 ] }), 47899 /* @__PURE__ */ re( 47900 "button", 47901 { 47902 onClick: () => t(!0), 47903 className: "flex items-center gap-1 text-white/50 hover:text-white transition-colors pl-2 border-l border-white/15", 47904 title: "Replace today's photo", 47905 children: [ 47906 /* @__PURE__ */ P(AA, { size: 11 }), 47907 /* @__PURE__ */ P("span", { className: "font-['Fira_Mono:Regular',sans-serif] text-[11px]", children: "Replace" }) 47908 ] 47909 } 47910 ) 47911 ] }) : /* @__PURE__ */ P("div", { className: "pointer-events-auto", children: /* @__PURE__ */ P(or, { variant: "green", onClick: () => t(!0), children: "Take today's photo" }) }) 47912 ] }) 47913 ] 47914 } 47915 ), 47916 R && s && /* @__PURE__ */ re("div", { className: "fixed inset-0 z-40 flex justify-end", children: [
47917 /* @__PURE__ */ P( 47918 "div", 47919 { 47920 className: "absolute inset-0 bg-black/50", 47921 onClick: () => a(!1) 47922 } 47923 ), 47924 /* @__PURE__ */ re( 47925 "div", 47926 { 47927 className: "relative bg-[#32bb29] h-full flex flex-col overflow-hidden", 47928 style: { 47929 width: "min(360px, 88vw)", 47930 borderTopLeftRadius: "36px", 47931 borderBottomLeftRadius: "36px", 47932 padding: "24px 22px", 47933 gap: "16px", 47934 animation: "tg-drop 280ms ease-out" 47935 }, 47936 children: [ 47937 /* @__PURE__ */ re("div", { className: "flex items-center justify-between shrink-0", children: [ 47938 /* @__PURE__ */ P("p", { className: "font-['Boldonse:Regular',sans-serif] text-black text-[20px]", children: "Community" }), 47939 /* @__PURE__ */ P( 47940 "button", 47941 { 47942 onClick: () => a(!1), 47943 className: "text-black/60 hover:text-black", 47944 "aria-label": "Close community", 47945 children: /* @__PURE__ */ P(Aa, { size: 18 }) 47946 } 47947 ) 47948 ] }),
47949 /* @__PURE__ */ P(Nf, { onSelect: x }) 47950 ] 47951 } 47952 ) 47953 ] }), 47954 e && /* @__PURE__ */ P( 47955 cR, 47956 { 47957 onClose: () => t(!1), 47958 onUploaded: () => U.refetch() 47959 } 47960 ), 47961 i && /* @__PURE__ */ P( 47962 YA, 47963 { 47964 photoUrl: V, 47965 username: se?.username ?? "demo", 47966 streak: K, 47967 onClose: () => r(!1) 47968 } 47969 ) 47970 ] }); 47971} 47972function gR({ value: n, onChange: e }) { 47973 const t = mt(null), [i, r] = Xe(!1), s = Math.min(n.length, 3); 47974 return /* @__PURE__ */ re( 47975 "div", 47976 { 47977 className: "relative flex gap-3 cursor-text w-full", 47978 onClick: () => t.current?.focus(), 47979 children: [ 47980 [0, 1, 2, 3].map((a) => { 47981 const l = a < n.length, o = i && a === s; 47982 return /* @__PURE__ */ P( 47983 "div", 47984 { 47985 className: "flex-1 rounded-[12px] flex items-center justify-center transition-colors", 47986 style: { 47987 // Fixed height so empty + filled cells match exactly. 47988 height: 56, 47989 border: `1.5px solid ${o ? "#000" : l ? "rgba(0,0,0,0.85)" : "rgba(0,0,0,0.35)"}`, 47990 background: o ? "rgba(255,255,255,0.35)" : l ? "rgba(255,255,255,0.2)" : "transparent", 47991 boxShadow: o ? "0 0 0 3px rgba(0,0,0,0.12)" : "none" 47992 }, 47993 children: /* @__PURE__ */ P("span", { className: "font-['Fira_Mono:Regular',sans-serif] text-[20px] text-[#121212] select-none leading-none", children: l ? n[a] : "" }) 47994 }, 47995 a 47996 ); 47997 }),
47998 /* @__PURE__ */ P( 47999 "input", 48000 { 48001 ref: t, 48002 type: "text", 48003 inputMode: "numeric", 48004 pattern: "[0-9]*", 48005 maxLength: 4, 48006 value: n, 48007 onChange: (a) => e(a.target.value.replace(/\D/g, "").slice(0, 4)), 48008 onFocus: () => r(!0), 48009 onBlur: () => r(!1), 48010 className: "absolute inset-0 opacity-0 cursor-text", 48011 style: { caretColor: "transparent" }, 48012 autoComplete: "off", 48013 autoCorrect: "off", 48014 autoCapitalize: "off", 48015 spellCheck: !1, 48016 name: "tg-pin", 48017 "data-lpignore": "true", 48018 "data-1p-ignore": "true", 48019 "data-form-type": "other" 48020 } 48021 ) 48022 ] 48023 } 48024 ); 48025} 48026function vR({ value: n, onChange: e }) { 48027 const [t, i] = Xe(!1), [r, s] = Xe(!1), a = t ? "#000" : r ? "rgba(0,0,0,0.85)" : "rgba(0,0,0,0.35)", l = t ? "rgba(255,255,255,0.35)" : r ? "rgba(255,255,255,0.18)" : "transparent", o = t ? "0 0 0 3px rgba(0,0,0,0.12)" : "none"; 48028 return /* @__PURE__ */ P( 48029 "div", 48030 { 48031 className: "rounded-[12px] transition-colors", 48032 onMouseEnter: () => s(!0), 48033 onMouseLeave: () => s(!1), 48034 style: { border: `1.5px solid ${a}`, background: l, boxShadow: o }, 48035 children: /* @__PURE__ */ P("div", { className: "flex items-center px-4", style: { height: 56 }, children: /* @__PURE__ */ P( 48036 "input", 48037 { 48038 type: "text", 48039 value: n, 48040 onChange: (c) => e(c.target.value.replace(/[^a-zA-Z0-9_]/g, "").slice(0, 20)), 48041 onFocus: () => i(!0), 48042 onBlur: () => i(!1), 48043 placeholder: "E.g. John1234", 48044 autoFocus: !0, 48045 autoComplete: "off", 48046 autoCorrect: "off", 48047 autoCapitalize: "off", 48048 spellCheck: !1, 48049 name: "tg-username", 48050 "data-lpignore": "true", 48051 "data-1p-ignore": "true", 48052 "data-form-type": "other", 48053 className: "w-full bg-transparent font-['Fira_Mono:Regular',sans-serif] text-[16px] text-[#121212] outline-none placeholder:opacity-40" 48054 } 48055 ) }) 48056 } 48057 ); 48058} 48059function _R() { 48060 const [n] = Fv(), e = n.get("pair") ?? "", t = hr(), [i, r] = Xe(""), [s, a] = Xe(""), [l, o] = Xe(null), [c, u] = Xe(!1), [h, d] = Xe(null); 48061 bt(() => { 48062 if (!e) { 48063 t("/start", { replace: !0 }); 48064 return; 48065 } 48066 fetch(`${Dn}/pair/status/${e}`, { 48067 headers: { Authorization: `Bearer ${$n}` } 48068 }).then((v) => v.json()).then((v) => { 48069 v.previewUrl && d(v.previewUrl); 48070 }).catch(() => { 48071 }); 48072 }, [e, t]); 48073 async function f(v) { 48074 v.preventDefault(), o(null), u(!0); 48075 try { 48076 const m = await fetch(`${Dn}/signup`, { 48077 method: "POST", 48078 headers: { "Content-Type": "application/json", Authorization: `Bearer ${$n}` }, 48079 body: JSON.stringify({ username: i, pin: s, pairCode: e }) 48080 }), g = await m.json(); 48081 if (!m.ok) { 48082 o(g.error ?? "Signup failed"); 48083 return; 48084 } 48085 Vm({ accessToken: g.accessToken, userId: g.userId, username: g.username }), t("/planet"); 48086 } catch { 48087 o("Network error â please try again"); 48088 } finally { 48089 u(!1); 48090 } 48091 } 48092 const p = i.length >= 3 && s.length === 4 && !c && !!e; 48093 return /* @__PURE__ */ re("div", { className: "size-full relative overflow-hidden bg-black flex items-center justify-center p-6", children: [ 48094 /* @__PURE__ */ P("div", { className: "absolute inset-0", children: /* @__PURE__ */ P(As, { mode: "single", health: 1 }) }), 48095 /* @__PURE__ */ re("div", { className: "relative z-10 bg-[#32bb29] rounded-[48px] p-10 flex flex-col gap-8 items-center w-full max-w-[500px] overflow-y-auto", children: [
48096 /* @__PURE__ */ P("p", { className: "font-['Boldonse:Regular',sans-serif] text-[28px] text-black w-full", children: "Choose a username and PIN to create your planet." }), 48097 /* @__PURE__ */ re( 48098 "form", 48099 { 48100 onSubmit: f, 48101 className: "w-full flex flex-col gap-6", 48102 autoComplete: "off", 48103 "data-form-type": "other", 48104 children: [ 48105 /* @__PURE__ */ P("input", { type: "text", name: "prevent_autofill", autoComplete: "off", tabIndex: -1, "aria-hidden": "true", style: { position: "absolute", opacity: 0, width: 0, height: 0, pointerEvents: "none" } }), 48106 /* @__PURE__ */ P("input", { type: "password", name: "prevent_password_save", autoComplete: "new-password", tabIndex: -1, "aria-hidden": "true", style: { position: "absolute", opacity: 0, width: 0, height: 0, pointerEvents: "none" } }), 48107 e && /* @__PURE__ */ re("div", { className: "flex flex-col gap-2 w-full", children: [ 48108 /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[14px] text-[#121212] opacity-60 uppercase tracking-wider", children: "Your image" }),
48109 /* @__PURE__ */ re("div", { className: "flex gap-3 items-center w-full", children: [ 48110 h ? /* @__PURE__ */ P( 48111 "img", 48112 { 48113 src: h, 48114 alt: "Your uploaded photo", 48115 className: "w-[72px] h-[72px] object-cover rounded-xl shrink-0" 48116 } 48117 ) : /* @__PURE__ */ P("div", { className: "w-[72px] h-[72px] rounded-xl bg-black/20 shrink-0 flex items-center justify-center", children: /* @__PURE__ */ P("span", { className: "text-[#121212] opacity-40 text-2xl", children: "ð¿" }) }), 48118 /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[16px] text-[#121212]", children: "Photo uploaded â" }) 48119 ] }) 48120 ] }), 48121 /* @__PURE__ */ re("div", { className: "flex flex-col gap-2 w-full", children: [ 48122 /* @__PURE__ */ P("label", { className: "font-['Fira_Mono:Regular',sans-serif] text-[14px] text-[#121212] opacity-60 uppercase tracking-wider", children: "Username" }),
48123 /* @__PURE__ */ P(vR, { value: i, onChange: r }) 48124 ] }), 48125 /* @__PURE__ */ re("div", { className: "flex flex-col gap-2 w-full", children: [ 48126 /* @__PURE__ */ P("label", { className: "font-['Fira_Mono:Regular',sans-serif] text-[14px] text-[#121212] opacity-60 uppercase tracking-wider", children: "Pin Code" }), 48127 /* @__PURE__ */ P(gR, { value: s, onChange: a }) 48128 ] }), 48129 l && /* @__PURE__ */ P("div", { className: "bg-red-100 border border-red-400 rounded-xl p-3", children: /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[14px] text-red-700", children: l }) }), 48130 /* @__PURE__ */ P(or, { type: "submit", disabled: !p, className: "w-full", children: c ? /* @__PURE__ */ P(Ta, { size: 18, className: "animate-spin" }) : "See your planet bloom" }) 48131 ] 48132 } 48133 ) 48134 ] }) 48135 ] }); 48136} 48137function yR({ value: n, onChange: e }) { 48138 const t = mt(null), [i, r] = Xe(!1), s = Math.min(n.length, 3); 48139 return /* @__PURE__ */ re( 48140 "div", 48141 { 48142 className: "relative flex gap-3 cursor-text w-full", 48143 onClick: () => t.current?.focus(), 48144 children: [ 48145 [0, 1, 2, 3].map((a) => { 48146 const l = a < n.length, o = i && a === s; 48147 return /* @__PURE__ */ P( 48148 "div", 48149 { 48150 className: "flex-1 rounded-[12px] flex items-center justify-center transition-colors", 48151 style: { 48152 height: 56, 48153 border: `1.5px solid ${o ? "#000" : l ? "rgba(0,0,0,0.85)" : "rgba(0,0,0,0.35)"}`, 48154 background: o ? "rgba(255,255,255,0.35)" : l ? "rgba(255,255,255,0.2)" : "transparent", 48155 boxShadow: o ? "0 0 0 3px rgba(0,0,0,0.12)" : "none" 48156 }, 48157 children: /* @__PURE__ */ P("span", { className: "font-['Fira_Mono:Regular',sans-serif] text-[20px] text-[#121212] select-none leading-none", children: l ? "â¢" : "" }) 48158 }, 48159 a 48160 ); 48161 }),
48162 /* @__PURE__ */ P( 48163 "input", 48164 { 48165 ref: t, 48166 type: "password", 48167 inputMode: "numeric", 48168 pattern: "[0-9]*", 48169 maxLength: 4, 48170 value: n, 48171 onChange: (a) => e(a.target.value.replace(/\D/g, "").slice(0, 4)), 48172 onFocus: () => r(!0), 48173 onBlur: () => r(!1), 48174 className: "absolute inset-0 opacity-0 cursor-text", 48175 style: { caretColor: "transparent" }, 48176 autoComplete: "off", 48177 autoCorrect: "off", 48178 autoCapitalize: "off", 48179 spellCheck: !1, 48180 name: "tg-pin", 48181 "data-lpignore": "true", 48182 "data-1p-ignore": "true", 48183 "data-form-type": "other" 48184 } 48185 ) 48186 ] 48187 } 48188 ); 48189} 48190function xR({ value: n, onChange: e }) { 48191 const [t, i] = Xe(!1), [r, s] = Xe(!1), a = t ? "#000" : r ? "rgba(0,0,0,0.85)" : "rgba(0,0,0,0.35)", l = t ? "rgba(255,255,255,0.35)" : r ? "rgba(255,255,255,0.18)" : "transparent", o = t ? "0 0 0 3px rgba(0,0,0,0.12)" : "none"; 48192 return /* @__PURE__ */ P( 48193 "div", 48194 { 48195 className: "rounded-[12px] transition-colors", 48196 onMouseEnter: () => s(!0), 48197 onMouseLeave: () => s(!1), 48198 style: { border: `1.5px solid ${a}`, background: l, boxShadow: o }, 48199 children: /* @__PURE__ */ P("div", { className: "flex items-center px-4", style: { height: 56 }, children: /* @__PURE__ */ P( 48200 "input", 48201 { 48202 type: "text", 48203 value: n, 48204 onChange: (c) => e(c.target.value.replace(/[^a-zA-Z0-9_]/g, "").slice(0, 20)), 48205 onFocus: () => i(!0), 48206 onBlur: () => i(!1), 48207 placeholder: "your_name", 48208 autoFocus: !0, 48209 autoComplete: "off", 48210 autoCorrect: "off", 48211 autoCapitalize: "off", 48212 spellCheck: !1, 48213 name: "tg-username", 48214 "data-lpignore": "true", 48215 "data-1p-ignore": "true", 48216 "data-form-type": "other", 48217 className: "w-full bg-transparent font-['Fira_Mono:Regular',sans-serif] text-[16px] text-[#121212] outline-none placeholder:opacity-40" 48218 } 48219 ) }) 48220 } 48221 ); 48222} 48223function bR() { 48224 const [n, e] = Xe(""), [t, i] = Xe(""), [r, s] = Xe(null), [a, l] = Xe(!1), o = hr(); 48225 async function c(h) { 48226 h.preventDefault(), s(null), l(!0); 48227 try { 48228 const d = await fetch(`${Dn}/login`, { 48229 method: "POST", 48230 headers: { "Content-Type": "application/json", Authorization: `Bearer ${$n}` }, 48231 body: JSON.stringify({ username: n, pin: t }) 48232 }), f = await d.json(); 48233 if (!d.ok) { 48234 s(f.error ?? "Login failed"); 48235 return; 48236 } 48237 Vm({ accessToken: f.accessToken, userId: f.userId, username: f.username }), o("/planet"); 48238 } catch { 48239 s("Network error â please try again"); 48240 } finally { 48241 l(!1); 48242 } 48243 } 48244 const u = n.length >= 1 && t.length === 4 && !a; 48245 return /* @__PURE__ */ re("div", { className: "size-full relative overflow-hidden bg-[#121212] flex items-center justify-center p-6", children: [ 48246 /* @__PURE__ */ P("div", { className: "absolute inset-0", children: /* @__PURE__ */ P(As, { mode: "grayscale", health: 0.4 }) }), 48247 /* @__PURE__ */ re("div", { className: "relative z-10 bg-[#32bb29] rounded-[48px] p-10 flex flex-col gap-8 items-center w-full max-w-[440px]", children: [
48248 /* @__PURE__ */ P("div", { className: "w-full", children: /* @__PURE__ */ P("p", { className: "font-['Boldonse:Regular',sans-serif] text-[32px] text-black leading-tight", children: "Welcome back." }) }), 48249 /* @__PURE__ */ re("form", { onSubmit: c, className: "w-full flex flex-col gap-6", children: [ 48250 /* @__PURE__ */ re("div", { className: "flex flex-col gap-2 w-full", children: [ 48251 /* @__PURE__ */ P("label", { className: "font-['Fira_Mono:Regular',sans-serif] text-[14px] text-[#121212] opacity-60 uppercase tracking-wider", children: "Username" }), 48252 /* @__PURE__ */ P(xR, { value: n, onChange: e }) 48253 ] }), 48254 /* @__PURE__ */ re("div", { className: "flex flex-col gap-2 w-full", children: [ 48255 /* @__PURE__ */ P("label", { className: "font-['Fira_Mono:Regular',sans-serif] text-[14px] text-[#121212] opacity-60 uppercase tracking-wider", children: "Pin Code" }), 48256 /* @__PURE__ */ P(yR, { value: t, onChange: i }) 48257 ] }), 48258 r && /* @__PURE__ */ P("div", { className: "bg-red-100 border border-red-400 rounded-xl p-3", children: /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[14px] text-red-700", children: r }) }),
48259 /* @__PURE__ */ P(or, { type: "submit", disabled: !u, className: "w-full", children: a ? /* @__PURE__ */ P(Ta, { size: 18, className: "animate-spin" }) : "Log in" }) 48260 ] }), 48261 /* @__PURE__ */ re("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[14px] text-[#121212] opacity-60", children: [ 48262 "New here?", 48263 " ", 48264 /* @__PURE__ */ P(Pu, { to: "/", className: "underline opacity-100 hover:opacity-70 transition-opacity", children: "Create an account" }) 48265 ] }) 48266 ] }) 48267 ] }); 48268} 48269const kf = { 48270 p2ef17580: "M88.9167 51.3211C88.9086 57.2623 88.8641 62.3063 88.5287 66.449C88.1366 71.2586 87.3323 75.276 85.5378 78.6104C84.7537 80.0717 83.7597 81.4103 82.5874 82.5834C79.2207 85.9501 74.9365 87.4738 69.5045 88.2013C64.1978 88.9167 57.3917 88.9167 48.7142 88.9167H48.2858C39.6043 88.9167 32.8062 88.9167 27.4955 88.2013C22.0675 87.4738 17.7793 85.9501 14.4166 82.5834C11.4339 79.6006 9.88996 75.8904 9.07354 71.2869C8.26521 66.7603 8.11971 61.1343 8.09142 54.1462C8.08333 52.3679 8.08064 50.4858 8.08333 48.5V48.2818C8.08333 39.6003 8.08333 32.8022 8.79871 27.4914C9.52621 22.0635 11.0499 17.7752 14.4166 14.4126C17.7833 11.0499 22.0675 9.52217 27.4955 8.79467C32.2161 8.16013 38.2867 8.08737 45.6789 8.07929C46.4271 8.07929 47.1447 8.37651 47.6737 8.90557C48.2028 9.43462 48.5 10.1522 48.5 10.9004C48.5 11.6486 48.2028 12.3661 47.6737 12.8952C47.1447 13.4242 46.4271 13.7215 45.6789 13.7215C38.1816 13.7295 32.6082 13.7942 28.2472 14.3802C23.4417 15.0269 20.5438 16.2556 18.4017 18.3977C16.2596 20.5397 15.035 23.4417 14.3883 28.2512C13.7295 33.1417 13.7215 39.5598 13.7215 48.5V51.6687L17.4883 48.3788C19.1394 46.9341 21.2779 46.1709 23.4706 46.2437C25.6633 46.3165 27.7464 47.2198 29.298 48.7708L45.4243 64.897C46.6754 66.1489 48.3282 66.9192 50.0915 67.0723C51.8548 67.2253 53.6155 66.7513 55.0637 65.7337L56.1872 64.9455C58.2759 63.4775 60.8009 62.7616 63.3492 62.9151C65.8976 63.0685 68.3185 64.0822 70.2159 65.7902L80.8576 75.369C81.9286 73.1178 82.5672 70.1633 82.9067 65.9923C83.226 62.0638 83.2705 57.2947 83.2745 51.3211C83.2745 50.5729 83.5717 49.8553 84.1008 49.3263C84.6298 48.7972 85.3474 48.5 86.0956 48.5C86.8438 48.5 87.5613 48.7972 88.0904 49.3263C88.6194 49.8553 88.9167 50.5729 88.9167 51.3211Z", 48271 pbc34b00: "M70.7292 44.4583C62.1568 44.4583 57.8686 44.4583 55.2051 41.7949C52.5417 39.1314 52.5417 34.8432 52.5417 26.2708C52.5417 17.6985 52.5417 13.4102 55.2051 10.7468C57.8686 8.08333 62.1568 8.08333 70.7292 8.08333C79.3015 8.08333 83.5897 8.08333 86.2532 10.7468C88.9167 13.4102 88.9167 17.6985 88.9167 26.2708C88.9167 34.8432 88.9167 39.1314 86.2532 41.7949C83.5897 44.4583 79.3015 44.4583 70.7292 44.4583ZM73.7604 18.1875C73.7604 17.3836 73.4411 16.6126 72.8726 16.0441C72.3041 15.4756 71.5331 15.1562 70.7292 15.1562C69.9252 15.1562 69.1542 15.4756 68.5857 16.0441C68.0173 16.6126 67.6979 17.3836 67.6979 18.1875V23.2396H62.6458C61.8419 23.2396 61.0709 23.5589 60.5024 24.1274C59.9339 24.6959 59.6146 25.4669 59.6146 26.2708C59.6146 27.0748 59.9339 27.8458 60.5024 28.4143C61.0709 28.9827 61.8419 29.3021 62.6458 29.3021H67.6979V34.3542C67.6979 35.1581 68.0173 35.9291 68.5857 36.4976C69.1542 37.0661 69.9252 37.3854 70.7292 37.3854C71.5331 37.3854 72.3041 37.0661 72.8726 36.4976C73.4411 35.9291 73.7604 35.1581 73.7604 34.3542V29.3021H78.8125C79.6164 29.3021 80.3875 28.9827 80.9559 28.4143C81.5244 27.8458 81.8438 27.0748 81.8438 26.2708C81.8438 25.4669 81.5244 24.6959 80.9559 24.1274C80.3875 23.5589 79.6164 23.2396 78.8125 23.2396H73.7604V18.1875Z" 48272}; 48273function wR() { 48274 return /* @__PURE__ */ re("svg", { className: "block", fill: "none", viewBox: "0 0 97 97", width: 97, height: 97, children: [ 48275 /* @__PURE__ */ P("path", { d: kf.p2ef17580, fill: "black" }), 48276 /* @__PURE__ */ P("path", { clipRule: "evenodd", d: kf.pbc34b00, fill: "black", fillRule: "evenodd" }) 48277 ] }); 48278} 48279function SR() { 48280 const { code: n } = B0(), [e, t] = Xe({ phase: "idle" }), i = mt(null); 48281 function r(l) { 48282 const o = l.target.files?.[0]; 48283 o && t({ phase: "previewing", file: o, previewUrl: URL.createObjectURL(o) }); 48284 } 48285 async function s() { 48286 if (!(e.phase !== "previewing" || !n)) { 48287 t({ phase: "uploading" });
48288 try { 48289 const l = await jm(e.file), o = new FormData(); 48290 o.append("code", n), o.append("photo", l); 48291 const c = await fetch(`${Dn}/pair/submit`, { 48292 method: "POST", 48293 headers: { Authorization: `Bearer ${$n}` }, 48294 body: o 48295 }), u = await c.json(); 48296 if (!c.ok) { 48297 t({ phase: "error", message: u.error ?? "Upload failed" }); 48298 return; 48299 } 48300 t({ phase: "success" }); 48301 } catch { 48302 t({ phase: "error", message: "Network error â please try again" }); 48303 } 48304 } 48305 } 48306 function a() { 48307 e.phase === "previewing" && URL.revokeObjectURL(e.previewUrl), t({ phase: "idle" }), i.current && (i.current.value = ""); 48308 } 48309 return /* @__PURE__ */ P("div", { className: "min-h-dvh bg-[#32bb29] flex flex-col items-center justify-center overflow-hidden relative", children: /* @__PURE__ */ re("div", { className: "flex flex-col gap-7 items-center w-full max-w-[min(365px,calc(100vw-2rem))]", children: [ 48310 /* @__PURE__ */ re("div", { className: "flex flex-col gap-3 items-center text-center", children: [
48311 /* @__PURE__ */ P("p", { className: "font-['Boldonse:Regular',sans-serif] text-[clamp(28px,8vw,40px)] text-black whitespace-nowrap", children: "Get Started" }), 48312 /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[clamp(15px,4.5vw,24px)] text-[#121212] text-center", children: "Upload your outdoor photo" }) 48313 ] }), 48314 e.phase === "idle" && /* @__PURE__ */ re(rr, { children: [ 48315 /* @__PURE__ */ re( 48316 "button", 48317 { 48318 onClick: () => i.current?.click(), 48319 className: "w-full relative rounded-[40px] active:scale-[0.98] transition-transform", 48320 children: [ 48321 /* @__PURE__ */ P( 48322 "div", 48323 { 48324 className: "absolute inset-0 rounded-[40px] pointer-events-none", 48325 style: { border: "2px dashed black" } 48326 } 48327 ), 48328 /* @__PURE__ */ re("div", { className: "flex flex-col gap-6 items-center justify-center p-8 w-full", children: [ 48329 /* @__PURE__ */ P(wR, {}),
48330 /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[clamp(15px,4.5vw,24px)] text-[#121212] text-center", children: "Take/Choose Photo" }) 48331 ] }) 48332 ] 48333 } 48334 ), 48335 /* @__PURE__ */ P( 48336 "input", 48337 { 48338 ref: i, 48339 type: "file", 48340 accept: "image/*", 48341 onChange: r, 48342 className: "hidden" 48343 } 48344 ) 48345 ] }), 48346 e.phase === "previewing" && /* @__PURE__ */ re("div", { className: "w-full flex flex-col gap-4", children: [ 48347 /* @__PURE__ */ P("div", { className: "w-full rounded-[24px] overflow-hidden aspect-[4/3]", children: /* @__PURE__ */ P( 48348 "img", 48349 { 48350 src: e.previewUrl, 48351 alt: "Your outdoor photo", 48352 className: "w-full h-full object-cover" 48353 } 48354 ) }), 48355 /* @__PURE__ */ re("div", { className: "flex gap-3 w-full", children: [ 48356 /* @__PURE__ */ P( 48357 "button", 48358 { 48359 className: "flex-1 bg-white/40 rounded-[40px] py-4 font-['Fira_Mono:Regular',sans-serif] text-[clamp(14px,4vw,18px)] text-black active:scale-[0.98] transition-transform", 48360 onClick: a, 48361 children: "Retake" 48362 } 48363 ),
48364 /* @__PURE__ */ P( 48365 "button", 48366 { 48367 className: "flex-[2] bg-black rounded-[40px] py-4 font-['Fira_Mono:Regular',sans-serif] text-[clamp(14px,4vw,18px)] text-white active:scale-[0.98] transition-transform", 48368 onClick: s, 48369 children: "Upload Photo" 48370 } 48371 ) 48372 ] }) 48373 ] }), 48374 e.phase === "uploading" && /* @__PURE__ */ re("div", { className: "flex flex-col items-center gap-6 py-8", children: [ 48375 /* @__PURE__ */ P(Ta, { size: 48, className: "animate-spin text-black" }), 48376 /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[clamp(15px,4.5vw,24px)] text-[#121212] text-center", children: "Uploadingâ¦" }) 48377 ] }), 48378 e.phase === "success" && /* @__PURE__ */ re("div", { className: "flex flex-col items-center gap-6 py-8", children: [ 48379 /* @__PURE__ */ P("div", { className: "w-20 h-20 rounded-full bg-black/10 flex items-center justify-center", children: /* @__PURE__ */ P(yA, { size: 48, className: "text-black" }) }),
48380 /* @__PURE__ */ re("div", { className: "flex flex-col items-center gap-2 text-center", children: [ 48381 /* @__PURE__ */ P("p", { className: "font-['Boldonse:Regular',sans-serif] text-[clamp(22px,7vw,32px)] text-black", children: "Done!" }), 48382 /* @__PURE__ */ re("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[clamp(14px,4vw,18px)] text-[#121212] text-center", children: [ 48383 "Your photo is on its way.", 48384 /* @__PURE__ */ P("br", {}), 48385 "Check the desktop to create your account." 48386 ] }) 48387 ] }) 48388 ] }), 48389 e.phase === "error" && /* @__PURE__ */ re("div", { className: "flex flex-col items-center gap-5 py-8", children: [ 48390 /* @__PURE__ */ P(vA, { size: 40, className: "text-red-700" }), 48391 /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[clamp(14px,4vw,18px)] text-red-700 text-center", children: e.message }), 48392 /* @__PURE__ */ P( 48393 "button", 48394 { 48395 className: "bg-black rounded-[40px] px-8 py-4 font-['Fira_Mono:Regular',sans-serif] text-white text-[clamp(14px,4vw,18px)]", 48396 onClick: a, 48397 children: "Try Again" 48398 } 48399 ) 48400 ] }) 48401 ] }) }); 48402} 48403const Ff = Lv([ 48404 { path: "/", Component: fE }, 48405 { path: "/how", Component: PE }, 48406 { path: "/start", Component: kA }, 48407 { path: "/planet", Component: mR }, 48408 { path: "/signup", Component: _R }, 48409 { path: "/login", Component: bR }, 48410 { path: "/u/:code", Component: SR } 48411]); 48412function ER({ children: n }) { 48413 const [e, t] = Xe(() => window.innerWidth < 600); 48414 return bt(() => { 48415 function i() { 48416 t(window.innerWidth < 600); 48417 } 48418 return window.addEventListener("resize", i), () => window.removeEventListener("resize", i); 48419 }
48419, []), e ? /* @__PURE__ */ P("div", { className: "min-h-dvh bg-[#121212] flex flex-col items-center justify-center gap-8 p-8 text-center", children: /* @__PURE__ */ re("div", { className: "flex flex-col items-center gap-6", children: [ 48420 /* @__PURE__ */ P("div", { className: "w-20 h-20 rounded-full bg-[#32bb29] opacity-80" }), 48421 /* @__PURE__ */ re("div", { className: "flex flex-col gap-3", children: [ 48422 /* @__PURE__ */ P("p", { className: "font-['Boldonse:Regular',sans-serif] text-[28px] text-white leading-tight", children: "Open on desktop" }), 48423 /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[14px] text-white/60 max-w-[260px]", children: "Touch Grass is designed for a desktop experience. Visit this page on your computer to get started." }) 48424 ] }), 48425 /* @__PURE__ */ P("div", { className: "w-full max-w-[260px] h-px bg-white/10" }), 48426 /* @__PURE__ */ P("p", { className: "font-['Fira_Mono:Regular',sans-serif] text-[13px] text-[#32bb29]", children: "Already have a QR code to scan? You're in the right place â just open the link from your phone's camera." }) 48427 ] }) }) : /* @__PURE__ */ P(rr, { children: n }); 48428} 48429const MR = window.location.pathname.startsWith("/u/"); 48430function TR() { 48431 return MR ? /* @__PURE__ */ P(kh, { router: Ff }) : /* @__PURE__ */ P(ER, { children: /* @__PURE__ */ P(kh, { router: Ff }) }); 48432} 48433const AR = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ 48434 __proto__: null, 48435 default: TR 48436}, Symbol.toStringTag, { value: "Module" })); 48437export { 48438 RR as Code0_8 48439};
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.