pinia.js 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546
  1. import {
  2. del,
  3. isVue2,
  4. set
  5. } from "./chunk-RNWUNH7L.js";
  6. import {
  7. setupDevtoolsPlugin
  8. } from "./chunk-AYVSL3LM.js";
  9. import {
  10. computed,
  11. effectScope,
  12. getCurrentInstance,
  13. getCurrentScope,
  14. hasInjectionContext,
  15. inject,
  16. isReactive,
  17. isRef,
  18. markRaw,
  19. nextTick,
  20. onScopeDispose,
  21. reactive,
  22. ref,
  23. toRaw,
  24. toRef,
  25. toRefs,
  26. unref,
  27. watch
  28. } from "./chunk-LPAU6MA2.js";
  29. // node_modules/pinia/dist/pinia.mjs
  30. var activePinia;
  31. var setActivePinia = (pinia) => activePinia = pinia;
  32. var getActivePinia = () => hasInjectionContext() && inject(piniaSymbol) || activePinia;
  33. var piniaSymbol = true ? Symbol("pinia") : (
  34. /* istanbul ignore next */
  35. Symbol()
  36. );
  37. function isPlainObject(o) {
  38. return o && typeof o === "object" && Object.prototype.toString.call(o) === "[object Object]" && typeof o.toJSON !== "function";
  39. }
  40. var MutationType;
  41. (function(MutationType2) {
  42. MutationType2["direct"] = "direct";
  43. MutationType2["patchObject"] = "patch object";
  44. MutationType2["patchFunction"] = "patch function";
  45. })(MutationType || (MutationType = {}));
  46. var IS_CLIENT = typeof window !== "undefined";
  47. var _global = (() => typeof window === "object" && window.window === window ? window : typeof self === "object" && self.self === self ? self : typeof global === "object" && global.global === global ? global : typeof globalThis === "object" ? globalThis : { HTMLElement: null })();
  48. function bom(blob, { autoBom = false } = {}) {
  49. if (autoBom && /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  50. return new Blob([String.fromCharCode(65279), blob], { type: blob.type });
  51. }
  52. return blob;
  53. }
  54. function download(url, name, opts) {
  55. const xhr = new XMLHttpRequest();
  56. xhr.open("GET", url);
  57. xhr.responseType = "blob";
  58. xhr.onload = function() {
  59. saveAs(xhr.response, name, opts);
  60. };
  61. xhr.onerror = function() {
  62. console.error("could not download file");
  63. };
  64. xhr.send();
  65. }
  66. function corsEnabled(url) {
  67. const xhr = new XMLHttpRequest();
  68. xhr.open("HEAD", url, false);
  69. try {
  70. xhr.send();
  71. } catch (e) {
  72. }
  73. return xhr.status >= 200 && xhr.status <= 299;
  74. }
  75. function click(node) {
  76. try {
  77. node.dispatchEvent(new MouseEvent("click"));
  78. } catch (e) {
  79. const evt = document.createEvent("MouseEvents");
  80. evt.initMouseEvent("click", true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
  81. node.dispatchEvent(evt);
  82. }
  83. }
  84. var _navigator = typeof navigator === "object" ? navigator : { userAgent: "" };
  85. var isMacOSWebView = (() => /Macintosh/.test(_navigator.userAgent) && /AppleWebKit/.test(_navigator.userAgent) && !/Safari/.test(_navigator.userAgent))();
  86. var saveAs = !IS_CLIENT ? () => {
  87. } : (
  88. // Use download attribute first if possible (#193 Lumia mobile) unless this is a macOS WebView or mini program
  89. typeof HTMLAnchorElement !== "undefined" && "download" in HTMLAnchorElement.prototype && !isMacOSWebView ? downloadSaveAs : (
  90. // Use msSaveOrOpenBlob as a second approach
  91. "msSaveOrOpenBlob" in _navigator ? msSaveAs : (
  92. // Fallback to using FileReader and a popup
  93. fileSaverSaveAs
  94. )
  95. )
  96. );
  97. function downloadSaveAs(blob, name = "download", opts) {
  98. const a = document.createElement("a");
  99. a.download = name;
  100. a.rel = "noopener";
  101. if (typeof blob === "string") {
  102. a.href = blob;
  103. if (a.origin !== location.origin) {
  104. if (corsEnabled(a.href)) {
  105. download(blob, name, opts);
  106. } else {
  107. a.target = "_blank";
  108. click(a);
  109. }
  110. } else {
  111. click(a);
  112. }
  113. } else {
  114. a.href = URL.createObjectURL(blob);
  115. setTimeout(function() {
  116. URL.revokeObjectURL(a.href);
  117. }, 4e4);
  118. setTimeout(function() {
  119. click(a);
  120. }, 0);
  121. }
  122. }
  123. function msSaveAs(blob, name = "download", opts) {
  124. if (typeof blob === "string") {
  125. if (corsEnabled(blob)) {
  126. download(blob, name, opts);
  127. } else {
  128. const a = document.createElement("a");
  129. a.href = blob;
  130. a.target = "_blank";
  131. setTimeout(function() {
  132. click(a);
  133. });
  134. }
  135. } else {
  136. navigator.msSaveOrOpenBlob(bom(blob, opts), name);
  137. }
  138. }
  139. function fileSaverSaveAs(blob, name, opts, popup) {
  140. popup = popup || open("", "_blank");
  141. if (popup) {
  142. popup.document.title = popup.document.body.innerText = "downloading...";
  143. }
  144. if (typeof blob === "string")
  145. return download(blob, name, opts);
  146. const force = blob.type === "application/octet-stream";
  147. const isSafari = /constructor/i.test(String(_global.HTMLElement)) || "safari" in _global;
  148. const isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent);
  149. if ((isChromeIOS || force && isSafari || isMacOSWebView) && typeof FileReader !== "undefined") {
  150. const reader = new FileReader();
  151. reader.onloadend = function() {
  152. let url = reader.result;
  153. if (typeof url !== "string") {
  154. popup = null;
  155. throw new Error("Wrong reader.result type");
  156. }
  157. url = isChromeIOS ? url : url.replace(/^data:[^;]*;/, "data:attachment/file;");
  158. if (popup) {
  159. popup.location.href = url;
  160. } else {
  161. location.assign(url);
  162. }
  163. popup = null;
  164. };
  165. reader.readAsDataURL(blob);
  166. } else {
  167. const url = URL.createObjectURL(blob);
  168. if (popup)
  169. popup.location.assign(url);
  170. else
  171. location.href = url;
  172. popup = null;
  173. setTimeout(function() {
  174. URL.revokeObjectURL(url);
  175. }, 4e4);
  176. }
  177. }
  178. function toastMessage(message, type) {
  179. const piniaMessage = "🍍 " + message;
  180. if (typeof __VUE_DEVTOOLS_TOAST__ === "function") {
  181. __VUE_DEVTOOLS_TOAST__(piniaMessage, type);
  182. } else if (type === "error") {
  183. console.error(piniaMessage);
  184. } else if (type === "warn") {
  185. console.warn(piniaMessage);
  186. } else {
  187. console.log(piniaMessage);
  188. }
  189. }
  190. function isPinia(o) {
  191. return "_a" in o && "install" in o;
  192. }
  193. function checkClipboardAccess() {
  194. if (!("clipboard" in navigator)) {
  195. toastMessage(`Your browser doesn't support the Clipboard API`, "error");
  196. return true;
  197. }
  198. }
  199. function checkNotFocusedError(error) {
  200. if (error instanceof Error && error.message.toLowerCase().includes("document is not focused")) {
  201. toastMessage('You need to activate the "Emulate a focused page" setting in the "Rendering" panel of devtools.', "warn");
  202. return true;
  203. }
  204. return false;
  205. }
  206. async function actionGlobalCopyState(pinia) {
  207. if (checkClipboardAccess())
  208. return;
  209. try {
  210. await navigator.clipboard.writeText(JSON.stringify(pinia.state.value));
  211. toastMessage("Global state copied to clipboard.");
  212. } catch (error) {
  213. if (checkNotFocusedError(error))
  214. return;
  215. toastMessage(`Failed to serialize the state. Check the console for more details.`, "error");
  216. console.error(error);
  217. }
  218. }
  219. async function actionGlobalPasteState(pinia) {
  220. if (checkClipboardAccess())
  221. return;
  222. try {
  223. loadStoresState(pinia, JSON.parse(await navigator.clipboard.readText()));
  224. toastMessage("Global state pasted from clipboard.");
  225. } catch (error) {
  226. if (checkNotFocusedError(error))
  227. return;
  228. toastMessage(`Failed to deserialize the state from clipboard. Check the console for more details.`, "error");
  229. console.error(error);
  230. }
  231. }
  232. async function actionGlobalSaveState(pinia) {
  233. try {
  234. saveAs(new Blob([JSON.stringify(pinia.state.value)], {
  235. type: "text/plain;charset=utf-8"
  236. }), "pinia-state.json");
  237. } catch (error) {
  238. toastMessage(`Failed to export the state as JSON. Check the console for more details.`, "error");
  239. console.error(error);
  240. }
  241. }
  242. var fileInput;
  243. function getFileOpener() {
  244. if (!fileInput) {
  245. fileInput = document.createElement("input");
  246. fileInput.type = "file";
  247. fileInput.accept = ".json";
  248. }
  249. function openFile() {
  250. return new Promise((resolve, reject) => {
  251. fileInput.onchange = async () => {
  252. const files = fileInput.files;
  253. if (!files)
  254. return resolve(null);
  255. const file = files.item(0);
  256. if (!file)
  257. return resolve(null);
  258. return resolve({ text: await file.text(), file });
  259. };
  260. fileInput.oncancel = () => resolve(null);
  261. fileInput.onerror = reject;
  262. fileInput.click();
  263. });
  264. }
  265. return openFile;
  266. }
  267. async function actionGlobalOpenStateFile(pinia) {
  268. try {
  269. const open2 = getFileOpener();
  270. const result = await open2();
  271. if (!result)
  272. return;
  273. const { text, file } = result;
  274. loadStoresState(pinia, JSON.parse(text));
  275. toastMessage(`Global state imported from "${file.name}".`);
  276. } catch (error) {
  277. toastMessage(`Failed to import the state from JSON. Check the console for more details.`, "error");
  278. console.error(error);
  279. }
  280. }
  281. function loadStoresState(pinia, state) {
  282. for (const key in state) {
  283. const storeState = pinia.state.value[key];
  284. if (storeState) {
  285. Object.assign(storeState, state[key]);
  286. } else {
  287. pinia.state.value[key] = state[key];
  288. }
  289. }
  290. }
  291. function formatDisplay(display) {
  292. return {
  293. _custom: {
  294. display
  295. }
  296. };
  297. }
  298. var PINIA_ROOT_LABEL = "🍍 Pinia (root)";
  299. var PINIA_ROOT_ID = "_root";
  300. function formatStoreForInspectorTree(store) {
  301. return isPinia(store) ? {
  302. id: PINIA_ROOT_ID,
  303. label: PINIA_ROOT_LABEL
  304. } : {
  305. id: store.$id,
  306. label: store.$id
  307. };
  308. }
  309. function formatStoreForInspectorState(store) {
  310. if (isPinia(store)) {
  311. const storeNames = Array.from(store._s.keys());
  312. const storeMap = store._s;
  313. const state2 = {
  314. state: storeNames.map((storeId) => ({
  315. editable: true,
  316. key: storeId,
  317. value: store.state.value[storeId]
  318. })),
  319. getters: storeNames.filter((id) => storeMap.get(id)._getters).map((id) => {
  320. const store2 = storeMap.get(id);
  321. return {
  322. editable: false,
  323. key: id,
  324. value: store2._getters.reduce((getters, key) => {
  325. getters[key] = store2[key];
  326. return getters;
  327. }, {})
  328. };
  329. })
  330. };
  331. return state2;
  332. }
  333. const state = {
  334. state: Object.keys(store.$state).map((key) => ({
  335. editable: true,
  336. key,
  337. value: store.$state[key]
  338. }))
  339. };
  340. if (store._getters && store._getters.length) {
  341. state.getters = store._getters.map((getterName) => ({
  342. editable: false,
  343. key: getterName,
  344. value: store[getterName]
  345. }));
  346. }
  347. if (store._customProperties.size) {
  348. state.customProperties = Array.from(store._customProperties).map((key) => ({
  349. editable: true,
  350. key,
  351. value: store[key]
  352. }));
  353. }
  354. return state;
  355. }
  356. function formatEventData(events) {
  357. if (!events)
  358. return {};
  359. if (Array.isArray(events)) {
  360. return events.reduce((data, event) => {
  361. data.keys.push(event.key);
  362. data.operations.push(event.type);
  363. data.oldValue[event.key] = event.oldValue;
  364. data.newValue[event.key] = event.newValue;
  365. return data;
  366. }, {
  367. oldValue: {},
  368. keys: [],
  369. operations: [],
  370. newValue: {}
  371. });
  372. } else {
  373. return {
  374. operation: formatDisplay(events.type),
  375. key: formatDisplay(events.key),
  376. oldValue: events.oldValue,
  377. newValue: events.newValue
  378. };
  379. }
  380. }
  381. function formatMutationType(type) {
  382. switch (type) {
  383. case MutationType.direct:
  384. return "mutation";
  385. case MutationType.patchFunction:
  386. return "$patch";
  387. case MutationType.patchObject:
  388. return "$patch";
  389. default:
  390. return "unknown";
  391. }
  392. }
  393. var isTimelineActive = true;
  394. var componentStateTypes = [];
  395. var MUTATIONS_LAYER_ID = "pinia:mutations";
  396. var INSPECTOR_ID = "pinia";
  397. var { assign: assign$1 } = Object;
  398. var getStoreType = (id) => "🍍 " + id;
  399. function registerPiniaDevtools(app, pinia) {
  400. setupDevtoolsPlugin({
  401. id: "dev.esm.pinia",
  402. label: "Pinia 🍍",
  403. logo: "https://pinia.vuejs.org/logo.svg",
  404. packageName: "pinia",
  405. homepage: "https://pinia.vuejs.org",
  406. componentStateTypes,
  407. app
  408. }, (api) => {
  409. if (typeof api.now !== "function") {
  410. toastMessage("You seem to be using an outdated version of Vue Devtools. Are you still using the Beta release instead of the stable one? You can find the links at https://devtools.vuejs.org/guide/installation.html.");
  411. }
  412. api.addTimelineLayer({
  413. id: MUTATIONS_LAYER_ID,
  414. label: `Pinia 🍍`,
  415. color: 15064968
  416. });
  417. api.addInspector({
  418. id: INSPECTOR_ID,
  419. label: "Pinia 🍍",
  420. icon: "storage",
  421. treeFilterPlaceholder: "Search stores",
  422. actions: [
  423. {
  424. icon: "content_copy",
  425. action: () => {
  426. actionGlobalCopyState(pinia);
  427. },
  428. tooltip: "Serialize and copy the state"
  429. },
  430. {
  431. icon: "content_paste",
  432. action: async () => {
  433. await actionGlobalPasteState(pinia);
  434. api.sendInspectorTree(INSPECTOR_ID);
  435. api.sendInspectorState(INSPECTOR_ID);
  436. },
  437. tooltip: "Replace the state with the content of your clipboard"
  438. },
  439. {
  440. icon: "save",
  441. action: () => {
  442. actionGlobalSaveState(pinia);
  443. },
  444. tooltip: "Save the state as a JSON file"
  445. },
  446. {
  447. icon: "folder_open",
  448. action: async () => {
  449. await actionGlobalOpenStateFile(pinia);
  450. api.sendInspectorTree(INSPECTOR_ID);
  451. api.sendInspectorState(INSPECTOR_ID);
  452. },
  453. tooltip: "Import the state from a JSON file"
  454. }
  455. ],
  456. nodeActions: [
  457. {
  458. icon: "restore",
  459. tooltip: 'Reset the state (with "$reset")',
  460. action: (nodeId) => {
  461. const store = pinia._s.get(nodeId);
  462. if (!store) {
  463. toastMessage(`Cannot reset "${nodeId}" store because it wasn't found.`, "warn");
  464. } else if (typeof store.$reset !== "function") {
  465. toastMessage(`Cannot reset "${nodeId}" store because it doesn't have a "$reset" method implemented.`, "warn");
  466. } else {
  467. store.$reset();
  468. toastMessage(`Store "${nodeId}" reset.`);
  469. }
  470. }
  471. }
  472. ]
  473. });
  474. api.on.inspectComponent((payload, ctx) => {
  475. const proxy = payload.componentInstance && payload.componentInstance.proxy;
  476. if (proxy && proxy._pStores) {
  477. const piniaStores = payload.componentInstance.proxy._pStores;
  478. Object.values(piniaStores).forEach((store) => {
  479. payload.instanceData.state.push({
  480. type: getStoreType(store.$id),
  481. key: "state",
  482. editable: true,
  483. value: store._isOptionsAPI ? {
  484. _custom: {
  485. value: toRaw(store.$state),
  486. actions: [
  487. {
  488. icon: "restore",
  489. tooltip: "Reset the state of this store",
  490. action: () => store.$reset()
  491. }
  492. ]
  493. }
  494. } : (
  495. // NOTE: workaround to unwrap transferred refs
  496. Object.keys(store.$state).reduce((state, key) => {
  497. state[key] = store.$state[key];
  498. return state;
  499. }, {})
  500. )
  501. });
  502. if (store._getters && store._getters.length) {
  503. payload.instanceData.state.push({
  504. type: getStoreType(store.$id),
  505. key: "getters",
  506. editable: false,
  507. value: store._getters.reduce((getters, key) => {
  508. try {
  509. getters[key] = store[key];
  510. } catch (error) {
  511. getters[key] = error;
  512. }
  513. return getters;
  514. }, {})
  515. });
  516. }
  517. });
  518. }
  519. });
  520. api.on.getInspectorTree((payload) => {
  521. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  522. let stores = [pinia];
  523. stores = stores.concat(Array.from(pinia._s.values()));
  524. payload.rootNodes = (payload.filter ? stores.filter((store) => "$id" in store ? store.$id.toLowerCase().includes(payload.filter.toLowerCase()) : PINIA_ROOT_LABEL.toLowerCase().includes(payload.filter.toLowerCase())) : stores).map(formatStoreForInspectorTree);
  525. }
  526. });
  527. globalThis.$pinia = pinia;
  528. api.on.getInspectorState((payload) => {
  529. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  530. const inspectedStore = payload.nodeId === PINIA_ROOT_ID ? pinia : pinia._s.get(payload.nodeId);
  531. if (!inspectedStore) {
  532. return;
  533. }
  534. if (inspectedStore) {
  535. if (payload.nodeId !== PINIA_ROOT_ID)
  536. globalThis.$store = toRaw(inspectedStore);
  537. payload.state = formatStoreForInspectorState(inspectedStore);
  538. }
  539. }
  540. });
  541. api.on.editInspectorState((payload, ctx) => {
  542. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  543. const inspectedStore = payload.nodeId === PINIA_ROOT_ID ? pinia : pinia._s.get(payload.nodeId);
  544. if (!inspectedStore) {
  545. return toastMessage(`store "${payload.nodeId}" not found`, "error");
  546. }
  547. const { path } = payload;
  548. if (!isPinia(inspectedStore)) {
  549. if (path.length !== 1 || !inspectedStore._customProperties.has(path[0]) || path[0] in inspectedStore.$state) {
  550. path.unshift("$state");
  551. }
  552. } else {
  553. path.unshift("state");
  554. }
  555. isTimelineActive = false;
  556. payload.set(inspectedStore, path, payload.state.value);
  557. isTimelineActive = true;
  558. }
  559. });
  560. api.on.editComponentState((payload) => {
  561. if (payload.type.startsWith("🍍")) {
  562. const storeId = payload.type.replace(/^🍍\s*/, "");
  563. const store = pinia._s.get(storeId);
  564. if (!store) {
  565. return toastMessage(`store "${storeId}" not found`, "error");
  566. }
  567. const { path } = payload;
  568. if (path[0] !== "state") {
  569. return toastMessage(`Invalid path for store "${storeId}":
  570. ${path}
  571. Only state can be modified.`);
  572. }
  573. path[0] = "$state";
  574. isTimelineActive = false;
  575. payload.set(store, path, payload.state.value);
  576. isTimelineActive = true;
  577. }
  578. });
  579. });
  580. }
  581. function addStoreToDevtools(app, store) {
  582. if (!componentStateTypes.includes(getStoreType(store.$id))) {
  583. componentStateTypes.push(getStoreType(store.$id));
  584. }
  585. setupDevtoolsPlugin({
  586. id: "dev.esm.pinia",
  587. label: "Pinia 🍍",
  588. logo: "https://pinia.vuejs.org/logo.svg",
  589. packageName: "pinia",
  590. homepage: "https://pinia.vuejs.org",
  591. componentStateTypes,
  592. app,
  593. settings: {
  594. logStoreChanges: {
  595. label: "Notify about new/deleted stores",
  596. type: "boolean",
  597. defaultValue: true
  598. }
  599. // useEmojis: {
  600. // label: 'Use emojis in messages ⚡️',
  601. // type: 'boolean',
  602. // defaultValue: true,
  603. // },
  604. }
  605. }, (api) => {
  606. const now = typeof api.now === "function" ? api.now.bind(api) : Date.now;
  607. store.$onAction(({ after, onError, name, args }) => {
  608. const groupId = runningActionId++;
  609. api.addTimelineEvent({
  610. layerId: MUTATIONS_LAYER_ID,
  611. event: {
  612. time: now(),
  613. title: "🛫 " + name,
  614. subtitle: "start",
  615. data: {
  616. store: formatDisplay(store.$id),
  617. action: formatDisplay(name),
  618. args
  619. },
  620. groupId
  621. }
  622. });
  623. after((result) => {
  624. activeAction = void 0;
  625. api.addTimelineEvent({
  626. layerId: MUTATIONS_LAYER_ID,
  627. event: {
  628. time: now(),
  629. title: "🛬 " + name,
  630. subtitle: "end",
  631. data: {
  632. store: formatDisplay(store.$id),
  633. action: formatDisplay(name),
  634. args,
  635. result
  636. },
  637. groupId
  638. }
  639. });
  640. });
  641. onError((error) => {
  642. activeAction = void 0;
  643. api.addTimelineEvent({
  644. layerId: MUTATIONS_LAYER_ID,
  645. event: {
  646. time: now(),
  647. logType: "error",
  648. title: "💥 " + name,
  649. subtitle: "end",
  650. data: {
  651. store: formatDisplay(store.$id),
  652. action: formatDisplay(name),
  653. args,
  654. error
  655. },
  656. groupId
  657. }
  658. });
  659. });
  660. }, true);
  661. store._customProperties.forEach((name) => {
  662. watch(() => unref(store[name]), (newValue, oldValue) => {
  663. api.notifyComponentUpdate();
  664. api.sendInspectorState(INSPECTOR_ID);
  665. if (isTimelineActive) {
  666. api.addTimelineEvent({
  667. layerId: MUTATIONS_LAYER_ID,
  668. event: {
  669. time: now(),
  670. title: "Change",
  671. subtitle: name,
  672. data: {
  673. newValue,
  674. oldValue
  675. },
  676. groupId: activeAction
  677. }
  678. });
  679. }
  680. }, { deep: true });
  681. });
  682. store.$subscribe(({ events, type }, state) => {
  683. api.notifyComponentUpdate();
  684. api.sendInspectorState(INSPECTOR_ID);
  685. if (!isTimelineActive)
  686. return;
  687. const eventData = {
  688. time: now(),
  689. title: formatMutationType(type),
  690. data: assign$1({ store: formatDisplay(store.$id) }, formatEventData(events)),
  691. groupId: activeAction
  692. };
  693. if (type === MutationType.patchFunction) {
  694. eventData.subtitle = "⤵️";
  695. } else if (type === MutationType.patchObject) {
  696. eventData.subtitle = "🧩";
  697. } else if (events && !Array.isArray(events)) {
  698. eventData.subtitle = events.type;
  699. }
  700. if (events) {
  701. eventData.data["rawEvent(s)"] = {
  702. _custom: {
  703. display: "DebuggerEvent",
  704. type: "object",
  705. tooltip: "raw DebuggerEvent[]",
  706. value: events
  707. }
  708. };
  709. }
  710. api.addTimelineEvent({
  711. layerId: MUTATIONS_LAYER_ID,
  712. event: eventData
  713. });
  714. }, { detached: true, flush: "sync" });
  715. const hotUpdate = store._hotUpdate;
  716. store._hotUpdate = markRaw((newStore) => {
  717. hotUpdate(newStore);
  718. api.addTimelineEvent({
  719. layerId: MUTATIONS_LAYER_ID,
  720. event: {
  721. time: now(),
  722. title: "🔥 " + store.$id,
  723. subtitle: "HMR update",
  724. data: {
  725. store: formatDisplay(store.$id),
  726. info: formatDisplay(`HMR update`)
  727. }
  728. }
  729. });
  730. api.notifyComponentUpdate();
  731. api.sendInspectorTree(INSPECTOR_ID);
  732. api.sendInspectorState(INSPECTOR_ID);
  733. });
  734. const { $dispose } = store;
  735. store.$dispose = () => {
  736. $dispose();
  737. api.notifyComponentUpdate();
  738. api.sendInspectorTree(INSPECTOR_ID);
  739. api.sendInspectorState(INSPECTOR_ID);
  740. api.getSettings().logStoreChanges && toastMessage(`Disposed "${store.$id}" store 🗑`);
  741. };
  742. api.notifyComponentUpdate();
  743. api.sendInspectorTree(INSPECTOR_ID);
  744. api.sendInspectorState(INSPECTOR_ID);
  745. api.getSettings().logStoreChanges && toastMessage(`"${store.$id}" store installed 🆕`);
  746. });
  747. }
  748. var runningActionId = 0;
  749. var activeAction;
  750. function patchActionForGrouping(store, actionNames, wrapWithProxy) {
  751. const actions = actionNames.reduce((storeActions, actionName) => {
  752. storeActions[actionName] = toRaw(store)[actionName];
  753. return storeActions;
  754. }, {});
  755. for (const actionName in actions) {
  756. store[actionName] = function() {
  757. const _actionId = runningActionId;
  758. const trackedStore = wrapWithProxy ? new Proxy(store, {
  759. get(...args) {
  760. activeAction = _actionId;
  761. return Reflect.get(...args);
  762. },
  763. set(...args) {
  764. activeAction = _actionId;
  765. return Reflect.set(...args);
  766. }
  767. }) : store;
  768. activeAction = _actionId;
  769. const retValue = actions[actionName].apply(trackedStore, arguments);
  770. activeAction = void 0;
  771. return retValue;
  772. };
  773. }
  774. }
  775. function devtoolsPlugin({ app, store, options }) {
  776. if (store.$id.startsWith("__hot:")) {
  777. return;
  778. }
  779. store._isOptionsAPI = !!options.state;
  780. if (!store._p._testing) {
  781. patchActionForGrouping(store, Object.keys(options.actions), store._isOptionsAPI);
  782. const originalHotUpdate = store._hotUpdate;
  783. toRaw(store)._hotUpdate = function(newStore) {
  784. originalHotUpdate.apply(this, arguments);
  785. patchActionForGrouping(store, Object.keys(newStore._hmrPayload.actions), !!store._isOptionsAPI);
  786. };
  787. }
  788. addStoreToDevtools(
  789. app,
  790. // FIXME: is there a way to allow the assignment from Store<Id, S, G, A> to StoreGeneric?
  791. store
  792. );
  793. }
  794. function createPinia() {
  795. const scope = effectScope(true);
  796. const state = scope.run(() => ref({}));
  797. let _p = [];
  798. let toBeInstalled = [];
  799. const pinia = markRaw({
  800. install(app) {
  801. setActivePinia(pinia);
  802. if (!isVue2) {
  803. pinia._a = app;
  804. app.provide(piniaSymbol, pinia);
  805. app.config.globalProperties.$pinia = pinia;
  806. if (IS_CLIENT) {
  807. registerPiniaDevtools(app, pinia);
  808. }
  809. toBeInstalled.forEach((plugin) => _p.push(plugin));
  810. toBeInstalled = [];
  811. }
  812. },
  813. use(plugin) {
  814. if (!this._a && !isVue2) {
  815. toBeInstalled.push(plugin);
  816. } else {
  817. _p.push(plugin);
  818. }
  819. return this;
  820. },
  821. _p,
  822. // it's actually undefined here
  823. // @ts-expect-error
  824. _a: null,
  825. _e: scope,
  826. _s: /* @__PURE__ */ new Map(),
  827. state
  828. });
  829. if (IS_CLIENT && typeof Proxy !== "undefined") {
  830. pinia.use(devtoolsPlugin);
  831. }
  832. return pinia;
  833. }
  834. function disposePinia(pinia) {
  835. pinia._e.stop();
  836. pinia._s.clear();
  837. pinia._p.splice(0);
  838. pinia.state.value = {};
  839. pinia._a = null;
  840. }
  841. var isUseStore = (fn) => {
  842. return typeof fn === "function" && typeof fn.$id === "string";
  843. };
  844. function patchObject(newState, oldState) {
  845. for (const key in oldState) {
  846. const subPatch = oldState[key];
  847. if (!(key in newState)) {
  848. continue;
  849. }
  850. const targetValue = newState[key];
  851. if (isPlainObject(targetValue) && isPlainObject(subPatch) && !isRef(subPatch) && !isReactive(subPatch)) {
  852. newState[key] = patchObject(targetValue, subPatch);
  853. } else {
  854. if (isVue2) {
  855. set(newState, key, subPatch);
  856. } else {
  857. newState[key] = subPatch;
  858. }
  859. }
  860. }
  861. return newState;
  862. }
  863. function acceptHMRUpdate(initialUseStore, hot) {
  864. if (false) {
  865. return () => {
  866. };
  867. }
  868. return (newModule) => {
  869. const pinia = hot.data.pinia || initialUseStore._pinia;
  870. if (!pinia) {
  871. return;
  872. }
  873. hot.data.pinia = pinia;
  874. for (const exportName in newModule) {
  875. const useStore = newModule[exportName];
  876. if (isUseStore(useStore) && pinia._s.has(useStore.$id)) {
  877. const id = useStore.$id;
  878. if (id !== initialUseStore.$id) {
  879. console.warn(`The id of the store changed from "${initialUseStore.$id}" to "${id}". Reloading.`);
  880. return hot.invalidate();
  881. }
  882. const existingStore = pinia._s.get(id);
  883. if (!existingStore) {
  884. console.log(`[Pinia]: skipping hmr because store doesn't exist yet`);
  885. return;
  886. }
  887. useStore(pinia, existingStore);
  888. }
  889. }
  890. };
  891. }
  892. var noop = () => {
  893. };
  894. function addSubscription(subscriptions, callback, detached, onCleanup = noop) {
  895. subscriptions.push(callback);
  896. const removeSubscription = () => {
  897. const idx = subscriptions.indexOf(callback);
  898. if (idx > -1) {
  899. subscriptions.splice(idx, 1);
  900. onCleanup();
  901. }
  902. };
  903. if (!detached && getCurrentScope()) {
  904. onScopeDispose(removeSubscription);
  905. }
  906. return removeSubscription;
  907. }
  908. function triggerSubscriptions(subscriptions, ...args) {
  909. subscriptions.slice().forEach((callback) => {
  910. callback(...args);
  911. });
  912. }
  913. var fallbackRunWithContext = (fn) => fn();
  914. var ACTION_MARKER = Symbol();
  915. var ACTION_NAME = Symbol();
  916. function mergeReactiveObjects(target, patchToApply) {
  917. if (target instanceof Map && patchToApply instanceof Map) {
  918. patchToApply.forEach((value, key) => target.set(key, value));
  919. } else if (target instanceof Set && patchToApply instanceof Set) {
  920. patchToApply.forEach(target.add, target);
  921. }
  922. for (const key in patchToApply) {
  923. if (!patchToApply.hasOwnProperty(key))
  924. continue;
  925. const subPatch = patchToApply[key];
  926. const targetValue = target[key];
  927. if (isPlainObject(targetValue) && isPlainObject(subPatch) && target.hasOwnProperty(key) && !isRef(subPatch) && !isReactive(subPatch)) {
  928. target[key] = mergeReactiveObjects(targetValue, subPatch);
  929. } else {
  930. target[key] = subPatch;
  931. }
  932. }
  933. return target;
  934. }
  935. var skipHydrateSymbol = true ? Symbol("pinia:skipHydration") : (
  936. /* istanbul ignore next */
  937. Symbol()
  938. );
  939. function skipHydrate(obj) {
  940. return Object.defineProperty(obj, skipHydrateSymbol, {});
  941. }
  942. function shouldHydrate(obj) {
  943. return !isPlainObject(obj) || !obj.hasOwnProperty(skipHydrateSymbol);
  944. }
  945. var { assign } = Object;
  946. function isComputed(o) {
  947. return !!(isRef(o) && o.effect);
  948. }
  949. function createOptionsStore(id, options, pinia, hot) {
  950. const { state, actions, getters } = options;
  951. const initialState = pinia.state.value[id];
  952. let store;
  953. function setup() {
  954. if (!initialState && !hot) {
  955. if (isVue2) {
  956. set(pinia.state.value, id, state ? state() : {});
  957. } else {
  958. pinia.state.value[id] = state ? state() : {};
  959. }
  960. }
  961. const localState = hot ? (
  962. // use ref() to unwrap refs inside state TODO: check if this is still necessary
  963. toRefs(ref(state ? state() : {}).value)
  964. ) : toRefs(pinia.state.value[id]);
  965. return assign(localState, actions, Object.keys(getters || {}).reduce((computedGetters, name) => {
  966. if (name in localState) {
  967. console.warn(`[🍍]: A getter cannot have the same name as another state property. Rename one of them. Found with "${name}" in store "${id}".`);
  968. }
  969. computedGetters[name] = markRaw(computed(() => {
  970. setActivePinia(pinia);
  971. const store2 = pinia._s.get(id);
  972. if (isVue2 && !store2._r)
  973. return;
  974. return getters[name].call(store2, store2);
  975. }));
  976. return computedGetters;
  977. }, {}));
  978. }
  979. store = createSetupStore(id, setup, options, pinia, hot, true);
  980. return store;
  981. }
  982. function createSetupStore($id, setup, options = {}, pinia, hot, isOptionsStore) {
  983. let scope;
  984. const optionsForPlugin = assign({ actions: {} }, options);
  985. if (!pinia._e.active) {
  986. throw new Error("Pinia destroyed");
  987. }
  988. const $subscribeOptions = { deep: true };
  989. if (!isVue2) {
  990. $subscribeOptions.onTrigger = (event) => {
  991. if (isListening) {
  992. debuggerEvents = event;
  993. } else if (isListening == false && !store._hotUpdating) {
  994. if (Array.isArray(debuggerEvents)) {
  995. debuggerEvents.push(event);
  996. } else {
  997. console.error("🍍 debuggerEvents should be an array. This is most likely an internal Pinia bug.");
  998. }
  999. }
  1000. };
  1001. }
  1002. let isListening;
  1003. let isSyncListening;
  1004. let subscriptions = [];
  1005. let actionSubscriptions = [];
  1006. let debuggerEvents;
  1007. const initialState = pinia.state.value[$id];
  1008. if (!isOptionsStore && !initialState && !hot) {
  1009. if (isVue2) {
  1010. set(pinia.state.value, $id, {});
  1011. } else {
  1012. pinia.state.value[$id] = {};
  1013. }
  1014. }
  1015. const hotState = ref({});
  1016. let activeListener;
  1017. function $patch(partialStateOrMutator) {
  1018. let subscriptionMutation;
  1019. isListening = isSyncListening = false;
  1020. if (true) {
  1021. debuggerEvents = [];
  1022. }
  1023. if (typeof partialStateOrMutator === "function") {
  1024. partialStateOrMutator(pinia.state.value[$id]);
  1025. subscriptionMutation = {
  1026. type: MutationType.patchFunction,
  1027. storeId: $id,
  1028. events: debuggerEvents
  1029. };
  1030. } else {
  1031. mergeReactiveObjects(pinia.state.value[$id], partialStateOrMutator);
  1032. subscriptionMutation = {
  1033. type: MutationType.patchObject,
  1034. payload: partialStateOrMutator,
  1035. storeId: $id,
  1036. events: debuggerEvents
  1037. };
  1038. }
  1039. const myListenerId = activeListener = Symbol();
  1040. nextTick().then(() => {
  1041. if (activeListener === myListenerId) {
  1042. isListening = true;
  1043. }
  1044. });
  1045. isSyncListening = true;
  1046. triggerSubscriptions(subscriptions, subscriptionMutation, pinia.state.value[$id]);
  1047. }
  1048. const $reset = isOptionsStore ? function $reset2() {
  1049. const { state } = options;
  1050. const newState = state ? state() : {};
  1051. this.$patch(($state) => {
  1052. assign($state, newState);
  1053. });
  1054. } : (
  1055. /* istanbul ignore next */
  1056. true ? () => {
  1057. throw new Error(`🍍: Store "${$id}" is built using the setup syntax and does not implement $reset().`);
  1058. } : noop
  1059. );
  1060. function $dispose() {
  1061. scope.stop();
  1062. subscriptions = [];
  1063. actionSubscriptions = [];
  1064. pinia._s.delete($id);
  1065. }
  1066. const action = (fn, name = "") => {
  1067. if (ACTION_MARKER in fn) {
  1068. fn[ACTION_NAME] = name;
  1069. return fn;
  1070. }
  1071. const wrappedAction = function() {
  1072. setActivePinia(pinia);
  1073. const args = Array.from(arguments);
  1074. const afterCallbackList = [];
  1075. const onErrorCallbackList = [];
  1076. function after(callback) {
  1077. afterCallbackList.push(callback);
  1078. }
  1079. function onError(callback) {
  1080. onErrorCallbackList.push(callback);
  1081. }
  1082. triggerSubscriptions(actionSubscriptions, {
  1083. args,
  1084. name: wrappedAction[ACTION_NAME],
  1085. store,
  1086. after,
  1087. onError
  1088. });
  1089. let ret;
  1090. try {
  1091. ret = fn.apply(this && this.$id === $id ? this : store, args);
  1092. } catch (error) {
  1093. triggerSubscriptions(onErrorCallbackList, error);
  1094. throw error;
  1095. }
  1096. if (ret instanceof Promise) {
  1097. return ret.then((value) => {
  1098. triggerSubscriptions(afterCallbackList, value);
  1099. return value;
  1100. }).catch((error) => {
  1101. triggerSubscriptions(onErrorCallbackList, error);
  1102. return Promise.reject(error);
  1103. });
  1104. }
  1105. triggerSubscriptions(afterCallbackList, ret);
  1106. return ret;
  1107. };
  1108. wrappedAction[ACTION_MARKER] = true;
  1109. wrappedAction[ACTION_NAME] = name;
  1110. return wrappedAction;
  1111. };
  1112. const _hmrPayload = markRaw({
  1113. actions: {},
  1114. getters: {},
  1115. state: [],
  1116. hotState
  1117. });
  1118. const partialStore = {
  1119. _p: pinia,
  1120. // _s: scope,
  1121. $id,
  1122. $onAction: addSubscription.bind(null, actionSubscriptions),
  1123. $patch,
  1124. $reset,
  1125. $subscribe(callback, options2 = {}) {
  1126. const removeSubscription = addSubscription(subscriptions, callback, options2.detached, () => stopWatcher());
  1127. const stopWatcher = scope.run(() => watch(() => pinia.state.value[$id], (state) => {
  1128. if (options2.flush === "sync" ? isSyncListening : isListening) {
  1129. callback({
  1130. storeId: $id,
  1131. type: MutationType.direct,
  1132. events: debuggerEvents
  1133. }, state);
  1134. }
  1135. }, assign({}, $subscribeOptions, options2)));
  1136. return removeSubscription;
  1137. },
  1138. $dispose
  1139. };
  1140. if (isVue2) {
  1141. partialStore._r = false;
  1142. }
  1143. const store = reactive(true ? assign(
  1144. {
  1145. _hmrPayload,
  1146. _customProperties: markRaw(/* @__PURE__ */ new Set())
  1147. // devtools custom properties
  1148. },
  1149. partialStore
  1150. // must be added later
  1151. // setupStore
  1152. ) : partialStore);
  1153. pinia._s.set($id, store);
  1154. const runWithContext = pinia._a && pinia._a.runWithContext || fallbackRunWithContext;
  1155. const setupStore = runWithContext(() => pinia._e.run(() => (scope = effectScope()).run(() => setup({ action }))));
  1156. for (const key in setupStore) {
  1157. const prop = setupStore[key];
  1158. if (isRef(prop) && !isComputed(prop) || isReactive(prop)) {
  1159. if (hot) {
  1160. set(hotState.value, key, toRef(setupStore, key));
  1161. } else if (!isOptionsStore) {
  1162. if (initialState && shouldHydrate(prop)) {
  1163. if (isRef(prop)) {
  1164. prop.value = initialState[key];
  1165. } else {
  1166. mergeReactiveObjects(prop, initialState[key]);
  1167. }
  1168. }
  1169. if (isVue2) {
  1170. set(pinia.state.value[$id], key, prop);
  1171. } else {
  1172. pinia.state.value[$id][key] = prop;
  1173. }
  1174. }
  1175. if (true) {
  1176. _hmrPayload.state.push(key);
  1177. }
  1178. } else if (typeof prop === "function") {
  1179. const actionValue = hot ? prop : action(prop, key);
  1180. if (isVue2) {
  1181. set(setupStore, key, actionValue);
  1182. } else {
  1183. setupStore[key] = actionValue;
  1184. }
  1185. if (true) {
  1186. _hmrPayload.actions[key] = prop;
  1187. }
  1188. optionsForPlugin.actions[key] = prop;
  1189. } else if (true) {
  1190. if (isComputed(prop)) {
  1191. _hmrPayload.getters[key] = isOptionsStore ? (
  1192. // @ts-expect-error
  1193. options.getters[key]
  1194. ) : prop;
  1195. if (IS_CLIENT) {
  1196. const getters = setupStore._getters || // @ts-expect-error: same
  1197. (setupStore._getters = markRaw([]));
  1198. getters.push(key);
  1199. }
  1200. }
  1201. }
  1202. }
  1203. if (isVue2) {
  1204. Object.keys(setupStore).forEach((key) => {
  1205. set(store, key, setupStore[key]);
  1206. });
  1207. } else {
  1208. assign(store, setupStore);
  1209. assign(toRaw(store), setupStore);
  1210. }
  1211. Object.defineProperty(store, "$state", {
  1212. get: () => hot ? hotState.value : pinia.state.value[$id],
  1213. set: (state) => {
  1214. if (hot) {
  1215. throw new Error("cannot set hotState");
  1216. }
  1217. $patch(($state) => {
  1218. assign($state, state);
  1219. });
  1220. }
  1221. });
  1222. if (true) {
  1223. store._hotUpdate = markRaw((newStore) => {
  1224. store._hotUpdating = true;
  1225. newStore._hmrPayload.state.forEach((stateKey) => {
  1226. if (stateKey in store.$state) {
  1227. const newStateTarget = newStore.$state[stateKey];
  1228. const oldStateSource = store.$state[stateKey];
  1229. if (typeof newStateTarget === "object" && isPlainObject(newStateTarget) && isPlainObject(oldStateSource)) {
  1230. patchObject(newStateTarget, oldStateSource);
  1231. } else {
  1232. newStore.$state[stateKey] = oldStateSource;
  1233. }
  1234. }
  1235. set(store, stateKey, toRef(newStore.$state, stateKey));
  1236. });
  1237. Object.keys(store.$state).forEach((stateKey) => {
  1238. if (!(stateKey in newStore.$state)) {
  1239. del(store, stateKey);
  1240. }
  1241. });
  1242. isListening = false;
  1243. isSyncListening = false;
  1244. pinia.state.value[$id] = toRef(newStore._hmrPayload, "hotState");
  1245. isSyncListening = true;
  1246. nextTick().then(() => {
  1247. isListening = true;
  1248. });
  1249. for (const actionName in newStore._hmrPayload.actions) {
  1250. const actionFn = newStore[actionName];
  1251. set(store, actionName, action(actionFn, actionName));
  1252. }
  1253. for (const getterName in newStore._hmrPayload.getters) {
  1254. const getter = newStore._hmrPayload.getters[getterName];
  1255. const getterValue = isOptionsStore ? (
  1256. // special handling of options api
  1257. computed(() => {
  1258. setActivePinia(pinia);
  1259. return getter.call(store, store);
  1260. })
  1261. ) : getter;
  1262. set(store, getterName, getterValue);
  1263. }
  1264. Object.keys(store._hmrPayload.getters).forEach((key) => {
  1265. if (!(key in newStore._hmrPayload.getters)) {
  1266. del(store, key);
  1267. }
  1268. });
  1269. Object.keys(store._hmrPayload.actions).forEach((key) => {
  1270. if (!(key in newStore._hmrPayload.actions)) {
  1271. del(store, key);
  1272. }
  1273. });
  1274. store._hmrPayload = newStore._hmrPayload;
  1275. store._getters = newStore._getters;
  1276. store._hotUpdating = false;
  1277. });
  1278. }
  1279. if (IS_CLIENT) {
  1280. const nonEnumerable = {
  1281. writable: true,
  1282. configurable: true,
  1283. // avoid warning on devtools trying to display this property
  1284. enumerable: false
  1285. };
  1286. ["_p", "_hmrPayload", "_getters", "_customProperties"].forEach((p) => {
  1287. Object.defineProperty(store, p, assign({ value: store[p] }, nonEnumerable));
  1288. });
  1289. }
  1290. if (isVue2) {
  1291. store._r = true;
  1292. }
  1293. pinia._p.forEach((extender) => {
  1294. if (IS_CLIENT) {
  1295. const extensions = scope.run(() => extender({
  1296. store,
  1297. app: pinia._a,
  1298. pinia,
  1299. options: optionsForPlugin
  1300. }));
  1301. Object.keys(extensions || {}).forEach((key) => store._customProperties.add(key));
  1302. assign(store, extensions);
  1303. } else {
  1304. assign(store, scope.run(() => extender({
  1305. store,
  1306. app: pinia._a,
  1307. pinia,
  1308. options: optionsForPlugin
  1309. })));
  1310. }
  1311. });
  1312. if (store.$state && typeof store.$state === "object" && typeof store.$state.constructor === "function" && !store.$state.constructor.toString().includes("[native code]")) {
  1313. console.warn(`[🍍]: The "state" must be a plain object. It cannot be
  1314. state: () => new MyClass()
  1315. Found in store "${store.$id}".`);
  1316. }
  1317. if (initialState && isOptionsStore && options.hydrate) {
  1318. options.hydrate(store.$state, initialState);
  1319. }
  1320. isListening = true;
  1321. isSyncListening = true;
  1322. return store;
  1323. }
  1324. function defineStore(idOrOptions, setup, setupOptions) {
  1325. let id;
  1326. let options;
  1327. const isSetupStore = typeof setup === "function";
  1328. if (typeof idOrOptions === "string") {
  1329. id = idOrOptions;
  1330. options = isSetupStore ? setupOptions : setup;
  1331. } else {
  1332. options = idOrOptions;
  1333. id = idOrOptions.id;
  1334. if (typeof id !== "string") {
  1335. throw new Error(`[🍍]: "defineStore()" must be passed a store id as its first argument.`);
  1336. }
  1337. }
  1338. function useStore(pinia, hot) {
  1339. const hasContext = hasInjectionContext();
  1340. pinia = // in test mode, ignore the argument provided as we can always retrieve a
  1341. // pinia instance with getActivePinia()
  1342. (false ? null : pinia) || (hasContext ? inject(piniaSymbol, null) : null);
  1343. if (pinia)
  1344. setActivePinia(pinia);
  1345. if (!activePinia) {
  1346. throw new Error(`[🍍]: "getActivePinia()" was called but there was no active Pinia. Are you trying to use a store before calling "app.use(pinia)"?
  1347. See https://pinia.vuejs.org/core-concepts/outside-component-usage.html for help.
  1348. This will fail in production.`);
  1349. }
  1350. pinia = activePinia;
  1351. if (!pinia._s.has(id)) {
  1352. if (isSetupStore) {
  1353. createSetupStore(id, setup, options, pinia);
  1354. } else {
  1355. createOptionsStore(id, options, pinia);
  1356. }
  1357. if (true) {
  1358. useStore._pinia = pinia;
  1359. }
  1360. }
  1361. const store = pinia._s.get(id);
  1362. if (hot) {
  1363. const hotId = "__hot:" + id;
  1364. const newStore = isSetupStore ? createSetupStore(hotId, setup, options, pinia, true) : createOptionsStore(hotId, assign({}, options), pinia, true);
  1365. hot._hotUpdate(newStore);
  1366. delete pinia.state.value[hotId];
  1367. pinia._s.delete(hotId);
  1368. }
  1369. if (IS_CLIENT) {
  1370. const currentInstance = getCurrentInstance();
  1371. if (currentInstance && currentInstance.proxy && // avoid adding stores that are just built for hot module replacement
  1372. !hot) {
  1373. const vm = currentInstance.proxy;
  1374. const cache = "_pStores" in vm ? vm._pStores : vm._pStores = {};
  1375. cache[id] = store;
  1376. }
  1377. }
  1378. return store;
  1379. }
  1380. useStore.$id = id;
  1381. return useStore;
  1382. }
  1383. var mapStoreSuffix = "Store";
  1384. function setMapStoreSuffix(suffix) {
  1385. mapStoreSuffix = suffix;
  1386. }
  1387. function mapStores(...stores) {
  1388. if (Array.isArray(stores[0])) {
  1389. console.warn(`[🍍]: Directly pass all stores to "mapStores()" without putting them in an array:
  1390. Replace
  1391. mapStores([useAuthStore, useCartStore])
  1392. with
  1393. mapStores(useAuthStore, useCartStore)
  1394. This will fail in production if not fixed.`);
  1395. stores = stores[0];
  1396. }
  1397. return stores.reduce((reduced, useStore) => {
  1398. reduced[useStore.$id + mapStoreSuffix] = function() {
  1399. return useStore(this.$pinia);
  1400. };
  1401. return reduced;
  1402. }, {});
  1403. }
  1404. function mapState(useStore, keysOrMapper) {
  1405. return Array.isArray(keysOrMapper) ? keysOrMapper.reduce((reduced, key) => {
  1406. reduced[key] = function() {
  1407. return useStore(this.$pinia)[key];
  1408. };
  1409. return reduced;
  1410. }, {}) : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1411. reduced[key] = function() {
  1412. const store = useStore(this.$pinia);
  1413. const storeKey = keysOrMapper[key];
  1414. return typeof storeKey === "function" ? storeKey.call(this, store) : (
  1415. // @ts-expect-error: FIXME: should work?
  1416. store[storeKey]
  1417. );
  1418. };
  1419. return reduced;
  1420. }, {});
  1421. }
  1422. var mapGetters = mapState;
  1423. function mapActions(useStore, keysOrMapper) {
  1424. return Array.isArray(keysOrMapper) ? keysOrMapper.reduce((reduced, key) => {
  1425. reduced[key] = function(...args) {
  1426. return useStore(this.$pinia)[key](...args);
  1427. };
  1428. return reduced;
  1429. }, {}) : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1430. reduced[key] = function(...args) {
  1431. return useStore(this.$pinia)[keysOrMapper[key]](...args);
  1432. };
  1433. return reduced;
  1434. }, {});
  1435. }
  1436. function mapWritableState(useStore, keysOrMapper) {
  1437. return Array.isArray(keysOrMapper) ? keysOrMapper.reduce((reduced, key) => {
  1438. reduced[key] = {
  1439. get() {
  1440. return useStore(this.$pinia)[key];
  1441. },
  1442. set(value) {
  1443. return useStore(this.$pinia)[key] = value;
  1444. }
  1445. };
  1446. return reduced;
  1447. }, {}) : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1448. reduced[key] = {
  1449. get() {
  1450. return useStore(this.$pinia)[keysOrMapper[key]];
  1451. },
  1452. set(value) {
  1453. return useStore(this.$pinia)[keysOrMapper[key]] = value;
  1454. }
  1455. };
  1456. return reduced;
  1457. }, {});
  1458. }
  1459. function storeToRefs(store) {
  1460. if (isVue2) {
  1461. return toRefs(store);
  1462. } else {
  1463. const rawStore = toRaw(store);
  1464. const refs = {};
  1465. for (const key in rawStore) {
  1466. const value = rawStore[key];
  1467. if (value.effect) {
  1468. refs[key] = // ...
  1469. computed({
  1470. get: () => store[key],
  1471. set(value2) {
  1472. store[key] = value2;
  1473. }
  1474. });
  1475. } else if (isRef(value) || isReactive(value)) {
  1476. refs[key] = // ---
  1477. toRef(store, key);
  1478. }
  1479. }
  1480. return refs;
  1481. }
  1482. }
  1483. var PiniaVuePlugin = function(_Vue) {
  1484. _Vue.mixin({
  1485. beforeCreate() {
  1486. const options = this.$options;
  1487. if (options.pinia) {
  1488. const pinia = options.pinia;
  1489. if (!this._provided) {
  1490. const provideCache = {};
  1491. Object.defineProperty(this, "_provided", {
  1492. get: () => provideCache,
  1493. set: (v) => Object.assign(provideCache, v)
  1494. });
  1495. }
  1496. this._provided[piniaSymbol] = pinia;
  1497. if (!this.$pinia) {
  1498. this.$pinia = pinia;
  1499. }
  1500. pinia._a = this;
  1501. if (IS_CLIENT) {
  1502. setActivePinia(pinia);
  1503. }
  1504. if (IS_CLIENT) {
  1505. registerPiniaDevtools(pinia._a, pinia);
  1506. }
  1507. } else if (!this.$pinia && options.parent && options.parent.$pinia) {
  1508. this.$pinia = options.parent.$pinia;
  1509. }
  1510. },
  1511. destroyed() {
  1512. delete this._pStores;
  1513. }
  1514. });
  1515. };
  1516. export {
  1517. MutationType,
  1518. PiniaVuePlugin,
  1519. acceptHMRUpdate,
  1520. createPinia,
  1521. defineStore,
  1522. disposePinia,
  1523. getActivePinia,
  1524. mapActions,
  1525. mapGetters,
  1526. mapState,
  1527. mapStores,
  1528. mapWritableState,
  1529. setActivePinia,
  1530. setMapStoreSuffix,
  1531. shouldHydrate,
  1532. skipHydrate,
  1533. storeToRefs
  1534. };
  1535. /*! Bundled license information:
  1536. pinia/dist/pinia.mjs:
  1537. (*!
  1538. * pinia v2.3.0
  1539. * (c) 2024 Eduardo San Martin Morote
  1540. * @license MIT
  1541. *)
  1542. (*! #__NO_SIDE_EFFECTS__ *)
  1543. */
  1544. //# sourceMappingURL=pinia.js.map