pinia.js 46 KB

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