pinia.js 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530
  1. import {
  2. setupDevtoolsPlugin
  3. } from "./chunk-TQOCY6B2.js";
  4. import {
  5. computed,
  6. effectScope,
  7. getCurrentInstance,
  8. getCurrentScope,
  9. inject,
  10. isReactive,
  11. isRef,
  12. markRaw,
  13. nextTick,
  14. onScopeDispose,
  15. reactive,
  16. ref,
  17. toRaw,
  18. toRef,
  19. toRefs,
  20. unref,
  21. watch
  22. } from "./chunk-IDMHQ7FM.js";
  23. import "./chunk-4EOJPDL2.js";
  24. // node_modules/pinia/node_modules/vue-demi/lib/index.mjs
  25. var isVue2 = false;
  26. function set(target, key, val) {
  27. if (Array.isArray(target)) {
  28. target.length = Math.max(target.length, key);
  29. target.splice(key, 1, val);
  30. return val;
  31. }
  32. target[key] = val;
  33. return val;
  34. }
  35. function del(target, key) {
  36. if (Array.isArray(target)) {
  37. target.splice(key, 1);
  38. return;
  39. }
  40. delete target[key];
  41. }
  42. // node_modules/pinia/dist/pinia.mjs
  43. var activePinia;
  44. var setActivePinia = (pinia) => activePinia = pinia;
  45. var getActivePinia = () => getCurrentInstance() && inject(piniaSymbol) || activePinia;
  46. var piniaSymbol = true ? Symbol("pinia") : (
  47. /* istanbul ignore next */
  48. Symbol()
  49. );
  50. function isPlainObject(o) {
  51. return o && typeof o === "object" && Object.prototype.toString.call(o) === "[object Object]" && typeof o.toJSON !== "function";
  52. }
  53. var MutationType;
  54. (function(MutationType2) {
  55. MutationType2["direct"] = "direct";
  56. MutationType2["patchObject"] = "patch object";
  57. MutationType2["patchFunction"] = "patch function";
  58. })(MutationType || (MutationType = {}));
  59. var IS_CLIENT = typeof window !== "undefined";
  60. var USE_DEVTOOLS = IS_CLIENT;
  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. pinia.state.value = 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 = await getFileOpener();
  284. const result = await open2();
  285. if (!result)
  286. return;
  287. const { text, file } = result;
  288. pinia.state.value = JSON.parse(text);
  289. toastMessage(`Global state imported from "${file.name}".`);
  290. } catch (error) {
  291. toastMessage(`Failed to export the state as JSON. Check the console for more details.`, "error");
  292. console.error(error);
  293. }
  294. }
  295. function formatDisplay(display) {
  296. return {
  297. _custom: {
  298. display
  299. }
  300. };
  301. }
  302. var PINIA_ROOT_LABEL = "🍍 Pinia (root)";
  303. var PINIA_ROOT_ID = "_root";
  304. function formatStoreForInspectorTree(store) {
  305. return isPinia(store) ? {
  306. id: PINIA_ROOT_ID,
  307. label: PINIA_ROOT_LABEL
  308. } : {
  309. id: store.$id,
  310. label: store.$id
  311. };
  312. }
  313. function formatStoreForInspectorState(store) {
  314. if (isPinia(store)) {
  315. const storeNames = Array.from(store._s.keys());
  316. const storeMap = store._s;
  317. const state2 = {
  318. state: storeNames.map((storeId) => ({
  319. editable: true,
  320. key: storeId,
  321. value: store.state.value[storeId]
  322. })),
  323. getters: storeNames.filter((id) => storeMap.get(id)._getters).map((id) => {
  324. const store2 = storeMap.get(id);
  325. return {
  326. editable: false,
  327. key: id,
  328. value: store2._getters.reduce((getters, key) => {
  329. getters[key] = store2[key];
  330. return getters;
  331. }, {})
  332. };
  333. })
  334. };
  335. return state2;
  336. }
  337. const state = {
  338. state: Object.keys(store.$state).map((key) => ({
  339. editable: true,
  340. key,
  341. value: store.$state[key]
  342. }))
  343. };
  344. if (store._getters && store._getters.length) {
  345. state.getters = store._getters.map((getterName) => ({
  346. editable: false,
  347. key: getterName,
  348. value: store[getterName]
  349. }));
  350. }
  351. if (store._customProperties.size) {
  352. state.customProperties = Array.from(store._customProperties).map((key) => ({
  353. editable: true,
  354. key,
  355. value: store[key]
  356. }));
  357. }
  358. return state;
  359. }
  360. function formatEventData(events) {
  361. if (!events)
  362. return {};
  363. if (Array.isArray(events)) {
  364. return events.reduce((data, event) => {
  365. data.keys.push(event.key);
  366. data.operations.push(event.type);
  367. data.oldValue[event.key] = event.oldValue;
  368. data.newValue[event.key] = event.newValue;
  369. return data;
  370. }, {
  371. oldValue: {},
  372. keys: [],
  373. operations: [],
  374. newValue: {}
  375. });
  376. } else {
  377. return {
  378. operation: formatDisplay(events.type),
  379. key: formatDisplay(events.key),
  380. oldValue: events.oldValue,
  381. newValue: events.newValue
  382. };
  383. }
  384. }
  385. function formatMutationType(type) {
  386. switch (type) {
  387. case MutationType.direct:
  388. return "mutation";
  389. case MutationType.patchFunction:
  390. return "$patch";
  391. case MutationType.patchObject:
  392. return "$patch";
  393. default:
  394. return "unknown";
  395. }
  396. }
  397. var isTimelineActive = true;
  398. var componentStateTypes = [];
  399. var MUTATIONS_LAYER_ID = "pinia:mutations";
  400. var INSPECTOR_ID = "pinia";
  401. var { assign: assign$1 } = Object;
  402. var getStoreType = (id) => "🍍 " + id;
  403. function registerPiniaDevtools(app, pinia) {
  404. setupDevtoolsPlugin({
  405. id: "dev.esm.pinia",
  406. label: "Pinia 🍍",
  407. logo: "https://pinia.vuejs.org/logo.svg",
  408. packageName: "pinia",
  409. homepage: "https://pinia.vuejs.org",
  410. componentStateTypes,
  411. app
  412. }, (api) => {
  413. if (typeof api.now !== "function") {
  414. 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.");
  415. }
  416. api.addTimelineLayer({
  417. id: MUTATIONS_LAYER_ID,
  418. label: `Pinia 🍍`,
  419. color: 15064968
  420. });
  421. api.addInspector({
  422. id: INSPECTOR_ID,
  423. label: "Pinia 🍍",
  424. icon: "storage",
  425. treeFilterPlaceholder: "Search stores",
  426. actions: [
  427. {
  428. icon: "content_copy",
  429. action: () => {
  430. actionGlobalCopyState(pinia);
  431. },
  432. tooltip: "Serialize and copy the state"
  433. },
  434. {
  435. icon: "content_paste",
  436. action: async () => {
  437. await actionGlobalPasteState(pinia);
  438. api.sendInspectorTree(INSPECTOR_ID);
  439. api.sendInspectorState(INSPECTOR_ID);
  440. },
  441. tooltip: "Replace the state with the content of your clipboard"
  442. },
  443. {
  444. icon: "save",
  445. action: () => {
  446. actionGlobalSaveState(pinia);
  447. },
  448. tooltip: "Save the state as a JSON file"
  449. },
  450. {
  451. icon: "folder_open",
  452. action: async () => {
  453. await actionGlobalOpenStateFile(pinia);
  454. api.sendInspectorTree(INSPECTOR_ID);
  455. api.sendInspectorState(INSPECTOR_ID);
  456. },
  457. tooltip: "Import the state from a JSON file"
  458. }
  459. ],
  460. nodeActions: [
  461. {
  462. icon: "restore",
  463. tooltip: "Reset the state (option store only)",
  464. action: (nodeId) => {
  465. const store = pinia._s.get(nodeId);
  466. if (!store) {
  467. toastMessage(`Cannot reset "${nodeId}" store because it wasn't found.`, "warn");
  468. } else if (!store._isOptionsAPI) {
  469. toastMessage(`Cannot reset "${nodeId}" store because it's a setup store.`, "warn");
  470. } else {
  471. store.$reset();
  472. toastMessage(`Store "${nodeId}" reset.`);
  473. }
  474. }
  475. }
  476. ]
  477. });
  478. api.on.inspectComponent((payload, ctx) => {
  479. const proxy = payload.componentInstance && payload.componentInstance.proxy;
  480. if (proxy && proxy._pStores) {
  481. const piniaStores = payload.componentInstance.proxy._pStores;
  482. Object.values(piniaStores).forEach((store) => {
  483. payload.instanceData.state.push({
  484. type: getStoreType(store.$id),
  485. key: "state",
  486. editable: true,
  487. value: store._isOptionsAPI ? {
  488. _custom: {
  489. value: toRaw(store.$state),
  490. actions: [
  491. {
  492. icon: "restore",
  493. tooltip: "Reset the state of this store",
  494. action: () => store.$reset()
  495. }
  496. ]
  497. }
  498. } : (
  499. // NOTE: workaround to unwrap transferred refs
  500. Object.keys(store.$state).reduce((state, key) => {
  501. state[key] = store.$state[key];
  502. return state;
  503. }, {})
  504. )
  505. });
  506. if (store._getters && store._getters.length) {
  507. payload.instanceData.state.push({
  508. type: getStoreType(store.$id),
  509. key: "getters",
  510. editable: false,
  511. value: store._getters.reduce((getters, key) => {
  512. try {
  513. getters[key] = store[key];
  514. } catch (error) {
  515. getters[key] = error;
  516. }
  517. return getters;
  518. }, {})
  519. });
  520. }
  521. });
  522. }
  523. });
  524. api.on.getInspectorTree((payload) => {
  525. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  526. let stores = [pinia];
  527. stores = stores.concat(Array.from(pinia._s.values()));
  528. 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);
  529. }
  530. });
  531. api.on.getInspectorState((payload) => {
  532. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  533. const inspectedStore = payload.nodeId === PINIA_ROOT_ID ? pinia : pinia._s.get(payload.nodeId);
  534. if (!inspectedStore) {
  535. return;
  536. }
  537. if (inspectedStore) {
  538. payload.state = formatStoreForInspectorState(inspectedStore);
  539. }
  540. }
  541. });
  542. api.on.editInspectorState((payload, ctx) => {
  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 toastMessage(`store "${payload.nodeId}" not found`, "error");
  547. }
  548. const { path } = payload;
  549. if (!isPinia(inspectedStore)) {
  550. if (path.length !== 1 || !inspectedStore._customProperties.has(path[0]) || path[0] in inspectedStore.$state) {
  551. path.unshift("$state");
  552. }
  553. } else {
  554. path.unshift("state");
  555. }
  556. isTimelineActive = false;
  557. payload.set(inspectedStore, path, payload.state.value);
  558. isTimelineActive = true;
  559. }
  560. });
  561. api.on.editComponentState((payload) => {
  562. if (payload.type.startsWith("🍍")) {
  563. const storeId = payload.type.replace(/^🍍\s*/, "");
  564. const store = pinia._s.get(storeId);
  565. if (!store) {
  566. return toastMessage(`store "${storeId}" not found`, "error");
  567. }
  568. const { path } = payload;
  569. if (path[0] !== "state") {
  570. return toastMessage(`Invalid path for store "${storeId}":
  571. ${path}
  572. Only state can be modified.`);
  573. }
  574. path[0] = "$state";
  575. isTimelineActive = false;
  576. payload.set(store, path, payload.state.value);
  577. isTimelineActive = true;
  578. }
  579. });
  580. });
  581. }
  582. function addStoreToDevtools(app, store) {
  583. if (!componentStateTypes.includes(getStoreType(store.$id))) {
  584. componentStateTypes.push(getStoreType(store.$id));
  585. }
  586. setupDevtoolsPlugin({
  587. id: "dev.esm.pinia",
  588. label: "Pinia 🍍",
  589. logo: "https://pinia.vuejs.org/logo.svg",
  590. packageName: "pinia",
  591. homepage: "https://pinia.vuejs.org",
  592. componentStateTypes,
  593. app,
  594. settings: {
  595. logStoreChanges: {
  596. label: "Notify about new/deleted stores",
  597. type: "boolean",
  598. defaultValue: true
  599. }
  600. // useEmojis: {
  601. // label: 'Use emojis in messages ⚡️',
  602. // type: 'boolean',
  603. // defaultValue: true,
  604. // },
  605. }
  606. }, (api) => {
  607. const now = typeof api.now === "function" ? api.now.bind(api) : Date.now;
  608. store.$onAction(({ after, onError, name, args }) => {
  609. const groupId = runningActionId++;
  610. api.addTimelineEvent({
  611. layerId: MUTATIONS_LAYER_ID,
  612. event: {
  613. time: now(),
  614. title: "🛫 " + name,
  615. subtitle: "start",
  616. data: {
  617. store: formatDisplay(store.$id),
  618. action: formatDisplay(name),
  619. args
  620. },
  621. groupId
  622. }
  623. });
  624. after((result) => {
  625. activeAction = void 0;
  626. api.addTimelineEvent({
  627. layerId: MUTATIONS_LAYER_ID,
  628. event: {
  629. time: now(),
  630. title: "🛬 " + name,
  631. subtitle: "end",
  632. data: {
  633. store: formatDisplay(store.$id),
  634. action: formatDisplay(name),
  635. args,
  636. result
  637. },
  638. groupId
  639. }
  640. });
  641. });
  642. onError((error) => {
  643. activeAction = void 0;
  644. api.addTimelineEvent({
  645. layerId: MUTATIONS_LAYER_ID,
  646. event: {
  647. time: now(),
  648. logType: "error",
  649. title: "💥 " + name,
  650. subtitle: "end",
  651. data: {
  652. store: formatDisplay(store.$id),
  653. action: formatDisplay(name),
  654. args,
  655. error
  656. },
  657. groupId
  658. }
  659. });
  660. });
  661. }, true);
  662. store._customProperties.forEach((name) => {
  663. watch(() => unref(store[name]), (newValue, oldValue) => {
  664. api.notifyComponentUpdate();
  665. api.sendInspectorState(INSPECTOR_ID);
  666. if (isTimelineActive) {
  667. api.addTimelineEvent({
  668. layerId: MUTATIONS_LAYER_ID,
  669. event: {
  670. time: now(),
  671. title: "Change",
  672. subtitle: name,
  673. data: {
  674. newValue,
  675. oldValue
  676. },
  677. groupId: activeAction
  678. }
  679. });
  680. }
  681. }, { deep: true });
  682. });
  683. store.$subscribe(({ events, type }, state) => {
  684. api.notifyComponentUpdate();
  685. api.sendInspectorState(INSPECTOR_ID);
  686. if (!isTimelineActive)
  687. return;
  688. const eventData = {
  689. time: now(),
  690. title: formatMutationType(type),
  691. data: assign$1({ store: formatDisplay(store.$id) }, formatEventData(events)),
  692. groupId: activeAction
  693. };
  694. activeAction = void 0;
  695. if (type === MutationType.patchFunction) {
  696. eventData.subtitle = "⤵️";
  697. } else if (type === MutationType.patchObject) {
  698. eventData.subtitle = "🧩";
  699. } else if (events && !Array.isArray(events)) {
  700. eventData.subtitle = events.type;
  701. }
  702. if (events) {
  703. eventData.data["rawEvent(s)"] = {
  704. _custom: {
  705. display: "DebuggerEvent",
  706. type: "object",
  707. tooltip: "raw DebuggerEvent[]",
  708. value: events
  709. }
  710. };
  711. }
  712. api.addTimelineEvent({
  713. layerId: MUTATIONS_LAYER_ID,
  714. event: eventData
  715. });
  716. }, { detached: true, flush: "sync" });
  717. const hotUpdate = store._hotUpdate;
  718. store._hotUpdate = markRaw((newStore) => {
  719. hotUpdate(newStore);
  720. api.addTimelineEvent({
  721. layerId: MUTATIONS_LAYER_ID,
  722. event: {
  723. time: now(),
  724. title: "🔥 " + store.$id,
  725. subtitle: "HMR update",
  726. data: {
  727. store: formatDisplay(store.$id),
  728. info: formatDisplay(`HMR update`)
  729. }
  730. }
  731. });
  732. api.notifyComponentUpdate();
  733. api.sendInspectorTree(INSPECTOR_ID);
  734. api.sendInspectorState(INSPECTOR_ID);
  735. });
  736. const { $dispose } = store;
  737. store.$dispose = () => {
  738. $dispose();
  739. api.notifyComponentUpdate();
  740. api.sendInspectorTree(INSPECTOR_ID);
  741. api.sendInspectorState(INSPECTOR_ID);
  742. api.getSettings().logStoreChanges && toastMessage(`Disposed "${store.$id}" store 🗑`);
  743. };
  744. api.notifyComponentUpdate();
  745. api.sendInspectorTree(INSPECTOR_ID);
  746. api.sendInspectorState(INSPECTOR_ID);
  747. api.getSettings().logStoreChanges && toastMessage(`"${store.$id}" store installed 🆕`);
  748. });
  749. }
  750. var runningActionId = 0;
  751. var activeAction;
  752. function patchActionForGrouping(store, actionNames) {
  753. const actions = actionNames.reduce((storeActions, actionName) => {
  754. storeActions[actionName] = toRaw(store)[actionName];
  755. return storeActions;
  756. }, {});
  757. for (const actionName in actions) {
  758. store[actionName] = function() {
  759. const _actionId = runningActionId;
  760. const trackedStore = new Proxy(store, {
  761. get(...args) {
  762. activeAction = _actionId;
  763. return Reflect.get(...args);
  764. },
  765. set(...args) {
  766. activeAction = _actionId;
  767. return Reflect.set(...args);
  768. }
  769. });
  770. return actions[actionName].apply(trackedStore, arguments);
  771. };
  772. }
  773. }
  774. function devtoolsPlugin({ app, store, options }) {
  775. if (store.$id.startsWith("__hot:")) {
  776. return;
  777. }
  778. if (options.state) {
  779. store._isOptionsAPI = true;
  780. }
  781. if (typeof options.state === "function") {
  782. patchActionForGrouping(
  783. // @ts-expect-error: can cast the store...
  784. store,
  785. Object.keys(options.actions)
  786. );
  787. const originalHotUpdate = store._hotUpdate;
  788. toRaw(store)._hotUpdate = function(newStore) {
  789. originalHotUpdate.apply(this, arguments);
  790. patchActionForGrouping(store, Object.keys(newStore._hmrPayload.actions));
  791. };
  792. }
  793. addStoreToDevtools(
  794. app,
  795. // FIXME: is there a way to allow the assignment from Store<Id, S, G, A> to StoreGeneric?
  796. store
  797. );
  798. }
  799. function createPinia() {
  800. const scope = effectScope(true);
  801. const state = scope.run(() => ref({}));
  802. let _p = [];
  803. let toBeInstalled = [];
  804. const pinia = markRaw({
  805. install(app) {
  806. setActivePinia(pinia);
  807. if (!isVue2) {
  808. pinia._a = app;
  809. app.provide(piniaSymbol, pinia);
  810. app.config.globalProperties.$pinia = pinia;
  811. if (USE_DEVTOOLS) {
  812. registerPiniaDevtools(app, pinia);
  813. }
  814. toBeInstalled.forEach((plugin) => _p.push(plugin));
  815. toBeInstalled = [];
  816. }
  817. },
  818. use(plugin) {
  819. if (!this._a && !isVue2) {
  820. toBeInstalled.push(plugin);
  821. } else {
  822. _p.push(plugin);
  823. }
  824. return this;
  825. },
  826. _p,
  827. // it's actually undefined here
  828. // @ts-expect-error
  829. _a: null,
  830. _e: scope,
  831. _s: /* @__PURE__ */ new Map(),
  832. state
  833. });
  834. if (USE_DEVTOOLS && typeof Proxy !== "undefined") {
  835. pinia.use(devtoolsPlugin);
  836. }
  837. return pinia;
  838. }
  839. var isUseStore = (fn) => {
  840. return typeof fn === "function" && typeof fn.$id === "string";
  841. };
  842. function patchObject(newState, oldState) {
  843. for (const key in oldState) {
  844. const subPatch = oldState[key];
  845. if (!(key in newState)) {
  846. continue;
  847. }
  848. const targetValue = newState[key];
  849. if (isPlainObject(targetValue) && isPlainObject(subPatch) && !isRef(subPatch) && !isReactive(subPatch)) {
  850. newState[key] = patchObject(targetValue, subPatch);
  851. } else {
  852. if (isVue2) {
  853. set(newState, key, subPatch);
  854. } else {
  855. newState[key] = subPatch;
  856. }
  857. }
  858. }
  859. return newState;
  860. }
  861. function acceptHMRUpdate(initialUseStore, hot) {
  862. if (false) {
  863. return () => {
  864. };
  865. }
  866. return (newModule) => {
  867. const pinia = hot.data.pinia || initialUseStore._pinia;
  868. if (!pinia) {
  869. return;
  870. }
  871. hot.data.pinia = pinia;
  872. for (const exportName in newModule) {
  873. const useStore = newModule[exportName];
  874. if (isUseStore(useStore) && pinia._s.has(useStore.$id)) {
  875. const id = useStore.$id;
  876. if (id !== initialUseStore.$id) {
  877. console.warn(`The id of the store changed from "${initialUseStore.$id}" to "${id}". Reloading.`);
  878. return hot.invalidate();
  879. }
  880. const existingStore = pinia._s.get(id);
  881. if (!existingStore) {
  882. console.log(`[Pinia]: skipping hmr because store doesn't exist yet`);
  883. return;
  884. }
  885. useStore(pinia, existingStore);
  886. }
  887. }
  888. };
  889. }
  890. var noop = () => {
  891. };
  892. function addSubscription(subscriptions, callback, detached, onCleanup = noop) {
  893. subscriptions.push(callback);
  894. const removeSubscription = () => {
  895. const idx = subscriptions.indexOf(callback);
  896. if (idx > -1) {
  897. subscriptions.splice(idx, 1);
  898. onCleanup();
  899. }
  900. };
  901. if (!detached && getCurrentScope()) {
  902. onScopeDispose(removeSubscription);
  903. }
  904. return removeSubscription;
  905. }
  906. function triggerSubscriptions(subscriptions, ...args) {
  907. subscriptions.slice().forEach((callback) => {
  908. callback(...args);
  909. });
  910. }
  911. function mergeReactiveObjects(target, patchToApply) {
  912. if (target instanceof Map && patchToApply instanceof Map) {
  913. patchToApply.forEach((value, key) => target.set(key, value));
  914. }
  915. if (target instanceof Set && patchToApply instanceof Set) {
  916. patchToApply.forEach(target.add, target);
  917. }
  918. for (const key in patchToApply) {
  919. if (!patchToApply.hasOwnProperty(key))
  920. continue;
  921. const subPatch = patchToApply[key];
  922. const targetValue = target[key];
  923. if (isPlainObject(targetValue) && isPlainObject(subPatch) && target.hasOwnProperty(key) && !isRef(subPatch) && !isReactive(subPatch)) {
  924. target[key] = mergeReactiveObjects(targetValue, subPatch);
  925. } else {
  926. target[key] = subPatch;
  927. }
  928. }
  929. return target;
  930. }
  931. var skipHydrateSymbol = true ? Symbol("pinia:skipHydration") : (
  932. /* istanbul ignore next */
  933. Symbol()
  934. );
  935. var skipHydrateMap = /* @__PURE__ */ new WeakMap();
  936. function skipHydrate(obj) {
  937. return isVue2 ? (
  938. // in @vue/composition-api, the refs are sealed so defineProperty doesn't work...
  939. /* istanbul ignore next */
  940. skipHydrateMap.set(obj, 1) && obj
  941. ) : Object.defineProperty(obj, skipHydrateSymbol, {});
  942. }
  943. function shouldHydrate(obj) {
  944. return isVue2 ? (
  945. /* istanbul ignore next */
  946. !skipHydrateMap.has(obj)
  947. ) : !isPlainObject(obj) || !obj.hasOwnProperty(skipHydrateSymbol);
  948. }
  949. var { assign } = Object;
  950. function isComputed(o) {
  951. return !!(isRef(o) && o.effect);
  952. }
  953. function createOptionsStore(id, options, pinia, hot) {
  954. const { state, actions, getters } = options;
  955. const initialState = pinia.state.value[id];
  956. let store;
  957. function setup() {
  958. if (!initialState && !hot) {
  959. if (isVue2) {
  960. set(pinia.state.value, id, state ? state() : {});
  961. } else {
  962. pinia.state.value[id] = state ? state() : {};
  963. }
  964. }
  965. const localState = hot ? (
  966. // use ref() to unwrap refs inside state TODO: check if this is still necessary
  967. toRefs(ref(state ? state() : {}).value)
  968. ) : toRefs(pinia.state.value[id]);
  969. return assign(localState, actions, Object.keys(getters || {}).reduce((computedGetters, name) => {
  970. if (name in localState) {
  971. console.warn(`[🍍]: A getter cannot have the same name as another state property. Rename one of them. Found with "${name}" in store "${id}".`);
  972. }
  973. computedGetters[name] = markRaw(computed(() => {
  974. setActivePinia(pinia);
  975. const store2 = pinia._s.get(id);
  976. if (isVue2 && !store2._r)
  977. return;
  978. return getters[name].call(store2, store2);
  979. }));
  980. return computedGetters;
  981. }, {}));
  982. }
  983. store = createSetupStore(id, setup, options, pinia, hot, true);
  984. return store;
  985. }
  986. function createSetupStore($id, setup, options = {}, pinia, hot, isOptionsStore) {
  987. let scope;
  988. const optionsForPlugin = assign({ actions: {} }, options);
  989. if (!pinia._e.active) {
  990. throw new Error("Pinia destroyed");
  991. }
  992. const $subscribeOptions = {
  993. deep: true
  994. // flush: 'post',
  995. };
  996. if (!isVue2) {
  997. $subscribeOptions.onTrigger = (event) => {
  998. if (isListening) {
  999. debuggerEvents = event;
  1000. } else if (isListening == false && !store._hotUpdating) {
  1001. if (Array.isArray(debuggerEvents)) {
  1002. debuggerEvents.push(event);
  1003. } else {
  1004. console.error("🍍 debuggerEvents should be an array. This is most likely an internal Pinia bug.");
  1005. }
  1006. }
  1007. };
  1008. }
  1009. let isListening;
  1010. let isSyncListening;
  1011. let subscriptions = markRaw([]);
  1012. let actionSubscriptions = markRaw([]);
  1013. let debuggerEvents;
  1014. const initialState = pinia.state.value[$id];
  1015. if (!isOptionsStore && !initialState && !hot) {
  1016. if (isVue2) {
  1017. set(pinia.state.value, $id, {});
  1018. } else {
  1019. pinia.state.value[$id] = {};
  1020. }
  1021. }
  1022. const hotState = ref({});
  1023. let activeListener;
  1024. function $patch(partialStateOrMutator) {
  1025. let subscriptionMutation;
  1026. isListening = isSyncListening = false;
  1027. if (true) {
  1028. debuggerEvents = [];
  1029. }
  1030. if (typeof partialStateOrMutator === "function") {
  1031. partialStateOrMutator(pinia.state.value[$id]);
  1032. subscriptionMutation = {
  1033. type: MutationType.patchFunction,
  1034. storeId: $id,
  1035. events: debuggerEvents
  1036. };
  1037. } else {
  1038. mergeReactiveObjects(pinia.state.value[$id], partialStateOrMutator);
  1039. subscriptionMutation = {
  1040. type: MutationType.patchObject,
  1041. payload: partialStateOrMutator,
  1042. storeId: $id,
  1043. events: debuggerEvents
  1044. };
  1045. }
  1046. const myListenerId = activeListener = Symbol();
  1047. nextTick().then(() => {
  1048. if (activeListener === myListenerId) {
  1049. isListening = true;
  1050. }
  1051. });
  1052. isSyncListening = true;
  1053. triggerSubscriptions(subscriptions, subscriptionMutation, pinia.state.value[$id]);
  1054. }
  1055. const $reset = isOptionsStore ? function $reset2() {
  1056. const { state } = options;
  1057. const newState = state ? state() : {};
  1058. this.$patch(($state) => {
  1059. assign($state, newState);
  1060. });
  1061. } : (
  1062. /* istanbul ignore next */
  1063. true ? () => {
  1064. throw new Error(`🍍: Store "${$id}" is built using the setup syntax and does not implement $reset().`);
  1065. } : noop
  1066. );
  1067. function $dispose() {
  1068. scope.stop();
  1069. subscriptions = [];
  1070. actionSubscriptions = [];
  1071. pinia._s.delete($id);
  1072. }
  1073. function wrapAction(name, action) {
  1074. return function() {
  1075. setActivePinia(pinia);
  1076. const args = Array.from(arguments);
  1077. const afterCallbackList = [];
  1078. const onErrorCallbackList = [];
  1079. function after(callback) {
  1080. afterCallbackList.push(callback);
  1081. }
  1082. function onError(callback) {
  1083. onErrorCallbackList.push(callback);
  1084. }
  1085. triggerSubscriptions(actionSubscriptions, {
  1086. args,
  1087. name,
  1088. store,
  1089. after,
  1090. onError
  1091. });
  1092. let ret;
  1093. try {
  1094. ret = action.apply(this && this.$id === $id ? this : store, args);
  1095. } catch (error) {
  1096. triggerSubscriptions(onErrorCallbackList, error);
  1097. throw error;
  1098. }
  1099. if (ret instanceof Promise) {
  1100. return ret.then((value) => {
  1101. triggerSubscriptions(afterCallbackList, value);
  1102. return value;
  1103. }).catch((error) => {
  1104. triggerSubscriptions(onErrorCallbackList, error);
  1105. return Promise.reject(error);
  1106. });
  1107. }
  1108. triggerSubscriptions(afterCallbackList, ret);
  1109. return ret;
  1110. };
  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 setupStore = pinia._e.run(() => {
  1155. scope = effectScope();
  1156. return scope.run(() => setup());
  1157. });
  1158. for (const key in setupStore) {
  1159. const prop = setupStore[key];
  1160. if (isRef(prop) && !isComputed(prop) || isReactive(prop)) {
  1161. if (hot) {
  1162. set(hotState.value, key, toRef(setupStore, key));
  1163. } else if (!isOptionsStore) {
  1164. if (initialState && shouldHydrate(prop)) {
  1165. if (isRef(prop)) {
  1166. prop.value = initialState[key];
  1167. } else {
  1168. mergeReactiveObjects(prop, initialState[key]);
  1169. }
  1170. }
  1171. if (isVue2) {
  1172. set(pinia.state.value[$id], key, prop);
  1173. } else {
  1174. pinia.state.value[$id][key] = prop;
  1175. }
  1176. }
  1177. if (true) {
  1178. _hmrPayload.state.push(key);
  1179. }
  1180. } else if (typeof prop === "function") {
  1181. const actionValue = hot ? prop : wrapAction(key, prop);
  1182. if (isVue2) {
  1183. set(setupStore, key, actionValue);
  1184. } else {
  1185. setupStore[key] = actionValue;
  1186. }
  1187. if (true) {
  1188. _hmrPayload.actions[key] = prop;
  1189. }
  1190. optionsForPlugin.actions[key] = prop;
  1191. } else if (true) {
  1192. if (isComputed(prop)) {
  1193. _hmrPayload.getters[key] = isOptionsStore ? (
  1194. // @ts-expect-error
  1195. options.getters[key]
  1196. ) : prop;
  1197. if (IS_CLIENT) {
  1198. const getters = setupStore._getters || // @ts-expect-error: same
  1199. (setupStore._getters = markRaw([]));
  1200. getters.push(key);
  1201. }
  1202. }
  1203. }
  1204. }
  1205. if (isVue2) {
  1206. Object.keys(setupStore).forEach((key) => {
  1207. set(store, key, setupStore[key]);
  1208. });
  1209. } else {
  1210. assign(store, setupStore);
  1211. assign(toRaw(store), setupStore);
  1212. }
  1213. Object.defineProperty(store, "$state", {
  1214. get: () => hot ? hotState.value : pinia.state.value[$id],
  1215. set: (state) => {
  1216. if (hot) {
  1217. throw new Error("cannot set hotState");
  1218. }
  1219. $patch(($state) => {
  1220. assign($state, state);
  1221. });
  1222. }
  1223. });
  1224. if (true) {
  1225. store._hotUpdate = markRaw((newStore) => {
  1226. store._hotUpdating = true;
  1227. newStore._hmrPayload.state.forEach((stateKey) => {
  1228. if (stateKey in store.$state) {
  1229. const newStateTarget = newStore.$state[stateKey];
  1230. const oldStateSource = store.$state[stateKey];
  1231. if (typeof newStateTarget === "object" && isPlainObject(newStateTarget) && isPlainObject(oldStateSource)) {
  1232. patchObject(newStateTarget, oldStateSource);
  1233. } else {
  1234. newStore.$state[stateKey] = oldStateSource;
  1235. }
  1236. }
  1237. set(store, stateKey, toRef(newStore.$state, stateKey));
  1238. });
  1239. Object.keys(store.$state).forEach((stateKey) => {
  1240. if (!(stateKey in newStore.$state)) {
  1241. del(store, stateKey);
  1242. }
  1243. });
  1244. isListening = false;
  1245. isSyncListening = false;
  1246. pinia.state.value[$id] = toRef(newStore._hmrPayload, "hotState");
  1247. isSyncListening = true;
  1248. nextTick().then(() => {
  1249. isListening = true;
  1250. });
  1251. for (const actionName in newStore._hmrPayload.actions) {
  1252. const action = newStore[actionName];
  1253. set(store, actionName, wrapAction(actionName, action));
  1254. }
  1255. for (const getterName in newStore._hmrPayload.getters) {
  1256. const getter = newStore._hmrPayload.getters[getterName];
  1257. const getterValue = isOptionsStore ? (
  1258. // special handling of options api
  1259. computed(() => {
  1260. setActivePinia(pinia);
  1261. return getter.call(store, store);
  1262. })
  1263. ) : getter;
  1264. set(store, getterName, getterValue);
  1265. }
  1266. Object.keys(store._hmrPayload.getters).forEach((key) => {
  1267. if (!(key in newStore._hmrPayload.getters)) {
  1268. del(store, key);
  1269. }
  1270. });
  1271. Object.keys(store._hmrPayload.actions).forEach((key) => {
  1272. if (!(key in newStore._hmrPayload.actions)) {
  1273. del(store, key);
  1274. }
  1275. });
  1276. store._hmrPayload = newStore._hmrPayload;
  1277. store._getters = newStore._getters;
  1278. store._hotUpdating = false;
  1279. });
  1280. }
  1281. if (USE_DEVTOOLS) {
  1282. const nonEnumerable = {
  1283. writable: true,
  1284. configurable: true,
  1285. // avoid warning on devtools trying to display this property
  1286. enumerable: false
  1287. };
  1288. ["_p", "_hmrPayload", "_getters", "_customProperties"].forEach((p) => {
  1289. Object.defineProperty(store, p, assign({ value: store[p] }, nonEnumerable));
  1290. });
  1291. }
  1292. if (isVue2) {
  1293. store._r = true;
  1294. }
  1295. pinia._p.forEach((extender) => {
  1296. if (USE_DEVTOOLS) {
  1297. const extensions = scope.run(() => extender({
  1298. store,
  1299. app: pinia._a,
  1300. pinia,
  1301. options: optionsForPlugin
  1302. }));
  1303. Object.keys(extensions || {}).forEach((key) => store._customProperties.add(key));
  1304. assign(store, extensions);
  1305. } else {
  1306. assign(store, scope.run(() => extender({
  1307. store,
  1308. app: pinia._a,
  1309. pinia,
  1310. options: optionsForPlugin
  1311. })));
  1312. }
  1313. });
  1314. if (store.$state && typeof store.$state === "object" && typeof store.$state.constructor === "function" && !store.$state.constructor.toString().includes("[native code]")) {
  1315. console.warn(`[🍍]: The "state" must be a plain object. It cannot be
  1316. state: () => new MyClass()
  1317. Found in store "${store.$id}".`);
  1318. }
  1319. if (initialState && isOptionsStore && options.hydrate) {
  1320. options.hydrate(store.$state, initialState);
  1321. }
  1322. isListening = true;
  1323. isSyncListening = true;
  1324. return store;
  1325. }
  1326. function defineStore(idOrOptions, setup, setupOptions) {
  1327. let id;
  1328. let options;
  1329. const isSetupStore = typeof setup === "function";
  1330. if (typeof idOrOptions === "string") {
  1331. id = idOrOptions;
  1332. options = isSetupStore ? setupOptions : setup;
  1333. } else {
  1334. options = idOrOptions;
  1335. id = idOrOptions.id;
  1336. }
  1337. function useStore(pinia, hot) {
  1338. const currentInstance = getCurrentInstance();
  1339. pinia = // in test mode, ignore the argument provided as we can always retrieve a
  1340. // pinia instance with getActivePinia()
  1341. (false ? null : pinia) || currentInstance && inject(piniaSymbol, null);
  1342. if (pinia)
  1343. setActivePinia(pinia);
  1344. if (!activePinia) {
  1345. throw new Error(`[🍍]: getActivePinia was called with no active Pinia. Did you forget to install pinia?
  1346. const pinia = createPinia()
  1347. app.use(pinia)
  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 && currentInstance && currentInstance.proxy && // avoid adding stores that are just built for hot module replacement
  1370. !hot) {
  1371. const vm = currentInstance.proxy;
  1372. const cache = "_pStores" in vm ? vm._pStores : vm._pStores = {};
  1373. cache[id] = store;
  1374. }
  1375. return store;
  1376. }
  1377. useStore.$id = id;
  1378. return useStore;
  1379. }
  1380. var mapStoreSuffix = "Store";
  1381. function setMapStoreSuffix(suffix) {
  1382. mapStoreSuffix = suffix;
  1383. }
  1384. function mapStores(...stores) {
  1385. if (Array.isArray(stores[0])) {
  1386. console.warn(`[🍍]: Directly pass all stores to "mapStores()" without putting them in an array:
  1387. Replace
  1388. mapStores([useAuthStore, useCartStore])
  1389. with
  1390. mapStores(useAuthStore, useCartStore)
  1391. This will fail in production if not fixed.`);
  1392. stores = stores[0];
  1393. }
  1394. return stores.reduce((reduced, useStore) => {
  1395. reduced[useStore.$id + mapStoreSuffix] = function() {
  1396. return useStore(this.$pinia);
  1397. };
  1398. return reduced;
  1399. }, {});
  1400. }
  1401. function mapState(useStore, keysOrMapper) {
  1402. return Array.isArray(keysOrMapper) ? keysOrMapper.reduce((reduced, key) => {
  1403. reduced[key] = function() {
  1404. return useStore(this.$pinia)[key];
  1405. };
  1406. return reduced;
  1407. }, {}) : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1408. reduced[key] = function() {
  1409. const store = useStore(this.$pinia);
  1410. const storeKey = keysOrMapper[key];
  1411. return typeof storeKey === "function" ? storeKey.call(this, store) : store[storeKey];
  1412. };
  1413. return reduced;
  1414. }, {});
  1415. }
  1416. var mapGetters = mapState;
  1417. function mapActions(useStore, keysOrMapper) {
  1418. return Array.isArray(keysOrMapper) ? keysOrMapper.reduce((reduced, key) => {
  1419. reduced[key] = function(...args) {
  1420. return useStore(this.$pinia)[key](...args);
  1421. };
  1422. return reduced;
  1423. }, {}) : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1424. reduced[key] = function(...args) {
  1425. return useStore(this.$pinia)[keysOrMapper[key]](...args);
  1426. };
  1427. return reduced;
  1428. }, {});
  1429. }
  1430. function mapWritableState(useStore, keysOrMapper) {
  1431. return Array.isArray(keysOrMapper) ? keysOrMapper.reduce((reduced, key) => {
  1432. reduced[key] = {
  1433. get() {
  1434. return useStore(this.$pinia)[key];
  1435. },
  1436. set(value) {
  1437. return useStore(this.$pinia)[key] = value;
  1438. }
  1439. };
  1440. return reduced;
  1441. }, {}) : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1442. reduced[key] = {
  1443. get() {
  1444. return useStore(this.$pinia)[keysOrMapper[key]];
  1445. },
  1446. set(value) {
  1447. return useStore(this.$pinia)[keysOrMapper[key]] = value;
  1448. }
  1449. };
  1450. return reduced;
  1451. }, {});
  1452. }
  1453. function storeToRefs(store) {
  1454. if (isVue2) {
  1455. return toRefs(store);
  1456. } else {
  1457. store = toRaw(store);
  1458. const refs = {};
  1459. for (const key in store) {
  1460. const value = store[key];
  1461. if (isRef(value) || isReactive(value)) {
  1462. refs[key] = // ---
  1463. toRef(store, key);
  1464. }
  1465. }
  1466. return refs;
  1467. }
  1468. }
  1469. var PiniaVuePlugin = function(_Vue) {
  1470. _Vue.mixin({
  1471. beforeCreate() {
  1472. const options = this.$options;
  1473. if (options.pinia) {
  1474. const pinia = options.pinia;
  1475. if (!this._provided) {
  1476. const provideCache = {};
  1477. Object.defineProperty(this, "_provided", {
  1478. get: () => provideCache,
  1479. set: (v) => Object.assign(provideCache, v)
  1480. });
  1481. }
  1482. this._provided[piniaSymbol] = pinia;
  1483. if (!this.$pinia) {
  1484. this.$pinia = pinia;
  1485. }
  1486. pinia._a = this;
  1487. if (IS_CLIENT) {
  1488. setActivePinia(pinia);
  1489. }
  1490. if (USE_DEVTOOLS) {
  1491. registerPiniaDevtools(pinia._a, pinia);
  1492. }
  1493. } else if (!this.$pinia && options.parent && options.parent.$pinia) {
  1494. this.$pinia = options.parent.$pinia;
  1495. }
  1496. },
  1497. destroyed() {
  1498. delete this._pStores;
  1499. }
  1500. });
  1501. };
  1502. export {
  1503. MutationType,
  1504. PiniaVuePlugin,
  1505. acceptHMRUpdate,
  1506. createPinia,
  1507. defineStore,
  1508. getActivePinia,
  1509. mapActions,
  1510. mapGetters,
  1511. mapState,
  1512. mapStores,
  1513. mapWritableState,
  1514. setActivePinia,
  1515. setMapStoreSuffix,
  1516. skipHydrate,
  1517. storeToRefs
  1518. };
  1519. /*! Bundled license information:
  1520. pinia/dist/pinia.mjs:
  1521. (*!
  1522. * pinia v2.0.33
  1523. * (c) 2023 Eduardo San Martin Morote
  1524. * @license MIT
  1525. *)
  1526. */
  1527. //# sourceMappingURL=pinia.js.map