pinia.cjs 76 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061
  1. /*!
  2. * pinia v2.3.0
  3. * (c) 2024 Eduardo San Martin Morote
  4. * @license MIT
  5. */
  6. 'use strict';
  7. var vueDemi = require('vue-demi');
  8. var devtoolsApi = require('@vue/devtools-api');
  9. /**
  10. * setActivePinia must be called to handle SSR at the top of functions like
  11. * `fetch`, `setup`, `serverPrefetch` and others
  12. */
  13. let activePinia;
  14. /**
  15. * Sets or unsets the active pinia. Used in SSR and internally when calling
  16. * actions and getters
  17. *
  18. * @param pinia - Pinia instance
  19. */
  20. // @ts-expect-error: cannot constrain the type of the return
  21. const setActivePinia = (pinia) => (activePinia = pinia);
  22. /**
  23. * Get the currently active pinia if there is any.
  24. */
  25. const getActivePinia = () => (vueDemi.hasInjectionContext() && vueDemi.inject(piniaSymbol)) || activePinia;
  26. const piniaSymbol = ((process.env.NODE_ENV !== 'production') ? Symbol('pinia') : /* istanbul ignore next */ Symbol());
  27. function isPlainObject(
  28. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  29. o) {
  30. return (o &&
  31. typeof o === 'object' &&
  32. Object.prototype.toString.call(o) === '[object Object]' &&
  33. typeof o.toJSON !== 'function');
  34. }
  35. // type DeepReadonly<T> = { readonly [P in keyof T]: DeepReadonly<T[P]> }
  36. // TODO: can we change these to numbers?
  37. /**
  38. * Possible types for SubscriptionCallback
  39. */
  40. exports.MutationType = void 0;
  41. (function (MutationType) {
  42. /**
  43. * Direct mutation of the state:
  44. *
  45. * - `store.name = 'new name'`
  46. * - `store.$state.name = 'new name'`
  47. * - `store.list.push('new item')`
  48. */
  49. MutationType["direct"] = "direct";
  50. /**
  51. * Mutated the state with `$patch` and an object
  52. *
  53. * - `store.$patch({ name: 'newName' })`
  54. */
  55. MutationType["patchObject"] = "patch object";
  56. /**
  57. * Mutated the state with `$patch` and a function
  58. *
  59. * - `store.$patch(state => state.name = 'newName')`
  60. */
  61. MutationType["patchFunction"] = "patch function";
  62. // maybe reset? for $state = {} and $reset
  63. })(exports.MutationType || (exports.MutationType = {}));
  64. const IS_CLIENT = typeof window !== 'undefined';
  65. /*
  66. * FileSaver.js A saveAs() FileSaver implementation.
  67. *
  68. * Originally by Eli Grey, adapted as an ESM module by Eduardo San Martin
  69. * Morote.
  70. *
  71. * License : MIT
  72. */
  73. // The one and only way of getting global scope in all environments
  74. // https://stackoverflow.com/q/3277182/1008999
  75. const _global = /*#__PURE__*/ (() => typeof window === 'object' && window.window === window
  76. ? window
  77. : typeof self === 'object' && self.self === self
  78. ? self
  79. : typeof global === 'object' && global.global === global
  80. ? global
  81. : typeof globalThis === 'object'
  82. ? globalThis
  83. : { HTMLElement: null })();
  84. function bom(blob, { autoBom = false } = {}) {
  85. // prepend BOM for UTF-8 XML and text/* types (including HTML)
  86. // note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
  87. if (autoBom &&
  88. /^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
  89. return new Blob([String.fromCharCode(0xfeff), blob], { type: blob.type });
  90. }
  91. return blob;
  92. }
  93. function download(url, name, opts) {
  94. const xhr = new XMLHttpRequest();
  95. xhr.open('GET', url);
  96. xhr.responseType = 'blob';
  97. xhr.onload = function () {
  98. saveAs(xhr.response, name, opts);
  99. };
  100. xhr.onerror = function () {
  101. console.error('could not download file');
  102. };
  103. xhr.send();
  104. }
  105. function corsEnabled(url) {
  106. const xhr = new XMLHttpRequest();
  107. // use sync to avoid popup blocker
  108. xhr.open('HEAD', url, false);
  109. try {
  110. xhr.send();
  111. }
  112. catch (e) { }
  113. return xhr.status >= 200 && xhr.status <= 299;
  114. }
  115. // `a.click()` doesn't work for all browsers (#465)
  116. function click(node) {
  117. try {
  118. node.dispatchEvent(new MouseEvent('click'));
  119. }
  120. catch (e) {
  121. const evt = document.createEvent('MouseEvents');
  122. evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
  123. node.dispatchEvent(evt);
  124. }
  125. }
  126. const _navigator = typeof navigator === 'object' ? navigator : { userAgent: '' };
  127. // Detect WebView inside a native macOS app by ruling out all browsers
  128. // We just need to check for 'Safari' because all other browsers (besides Firefox) include that too
  129. // https://www.whatismybrowser.com/guides/the-latest-user-agent/macos
  130. const isMacOSWebView = /*#__PURE__*/ (() => /Macintosh/.test(_navigator.userAgent) &&
  131. /AppleWebKit/.test(_navigator.userAgent) &&
  132. !/Safari/.test(_navigator.userAgent))();
  133. const saveAs = !IS_CLIENT
  134. ? () => { } // noop
  135. : // Use download attribute first if possible (#193 Lumia mobile) unless this is a macOS WebView or mini program
  136. typeof HTMLAnchorElement !== 'undefined' &&
  137. 'download' in HTMLAnchorElement.prototype &&
  138. !isMacOSWebView
  139. ? downloadSaveAs
  140. : // Use msSaveOrOpenBlob as a second approach
  141. 'msSaveOrOpenBlob' in _navigator
  142. ? msSaveAs
  143. : // Fallback to using FileReader and a popup
  144. fileSaverSaveAs;
  145. function downloadSaveAs(blob, name = 'download', opts) {
  146. const a = document.createElement('a');
  147. a.download = name;
  148. a.rel = 'noopener'; // tabnabbing
  149. // TODO: detect chrome extensions & packaged apps
  150. // a.target = '_blank'
  151. if (typeof blob === 'string') {
  152. // Support regular links
  153. a.href = blob;
  154. if (a.origin !== location.origin) {
  155. if (corsEnabled(a.href)) {
  156. download(blob, name, opts);
  157. }
  158. else {
  159. a.target = '_blank';
  160. click(a);
  161. }
  162. }
  163. else {
  164. click(a);
  165. }
  166. }
  167. else {
  168. // Support blobs
  169. a.href = URL.createObjectURL(blob);
  170. setTimeout(function () {
  171. URL.revokeObjectURL(a.href);
  172. }, 4e4); // 40s
  173. setTimeout(function () {
  174. click(a);
  175. }, 0);
  176. }
  177. }
  178. function msSaveAs(blob, name = 'download', opts) {
  179. if (typeof blob === 'string') {
  180. if (corsEnabled(blob)) {
  181. download(blob, name, opts);
  182. }
  183. else {
  184. const a = document.createElement('a');
  185. a.href = blob;
  186. a.target = '_blank';
  187. setTimeout(function () {
  188. click(a);
  189. });
  190. }
  191. }
  192. else {
  193. // @ts-ignore: works on windows
  194. navigator.msSaveOrOpenBlob(bom(blob, opts), name);
  195. }
  196. }
  197. function fileSaverSaveAs(blob, name, opts, popup) {
  198. // Open a popup immediately do go around popup blocker
  199. // Mostly only available on user interaction and the fileReader is async so...
  200. popup = popup || open('', '_blank');
  201. if (popup) {
  202. popup.document.title = popup.document.body.innerText = 'downloading...';
  203. }
  204. if (typeof blob === 'string')
  205. return download(blob, name, opts);
  206. const force = blob.type === 'application/octet-stream';
  207. const isSafari = /constructor/i.test(String(_global.HTMLElement)) || 'safari' in _global;
  208. const isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent);
  209. if ((isChromeIOS || (force && isSafari) || isMacOSWebView) &&
  210. typeof FileReader !== 'undefined') {
  211. // Safari doesn't allow downloading of blob URLs
  212. const reader = new FileReader();
  213. reader.onloadend = function () {
  214. let url = reader.result;
  215. if (typeof url !== 'string') {
  216. popup = null;
  217. throw new Error('Wrong reader.result type');
  218. }
  219. url = isChromeIOS
  220. ? url
  221. : url.replace(/^data:[^;]*;/, 'data:attachment/file;');
  222. if (popup) {
  223. popup.location.href = url;
  224. }
  225. else {
  226. location.assign(url);
  227. }
  228. popup = null; // reverse-tabnabbing #460
  229. };
  230. reader.readAsDataURL(blob);
  231. }
  232. else {
  233. const url = URL.createObjectURL(blob);
  234. if (popup)
  235. popup.location.assign(url);
  236. else
  237. location.href = url;
  238. popup = null; // reverse-tabnabbing #460
  239. setTimeout(function () {
  240. URL.revokeObjectURL(url);
  241. }, 4e4); // 40s
  242. }
  243. }
  244. /**
  245. * Shows a toast or console.log
  246. *
  247. * @param message - message to log
  248. * @param type - different color of the tooltip
  249. */
  250. function toastMessage(message, type) {
  251. const piniaMessage = '🍍 ' + message;
  252. if (typeof __VUE_DEVTOOLS_TOAST__ === 'function') {
  253. // No longer available :(
  254. __VUE_DEVTOOLS_TOAST__(piniaMessage, type);
  255. }
  256. else if (type === 'error') {
  257. console.error(piniaMessage);
  258. }
  259. else if (type === 'warn') {
  260. console.warn(piniaMessage);
  261. }
  262. else {
  263. console.log(piniaMessage);
  264. }
  265. }
  266. function isPinia(o) {
  267. return '_a' in o && 'install' in o;
  268. }
  269. /**
  270. * This file contain devtools actions, they are not Pinia actions.
  271. */
  272. // ---
  273. function checkClipboardAccess() {
  274. if (!('clipboard' in navigator)) {
  275. toastMessage(`Your browser doesn't support the Clipboard API`, 'error');
  276. return true;
  277. }
  278. }
  279. function checkNotFocusedError(error) {
  280. if (error instanceof Error &&
  281. error.message.toLowerCase().includes('document is not focused')) {
  282. toastMessage('You need to activate the "Emulate a focused page" setting in the "Rendering" panel of devtools.', 'warn');
  283. return true;
  284. }
  285. return false;
  286. }
  287. async function actionGlobalCopyState(pinia) {
  288. if (checkClipboardAccess())
  289. return;
  290. try {
  291. await navigator.clipboard.writeText(JSON.stringify(pinia.state.value));
  292. toastMessage('Global state copied to clipboard.');
  293. }
  294. catch (error) {
  295. if (checkNotFocusedError(error))
  296. return;
  297. toastMessage(`Failed to serialize the state. Check the console for more details.`, 'error');
  298. console.error(error);
  299. }
  300. }
  301. async function actionGlobalPasteState(pinia) {
  302. if (checkClipboardAccess())
  303. return;
  304. try {
  305. loadStoresState(pinia, JSON.parse(await navigator.clipboard.readText()));
  306. toastMessage('Global state pasted from clipboard.');
  307. }
  308. catch (error) {
  309. if (checkNotFocusedError(error))
  310. return;
  311. toastMessage(`Failed to deserialize the state from clipboard. Check the console for more details.`, 'error');
  312. console.error(error);
  313. }
  314. }
  315. async function actionGlobalSaveState(pinia) {
  316. try {
  317. saveAs(new Blob([JSON.stringify(pinia.state.value)], {
  318. type: 'text/plain;charset=utf-8',
  319. }), 'pinia-state.json');
  320. }
  321. catch (error) {
  322. toastMessage(`Failed to export the state as JSON. Check the console for more details.`, 'error');
  323. console.error(error);
  324. }
  325. }
  326. let fileInput;
  327. function getFileOpener() {
  328. if (!fileInput) {
  329. fileInput = document.createElement('input');
  330. fileInput.type = 'file';
  331. fileInput.accept = '.json';
  332. }
  333. function openFile() {
  334. return new Promise((resolve, reject) => {
  335. fileInput.onchange = async () => {
  336. const files = fileInput.files;
  337. if (!files)
  338. return resolve(null);
  339. const file = files.item(0);
  340. if (!file)
  341. return resolve(null);
  342. return resolve({ text: await file.text(), file });
  343. };
  344. // @ts-ignore: TODO: changed from 4.3 to 4.4
  345. fileInput.oncancel = () => resolve(null);
  346. fileInput.onerror = reject;
  347. fileInput.click();
  348. });
  349. }
  350. return openFile;
  351. }
  352. async function actionGlobalOpenStateFile(pinia) {
  353. try {
  354. const open = getFileOpener();
  355. const result = await open();
  356. if (!result)
  357. return;
  358. const { text, file } = result;
  359. loadStoresState(pinia, JSON.parse(text));
  360. toastMessage(`Global state imported from "${file.name}".`);
  361. }
  362. catch (error) {
  363. toastMessage(`Failed to import the state from JSON. Check the console for more details.`, 'error');
  364. console.error(error);
  365. }
  366. }
  367. function loadStoresState(pinia, state) {
  368. for (const key in state) {
  369. const storeState = pinia.state.value[key];
  370. // store is already instantiated, patch it
  371. if (storeState) {
  372. Object.assign(storeState, state[key]);
  373. }
  374. else {
  375. // store is not instantiated, set the initial state
  376. pinia.state.value[key] = state[key];
  377. }
  378. }
  379. }
  380. function formatDisplay(display) {
  381. return {
  382. _custom: {
  383. display,
  384. },
  385. };
  386. }
  387. const PINIA_ROOT_LABEL = '🍍 Pinia (root)';
  388. const PINIA_ROOT_ID = '_root';
  389. function formatStoreForInspectorTree(store) {
  390. return isPinia(store)
  391. ? {
  392. id: PINIA_ROOT_ID,
  393. label: PINIA_ROOT_LABEL,
  394. }
  395. : {
  396. id: store.$id,
  397. label: store.$id,
  398. };
  399. }
  400. function formatStoreForInspectorState(store) {
  401. if (isPinia(store)) {
  402. const storeNames = Array.from(store._s.keys());
  403. const storeMap = store._s;
  404. const state = {
  405. state: storeNames.map((storeId) => ({
  406. editable: true,
  407. key: storeId,
  408. value: store.state.value[storeId],
  409. })),
  410. getters: storeNames
  411. .filter((id) => storeMap.get(id)._getters)
  412. .map((id) => {
  413. const store = storeMap.get(id);
  414. return {
  415. editable: false,
  416. key: id,
  417. value: store._getters.reduce((getters, key) => {
  418. getters[key] = store[key];
  419. return getters;
  420. }, {}),
  421. };
  422. }),
  423. };
  424. return state;
  425. }
  426. const state = {
  427. state: Object.keys(store.$state).map((key) => ({
  428. editable: true,
  429. key,
  430. value: store.$state[key],
  431. })),
  432. };
  433. // avoid adding empty getters
  434. if (store._getters && store._getters.length) {
  435. state.getters = store._getters.map((getterName) => ({
  436. editable: false,
  437. key: getterName,
  438. value: store[getterName],
  439. }));
  440. }
  441. if (store._customProperties.size) {
  442. state.customProperties = Array.from(store._customProperties).map((key) => ({
  443. editable: true,
  444. key,
  445. value: store[key],
  446. }));
  447. }
  448. return state;
  449. }
  450. function formatEventData(events) {
  451. if (!events)
  452. return {};
  453. if (Array.isArray(events)) {
  454. // TODO: handle add and delete for arrays and objects
  455. return events.reduce((data, event) => {
  456. data.keys.push(event.key);
  457. data.operations.push(event.type);
  458. data.oldValue[event.key] = event.oldValue;
  459. data.newValue[event.key] = event.newValue;
  460. return data;
  461. }, {
  462. oldValue: {},
  463. keys: [],
  464. operations: [],
  465. newValue: {},
  466. });
  467. }
  468. else {
  469. return {
  470. operation: formatDisplay(events.type),
  471. key: formatDisplay(events.key),
  472. oldValue: events.oldValue,
  473. newValue: events.newValue,
  474. };
  475. }
  476. }
  477. function formatMutationType(type) {
  478. switch (type) {
  479. case exports.MutationType.direct:
  480. return 'mutation';
  481. case exports.MutationType.patchFunction:
  482. return '$patch';
  483. case exports.MutationType.patchObject:
  484. return '$patch';
  485. default:
  486. return 'unknown';
  487. }
  488. }
  489. // timeline can be paused when directly changing the state
  490. let isTimelineActive = true;
  491. const componentStateTypes = [];
  492. const MUTATIONS_LAYER_ID = 'pinia:mutations';
  493. const INSPECTOR_ID = 'pinia';
  494. const { assign: assign$1 } = Object;
  495. /**
  496. * Gets the displayed name of a store in devtools
  497. *
  498. * @param id - id of the store
  499. * @returns a formatted string
  500. */
  501. const getStoreType = (id) => '🍍 ' + id;
  502. /**
  503. * Add the pinia plugin without any store. Allows displaying a Pinia plugin tab
  504. * as soon as it is added to the application.
  505. *
  506. * @param app - Vue application
  507. * @param pinia - pinia instance
  508. */
  509. function registerPiniaDevtools(app, pinia) {
  510. devtoolsApi.setupDevtoolsPlugin({
  511. id: 'dev.esm.pinia',
  512. label: 'Pinia 🍍',
  513. logo: 'https://pinia.vuejs.org/logo.svg',
  514. packageName: 'pinia',
  515. homepage: 'https://pinia.vuejs.org',
  516. componentStateTypes,
  517. app,
  518. }, (api) => {
  519. if (typeof api.now !== 'function') {
  520. 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.');
  521. }
  522. api.addTimelineLayer({
  523. id: MUTATIONS_LAYER_ID,
  524. label: `Pinia 🍍`,
  525. color: 0xe5df88,
  526. });
  527. api.addInspector({
  528. id: INSPECTOR_ID,
  529. label: 'Pinia 🍍',
  530. icon: 'storage',
  531. treeFilterPlaceholder: 'Search stores',
  532. actions: [
  533. {
  534. icon: 'content_copy',
  535. action: () => {
  536. actionGlobalCopyState(pinia);
  537. },
  538. tooltip: 'Serialize and copy the state',
  539. },
  540. {
  541. icon: 'content_paste',
  542. action: async () => {
  543. await actionGlobalPasteState(pinia);
  544. api.sendInspectorTree(INSPECTOR_ID);
  545. api.sendInspectorState(INSPECTOR_ID);
  546. },
  547. tooltip: 'Replace the state with the content of your clipboard',
  548. },
  549. {
  550. icon: 'save',
  551. action: () => {
  552. actionGlobalSaveState(pinia);
  553. },
  554. tooltip: 'Save the state as a JSON file',
  555. },
  556. {
  557. icon: 'folder_open',
  558. action: async () => {
  559. await actionGlobalOpenStateFile(pinia);
  560. api.sendInspectorTree(INSPECTOR_ID);
  561. api.sendInspectorState(INSPECTOR_ID);
  562. },
  563. tooltip: 'Import the state from a JSON file',
  564. },
  565. ],
  566. nodeActions: [
  567. {
  568. icon: 'restore',
  569. tooltip: 'Reset the state (with "$reset")',
  570. action: (nodeId) => {
  571. const store = pinia._s.get(nodeId);
  572. if (!store) {
  573. toastMessage(`Cannot reset "${nodeId}" store because it wasn't found.`, 'warn');
  574. }
  575. else if (typeof store.$reset !== 'function') {
  576. toastMessage(`Cannot reset "${nodeId}" store because it doesn't have a "$reset" method implemented.`, 'warn');
  577. }
  578. else {
  579. store.$reset();
  580. toastMessage(`Store "${nodeId}" reset.`);
  581. }
  582. },
  583. },
  584. ],
  585. });
  586. api.on.inspectComponent((payload, ctx) => {
  587. const proxy = (payload.componentInstance &&
  588. payload.componentInstance.proxy);
  589. if (proxy && proxy._pStores) {
  590. const piniaStores = payload.componentInstance.proxy._pStores;
  591. Object.values(piniaStores).forEach((store) => {
  592. payload.instanceData.state.push({
  593. type: getStoreType(store.$id),
  594. key: 'state',
  595. editable: true,
  596. value: store._isOptionsAPI
  597. ? {
  598. _custom: {
  599. value: vueDemi.toRaw(store.$state),
  600. actions: [
  601. {
  602. icon: 'restore',
  603. tooltip: 'Reset the state of this store',
  604. action: () => store.$reset(),
  605. },
  606. ],
  607. },
  608. }
  609. : // NOTE: workaround to unwrap transferred refs
  610. Object.keys(store.$state).reduce((state, key) => {
  611. state[key] = store.$state[key];
  612. return state;
  613. }, {}),
  614. });
  615. if (store._getters && store._getters.length) {
  616. payload.instanceData.state.push({
  617. type: getStoreType(store.$id),
  618. key: 'getters',
  619. editable: false,
  620. value: store._getters.reduce((getters, key) => {
  621. try {
  622. getters[key] = store[key];
  623. }
  624. catch (error) {
  625. // @ts-expect-error: we just want to show it in devtools
  626. getters[key] = error;
  627. }
  628. return getters;
  629. }, {}),
  630. });
  631. }
  632. });
  633. }
  634. });
  635. api.on.getInspectorTree((payload) => {
  636. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  637. let stores = [pinia];
  638. stores = stores.concat(Array.from(pinia._s.values()));
  639. payload.rootNodes = (payload.filter
  640. ? stores.filter((store) => '$id' in store
  641. ? store.$id
  642. .toLowerCase()
  643. .includes(payload.filter.toLowerCase())
  644. : PINIA_ROOT_LABEL.toLowerCase().includes(payload.filter.toLowerCase()))
  645. : stores).map(formatStoreForInspectorTree);
  646. }
  647. });
  648. // Expose pinia instance as $pinia to window
  649. globalThis.$pinia = pinia;
  650. api.on.getInspectorState((payload) => {
  651. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  652. const inspectedStore = payload.nodeId === PINIA_ROOT_ID
  653. ? pinia
  654. : pinia._s.get(payload.nodeId);
  655. if (!inspectedStore) {
  656. // this could be the selected store restored for a different project
  657. // so it's better not to say anything here
  658. return;
  659. }
  660. if (inspectedStore) {
  661. // Expose selected store as $store to window
  662. if (payload.nodeId !== PINIA_ROOT_ID)
  663. globalThis.$store = vueDemi.toRaw(inspectedStore);
  664. payload.state = formatStoreForInspectorState(inspectedStore);
  665. }
  666. }
  667. });
  668. api.on.editInspectorState((payload, ctx) => {
  669. if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
  670. const inspectedStore = payload.nodeId === PINIA_ROOT_ID
  671. ? pinia
  672. : pinia._s.get(payload.nodeId);
  673. if (!inspectedStore) {
  674. return toastMessage(`store "${payload.nodeId}" not found`, 'error');
  675. }
  676. const { path } = payload;
  677. if (!isPinia(inspectedStore)) {
  678. // access only the state
  679. if (path.length !== 1 ||
  680. !inspectedStore._customProperties.has(path[0]) ||
  681. path[0] in inspectedStore.$state) {
  682. path.unshift('$state');
  683. }
  684. }
  685. else {
  686. // Root access, we can omit the `.value` because the devtools API does it for us
  687. path.unshift('state');
  688. }
  689. isTimelineActive = false;
  690. payload.set(inspectedStore, path, payload.state.value);
  691. isTimelineActive = true;
  692. }
  693. });
  694. api.on.editComponentState((payload) => {
  695. if (payload.type.startsWith('🍍')) {
  696. const storeId = payload.type.replace(/^🍍\s*/, '');
  697. const store = pinia._s.get(storeId);
  698. if (!store) {
  699. return toastMessage(`store "${storeId}" not found`, 'error');
  700. }
  701. const { path } = payload;
  702. if (path[0] !== 'state') {
  703. return toastMessage(`Invalid path for store "${storeId}":\n${path}\nOnly state can be modified.`);
  704. }
  705. // rewrite the first entry to be able to directly set the state as
  706. // well as any other path
  707. path[0] = '$state';
  708. isTimelineActive = false;
  709. payload.set(store, path, payload.state.value);
  710. isTimelineActive = true;
  711. }
  712. });
  713. });
  714. }
  715. function addStoreToDevtools(app, store) {
  716. if (!componentStateTypes.includes(getStoreType(store.$id))) {
  717. componentStateTypes.push(getStoreType(store.$id));
  718. }
  719. devtoolsApi.setupDevtoolsPlugin({
  720. id: 'dev.esm.pinia',
  721. label: 'Pinia 🍍',
  722. logo: 'https://pinia.vuejs.org/logo.svg',
  723. packageName: 'pinia',
  724. homepage: 'https://pinia.vuejs.org',
  725. componentStateTypes,
  726. app,
  727. settings: {
  728. logStoreChanges: {
  729. label: 'Notify about new/deleted stores',
  730. type: 'boolean',
  731. defaultValue: true,
  732. },
  733. // useEmojis: {
  734. // label: 'Use emojis in messages ⚡️',
  735. // type: 'boolean',
  736. // defaultValue: true,
  737. // },
  738. },
  739. }, (api) => {
  740. // gracefully handle errors
  741. const now = typeof api.now === 'function' ? api.now.bind(api) : Date.now;
  742. store.$onAction(({ after, onError, name, args }) => {
  743. const groupId = runningActionId++;
  744. api.addTimelineEvent({
  745. layerId: MUTATIONS_LAYER_ID,
  746. event: {
  747. time: now(),
  748. title: '🛫 ' + name,
  749. subtitle: 'start',
  750. data: {
  751. store: formatDisplay(store.$id),
  752. action: formatDisplay(name),
  753. args,
  754. },
  755. groupId,
  756. },
  757. });
  758. after((result) => {
  759. activeAction = undefined;
  760. api.addTimelineEvent({
  761. layerId: MUTATIONS_LAYER_ID,
  762. event: {
  763. time: now(),
  764. title: '🛬 ' + name,
  765. subtitle: 'end',
  766. data: {
  767. store: formatDisplay(store.$id),
  768. action: formatDisplay(name),
  769. args,
  770. result,
  771. },
  772. groupId,
  773. },
  774. });
  775. });
  776. onError((error) => {
  777. activeAction = undefined;
  778. api.addTimelineEvent({
  779. layerId: MUTATIONS_LAYER_ID,
  780. event: {
  781. time: now(),
  782. logType: 'error',
  783. title: '💥 ' + name,
  784. subtitle: 'end',
  785. data: {
  786. store: formatDisplay(store.$id),
  787. action: formatDisplay(name),
  788. args,
  789. error,
  790. },
  791. groupId,
  792. },
  793. });
  794. });
  795. }, true);
  796. store._customProperties.forEach((name) => {
  797. vueDemi.watch(() => vueDemi.unref(store[name]), (newValue, oldValue) => {
  798. api.notifyComponentUpdate();
  799. api.sendInspectorState(INSPECTOR_ID);
  800. if (isTimelineActive) {
  801. api.addTimelineEvent({
  802. layerId: MUTATIONS_LAYER_ID,
  803. event: {
  804. time: now(),
  805. title: 'Change',
  806. subtitle: name,
  807. data: {
  808. newValue,
  809. oldValue,
  810. },
  811. groupId: activeAction,
  812. },
  813. });
  814. }
  815. }, { deep: true });
  816. });
  817. store.$subscribe(({ events, type }, state) => {
  818. api.notifyComponentUpdate();
  819. api.sendInspectorState(INSPECTOR_ID);
  820. if (!isTimelineActive)
  821. return;
  822. // rootStore.state[store.id] = state
  823. const eventData = {
  824. time: now(),
  825. title: formatMutationType(type),
  826. data: assign$1({ store: formatDisplay(store.$id) }, formatEventData(events)),
  827. groupId: activeAction,
  828. };
  829. if (type === exports.MutationType.patchFunction) {
  830. eventData.subtitle = '⤵️';
  831. }
  832. else if (type === exports.MutationType.patchObject) {
  833. eventData.subtitle = '🧩';
  834. }
  835. else if (events && !Array.isArray(events)) {
  836. eventData.subtitle = events.type;
  837. }
  838. if (events) {
  839. eventData.data['rawEvent(s)'] = {
  840. _custom: {
  841. display: 'DebuggerEvent',
  842. type: 'object',
  843. tooltip: 'raw DebuggerEvent[]',
  844. value: events,
  845. },
  846. };
  847. }
  848. api.addTimelineEvent({
  849. layerId: MUTATIONS_LAYER_ID,
  850. event: eventData,
  851. });
  852. }, { detached: true, flush: 'sync' });
  853. const hotUpdate = store._hotUpdate;
  854. store._hotUpdate = vueDemi.markRaw((newStore) => {
  855. hotUpdate(newStore);
  856. api.addTimelineEvent({
  857. layerId: MUTATIONS_LAYER_ID,
  858. event: {
  859. time: now(),
  860. title: '🔥 ' + store.$id,
  861. subtitle: 'HMR update',
  862. data: {
  863. store: formatDisplay(store.$id),
  864. info: formatDisplay(`HMR update`),
  865. },
  866. },
  867. });
  868. // update the devtools too
  869. api.notifyComponentUpdate();
  870. api.sendInspectorTree(INSPECTOR_ID);
  871. api.sendInspectorState(INSPECTOR_ID);
  872. });
  873. const { $dispose } = store;
  874. store.$dispose = () => {
  875. $dispose();
  876. api.notifyComponentUpdate();
  877. api.sendInspectorTree(INSPECTOR_ID);
  878. api.sendInspectorState(INSPECTOR_ID);
  879. api.getSettings().logStoreChanges &&
  880. toastMessage(`Disposed "${store.$id}" store 🗑`);
  881. };
  882. // trigger an update so it can display new registered stores
  883. api.notifyComponentUpdate();
  884. api.sendInspectorTree(INSPECTOR_ID);
  885. api.sendInspectorState(INSPECTOR_ID);
  886. api.getSettings().logStoreChanges &&
  887. toastMessage(`"${store.$id}" store installed 🆕`);
  888. });
  889. }
  890. let runningActionId = 0;
  891. let activeAction;
  892. /**
  893. * Patches a store to enable action grouping in devtools by wrapping the store with a Proxy that is passed as the
  894. * context of all actions, allowing us to set `runningAction` on each access and effectively associating any state
  895. * mutation to the action.
  896. *
  897. * @param store - store to patch
  898. * @param actionNames - list of actionst to patch
  899. */
  900. function patchActionForGrouping(store, actionNames, wrapWithProxy) {
  901. // original actions of the store as they are given by pinia. We are going to override them
  902. const actions = actionNames.reduce((storeActions, actionName) => {
  903. // use toRaw to avoid tracking #541
  904. storeActions[actionName] = vueDemi.toRaw(store)[actionName];
  905. return storeActions;
  906. }, {});
  907. for (const actionName in actions) {
  908. store[actionName] = function () {
  909. // the running action id is incremented in a before action hook
  910. const _actionId = runningActionId;
  911. const trackedStore = wrapWithProxy
  912. ? new Proxy(store, {
  913. get(...args) {
  914. activeAction = _actionId;
  915. return Reflect.get(...args);
  916. },
  917. set(...args) {
  918. activeAction = _actionId;
  919. return Reflect.set(...args);
  920. },
  921. })
  922. : store;
  923. // For Setup Stores we need https://github.com/tc39/proposal-async-context
  924. activeAction = _actionId;
  925. const retValue = actions[actionName].apply(trackedStore, arguments);
  926. // this is safer as async actions in Setup Stores would associate mutations done outside of the action
  927. activeAction = undefined;
  928. return retValue;
  929. };
  930. }
  931. }
  932. /**
  933. * pinia.use(devtoolsPlugin)
  934. */
  935. function devtoolsPlugin({ app, store, options }) {
  936. // HMR module
  937. if (store.$id.startsWith('__hot:')) {
  938. return;
  939. }
  940. // detect option api vs setup api
  941. store._isOptionsAPI = !!options.state;
  942. // Do not overwrite actions mocked by @pinia/testing (#2298)
  943. if (!store._p._testing) {
  944. patchActionForGrouping(store, Object.keys(options.actions), store._isOptionsAPI);
  945. // Upgrade the HMR to also update the new actions
  946. const originalHotUpdate = store._hotUpdate;
  947. vueDemi.toRaw(store)._hotUpdate = function (newStore) {
  948. originalHotUpdate.apply(this, arguments);
  949. patchActionForGrouping(store, Object.keys(newStore._hmrPayload.actions), !!store._isOptionsAPI);
  950. };
  951. }
  952. addStoreToDevtools(app,
  953. // FIXME: is there a way to allow the assignment from Store<Id, S, G, A> to StoreGeneric?
  954. store);
  955. }
  956. /**
  957. * Creates a Pinia instance to be used by the application
  958. */
  959. function createPinia() {
  960. const scope = vueDemi.effectScope(true);
  961. // NOTE: here we could check the window object for a state and directly set it
  962. // if there is anything like it with Vue 3 SSR
  963. const state = scope.run(() => vueDemi.ref({}));
  964. let _p = [];
  965. // plugins added before calling app.use(pinia)
  966. let toBeInstalled = [];
  967. const pinia = vueDemi.markRaw({
  968. install(app) {
  969. // this allows calling useStore() outside of a component setup after
  970. // installing pinia's plugin
  971. setActivePinia(pinia);
  972. if (!vueDemi.isVue2) {
  973. pinia._a = app;
  974. app.provide(piniaSymbol, pinia);
  975. app.config.globalProperties.$pinia = pinia;
  976. /* istanbul ignore else */
  977. if ((((process.env.NODE_ENV !== 'production') || false) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT) {
  978. registerPiniaDevtools(app, pinia);
  979. }
  980. toBeInstalled.forEach((plugin) => _p.push(plugin));
  981. toBeInstalled = [];
  982. }
  983. },
  984. use(plugin) {
  985. if (!this._a && !vueDemi.isVue2) {
  986. toBeInstalled.push(plugin);
  987. }
  988. else {
  989. _p.push(plugin);
  990. }
  991. return this;
  992. },
  993. _p,
  994. // it's actually undefined here
  995. // @ts-expect-error
  996. _a: null,
  997. _e: scope,
  998. _s: new Map(),
  999. state,
  1000. });
  1001. // pinia devtools rely on dev only features so they cannot be forced unless
  1002. // the dev build of Vue is used. Avoid old browsers like IE11.
  1003. if ((((process.env.NODE_ENV !== 'production') || false) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT && typeof Proxy !== 'undefined') {
  1004. pinia.use(devtoolsPlugin);
  1005. }
  1006. return pinia;
  1007. }
  1008. /**
  1009. * Dispose a Pinia instance by stopping its effectScope and removing the state, plugins and stores. This is mostly
  1010. * useful in tests, with both a testing pinia or a regular pinia and in applications that use multiple pinia instances.
  1011. * Once disposed, the pinia instance cannot be used anymore.
  1012. *
  1013. * @param pinia - pinia instance
  1014. */
  1015. function disposePinia(pinia) {
  1016. pinia._e.stop();
  1017. pinia._s.clear();
  1018. pinia._p.splice(0);
  1019. pinia.state.value = {};
  1020. // @ts-expect-error: non valid
  1021. pinia._a = null;
  1022. }
  1023. /**
  1024. * Checks if a function is a `StoreDefinition`.
  1025. *
  1026. * @param fn - object to test
  1027. * @returns true if `fn` is a StoreDefinition
  1028. */
  1029. const isUseStore = (fn) => {
  1030. return typeof fn === 'function' && typeof fn.$id === 'string';
  1031. };
  1032. /**
  1033. * Mutates in place `newState` with `oldState` to _hot update_ it. It will
  1034. * remove any key not existing in `newState` and recursively merge plain
  1035. * objects.
  1036. *
  1037. * @param newState - new state object to be patched
  1038. * @param oldState - old state that should be used to patch newState
  1039. * @returns - newState
  1040. */
  1041. function patchObject(newState, oldState) {
  1042. // no need to go through symbols because they cannot be serialized anyway
  1043. for (const key in oldState) {
  1044. const subPatch = oldState[key];
  1045. // skip the whole sub tree
  1046. if (!(key in newState)) {
  1047. continue;
  1048. }
  1049. const targetValue = newState[key];
  1050. if (isPlainObject(targetValue) &&
  1051. isPlainObject(subPatch) &&
  1052. !vueDemi.isRef(subPatch) &&
  1053. !vueDemi.isReactive(subPatch)) {
  1054. newState[key] = patchObject(targetValue, subPatch);
  1055. }
  1056. else {
  1057. // objects are either a bit more complex (e.g. refs) or primitives, so we
  1058. // just set the whole thing
  1059. if (vueDemi.isVue2) {
  1060. vueDemi.set(newState, key, subPatch);
  1061. }
  1062. else {
  1063. newState[key] = subPatch;
  1064. }
  1065. }
  1066. }
  1067. return newState;
  1068. }
  1069. /**
  1070. * Creates an _accept_ function to pass to `import.meta.hot` in Vite applications.
  1071. *
  1072. * @example
  1073. * ```js
  1074. * const useUser = defineStore(...)
  1075. * if (import.meta.hot) {
  1076. * import.meta.hot.accept(acceptHMRUpdate(useUser, import.meta.hot))
  1077. * }
  1078. * ```
  1079. *
  1080. * @param initialUseStore - return of the defineStore to hot update
  1081. * @param hot - `import.meta.hot`
  1082. */
  1083. function acceptHMRUpdate(initialUseStore, hot) {
  1084. // strip as much as possible from iife.prod
  1085. if (!(process.env.NODE_ENV !== 'production')) {
  1086. return () => { };
  1087. }
  1088. return (newModule) => {
  1089. const pinia = hot.data.pinia || initialUseStore._pinia;
  1090. if (!pinia) {
  1091. // this store is still not used
  1092. return;
  1093. }
  1094. // preserve the pinia instance across loads
  1095. hot.data.pinia = pinia;
  1096. // console.log('got data', newStore)
  1097. for (const exportName in newModule) {
  1098. const useStore = newModule[exportName];
  1099. // console.log('checking for', exportName)
  1100. if (isUseStore(useStore) && pinia._s.has(useStore.$id)) {
  1101. // console.log('Accepting update for', useStore.$id)
  1102. const id = useStore.$id;
  1103. if (id !== initialUseStore.$id) {
  1104. console.warn(`The id of the store changed from "${initialUseStore.$id}" to "${id}". Reloading.`);
  1105. // return import.meta.hot.invalidate()
  1106. return hot.invalidate();
  1107. }
  1108. const existingStore = pinia._s.get(id);
  1109. if (!existingStore) {
  1110. console.log(`[Pinia]: skipping hmr because store doesn't exist yet`);
  1111. return;
  1112. }
  1113. useStore(pinia, existingStore);
  1114. }
  1115. }
  1116. };
  1117. }
  1118. const noop = () => { };
  1119. function addSubscription(subscriptions, callback, detached, onCleanup = noop) {
  1120. subscriptions.push(callback);
  1121. const removeSubscription = () => {
  1122. const idx = subscriptions.indexOf(callback);
  1123. if (idx > -1) {
  1124. subscriptions.splice(idx, 1);
  1125. onCleanup();
  1126. }
  1127. };
  1128. if (!detached && vueDemi.getCurrentScope()) {
  1129. vueDemi.onScopeDispose(removeSubscription);
  1130. }
  1131. return removeSubscription;
  1132. }
  1133. function triggerSubscriptions(subscriptions, ...args) {
  1134. subscriptions.slice().forEach((callback) => {
  1135. callback(...args);
  1136. });
  1137. }
  1138. const fallbackRunWithContext = (fn) => fn();
  1139. /**
  1140. * Marks a function as an action for `$onAction`
  1141. * @internal
  1142. */
  1143. const ACTION_MARKER = Symbol();
  1144. /**
  1145. * Action name symbol. Allows to add a name to an action after defining it
  1146. * @internal
  1147. */
  1148. const ACTION_NAME = Symbol();
  1149. function mergeReactiveObjects(target, patchToApply) {
  1150. // Handle Map instances
  1151. if (target instanceof Map && patchToApply instanceof Map) {
  1152. patchToApply.forEach((value, key) => target.set(key, value));
  1153. }
  1154. else if (target instanceof Set && patchToApply instanceof Set) {
  1155. // Handle Set instances
  1156. patchToApply.forEach(target.add, target);
  1157. }
  1158. // no need to go through symbols because they cannot be serialized anyway
  1159. for (const key in patchToApply) {
  1160. if (!patchToApply.hasOwnProperty(key))
  1161. continue;
  1162. const subPatch = patchToApply[key];
  1163. const targetValue = target[key];
  1164. if (isPlainObject(targetValue) &&
  1165. isPlainObject(subPatch) &&
  1166. target.hasOwnProperty(key) &&
  1167. !vueDemi.isRef(subPatch) &&
  1168. !vueDemi.isReactive(subPatch)) {
  1169. // NOTE: here I wanted to warn about inconsistent types but it's not possible because in setup stores one might
  1170. // start the value of a property as a certain type e.g. a Map, and then for some reason, during SSR, change that
  1171. // to `undefined`. When trying to hydrate, we want to override the Map with `undefined`.
  1172. target[key] = mergeReactiveObjects(targetValue, subPatch);
  1173. }
  1174. else {
  1175. // @ts-expect-error: subPatch is a valid value
  1176. target[key] = subPatch;
  1177. }
  1178. }
  1179. return target;
  1180. }
  1181. const skipHydrateSymbol = (process.env.NODE_ENV !== 'production')
  1182. ? Symbol('pinia:skipHydration')
  1183. : /* istanbul ignore next */ Symbol();
  1184. /**
  1185. * Tells Pinia to skip the hydration process of a given object. This is useful in setup stores (only) when you return a
  1186. * stateful object in the store but it isn't really state. e.g. returning a router instance in a setup store.
  1187. *
  1188. * @param obj - target object
  1189. * @returns obj
  1190. */
  1191. function skipHydrate(obj) {
  1192. return Object.defineProperty(obj, skipHydrateSymbol, {});
  1193. }
  1194. /**
  1195. * Returns whether a value should be hydrated
  1196. *
  1197. * @param obj - target variable
  1198. * @returns true if `obj` should be hydrated
  1199. */
  1200. function shouldHydrate(obj) {
  1201. return !isPlainObject(obj) || !obj.hasOwnProperty(skipHydrateSymbol);
  1202. }
  1203. const { assign } = Object;
  1204. function isComputed(o) {
  1205. return !!(vueDemi.isRef(o) && o.effect);
  1206. }
  1207. function createOptionsStore(id, options, pinia, hot) {
  1208. const { state, actions, getters } = options;
  1209. const initialState = pinia.state.value[id];
  1210. let store;
  1211. function setup() {
  1212. if (!initialState && (!(process.env.NODE_ENV !== 'production') || !hot)) {
  1213. /* istanbul ignore if */
  1214. if (vueDemi.isVue2) {
  1215. vueDemi.set(pinia.state.value, id, state ? state() : {});
  1216. }
  1217. else {
  1218. pinia.state.value[id] = state ? state() : {};
  1219. }
  1220. }
  1221. // avoid creating a state in pinia.state.value
  1222. const localState = (process.env.NODE_ENV !== 'production') && hot
  1223. ? // use ref() to unwrap refs inside state TODO: check if this is still necessary
  1224. vueDemi.toRefs(vueDemi.ref(state ? state() : {}).value)
  1225. : vueDemi.toRefs(pinia.state.value[id]);
  1226. return assign(localState, actions, Object.keys(getters || {}).reduce((computedGetters, name) => {
  1227. if ((process.env.NODE_ENV !== 'production') && name in localState) {
  1228. console.warn(`[🍍]: A getter cannot have the same name as another state property. Rename one of them. Found with "${name}" in store "${id}".`);
  1229. }
  1230. computedGetters[name] = vueDemi.markRaw(vueDemi.computed(() => {
  1231. setActivePinia(pinia);
  1232. // it was created just before
  1233. const store = pinia._s.get(id);
  1234. // allow cross using stores
  1235. /* istanbul ignore if */
  1236. if (vueDemi.isVue2 && !store._r)
  1237. return;
  1238. // @ts-expect-error
  1239. // return getters![name].call(context, context)
  1240. // TODO: avoid reading the getter while assigning with a global variable
  1241. return getters[name].call(store, store);
  1242. }));
  1243. return computedGetters;
  1244. }, {}));
  1245. }
  1246. store = createSetupStore(id, setup, options, pinia, hot, true);
  1247. return store;
  1248. }
  1249. function createSetupStore($id, setup, options = {}, pinia, hot, isOptionsStore) {
  1250. let scope;
  1251. const optionsForPlugin = assign({ actions: {} }, options);
  1252. /* istanbul ignore if */
  1253. if ((process.env.NODE_ENV !== 'production') && !pinia._e.active) {
  1254. throw new Error('Pinia destroyed');
  1255. }
  1256. // watcher options for $subscribe
  1257. const $subscribeOptions = { deep: true };
  1258. /* istanbul ignore else */
  1259. if ((process.env.NODE_ENV !== 'production') && !vueDemi.isVue2) {
  1260. $subscribeOptions.onTrigger = (event) => {
  1261. /* istanbul ignore else */
  1262. if (isListening) {
  1263. debuggerEvents = event;
  1264. // avoid triggering this while the store is being built and the state is being set in pinia
  1265. }
  1266. else if (isListening == false && !store._hotUpdating) {
  1267. // let patch send all the events together later
  1268. /* istanbul ignore else */
  1269. if (Array.isArray(debuggerEvents)) {
  1270. debuggerEvents.push(event);
  1271. }
  1272. else {
  1273. console.error('🍍 debuggerEvents should be an array. This is most likely an internal Pinia bug.');
  1274. }
  1275. }
  1276. };
  1277. }
  1278. // internal state
  1279. let isListening; // set to true at the end
  1280. let isSyncListening; // set to true at the end
  1281. let subscriptions = [];
  1282. let actionSubscriptions = [];
  1283. let debuggerEvents;
  1284. const initialState = pinia.state.value[$id];
  1285. // avoid setting the state for option stores if it is set
  1286. // by the setup
  1287. if (!isOptionsStore && !initialState && (!(process.env.NODE_ENV !== 'production') || !hot)) {
  1288. /* istanbul ignore if */
  1289. if (vueDemi.isVue2) {
  1290. vueDemi.set(pinia.state.value, $id, {});
  1291. }
  1292. else {
  1293. pinia.state.value[$id] = {};
  1294. }
  1295. }
  1296. const hotState = vueDemi.ref({});
  1297. // avoid triggering too many listeners
  1298. // https://github.com/vuejs/pinia/issues/1129
  1299. let activeListener;
  1300. function $patch(partialStateOrMutator) {
  1301. let subscriptionMutation;
  1302. isListening = isSyncListening = false;
  1303. // reset the debugger events since patches are sync
  1304. /* istanbul ignore else */
  1305. if ((process.env.NODE_ENV !== 'production')) {
  1306. debuggerEvents = [];
  1307. }
  1308. if (typeof partialStateOrMutator === 'function') {
  1309. partialStateOrMutator(pinia.state.value[$id]);
  1310. subscriptionMutation = {
  1311. type: exports.MutationType.patchFunction,
  1312. storeId: $id,
  1313. events: debuggerEvents,
  1314. };
  1315. }
  1316. else {
  1317. mergeReactiveObjects(pinia.state.value[$id], partialStateOrMutator);
  1318. subscriptionMutation = {
  1319. type: exports.MutationType.patchObject,
  1320. payload: partialStateOrMutator,
  1321. storeId: $id,
  1322. events: debuggerEvents,
  1323. };
  1324. }
  1325. const myListenerId = (activeListener = Symbol());
  1326. vueDemi.nextTick().then(() => {
  1327. if (activeListener === myListenerId) {
  1328. isListening = true;
  1329. }
  1330. });
  1331. isSyncListening = true;
  1332. // because we paused the watcher, we need to manually call the subscriptions
  1333. triggerSubscriptions(subscriptions, subscriptionMutation, pinia.state.value[$id]);
  1334. }
  1335. const $reset = isOptionsStore
  1336. ? function $reset() {
  1337. const { state } = options;
  1338. const newState = state ? state() : {};
  1339. // we use a patch to group all changes into one single subscription
  1340. this.$patch(($state) => {
  1341. // @ts-expect-error: FIXME: shouldn't error?
  1342. assign($state, newState);
  1343. });
  1344. }
  1345. : /* istanbul ignore next */
  1346. (process.env.NODE_ENV !== 'production')
  1347. ? () => {
  1348. throw new Error(`🍍: Store "${$id}" is built using the setup syntax and does not implement $reset().`);
  1349. }
  1350. : noop;
  1351. function $dispose() {
  1352. scope.stop();
  1353. subscriptions = [];
  1354. actionSubscriptions = [];
  1355. pinia._s.delete($id);
  1356. }
  1357. /**
  1358. * Helper that wraps function so it can be tracked with $onAction
  1359. * @param fn - action to wrap
  1360. * @param name - name of the action
  1361. */
  1362. const action = (fn, name = '') => {
  1363. if (ACTION_MARKER in fn) {
  1364. fn[ACTION_NAME] = name;
  1365. return fn;
  1366. }
  1367. const wrappedAction = function () {
  1368. setActivePinia(pinia);
  1369. const args = Array.from(arguments);
  1370. const afterCallbackList = [];
  1371. const onErrorCallbackList = [];
  1372. function after(callback) {
  1373. afterCallbackList.push(callback);
  1374. }
  1375. function onError(callback) {
  1376. onErrorCallbackList.push(callback);
  1377. }
  1378. // @ts-expect-error
  1379. triggerSubscriptions(actionSubscriptions, {
  1380. args,
  1381. name: wrappedAction[ACTION_NAME],
  1382. store,
  1383. after,
  1384. onError,
  1385. });
  1386. let ret;
  1387. try {
  1388. ret = fn.apply(this && this.$id === $id ? this : store, args);
  1389. // handle sync errors
  1390. }
  1391. catch (error) {
  1392. triggerSubscriptions(onErrorCallbackList, error);
  1393. throw error;
  1394. }
  1395. if (ret instanceof Promise) {
  1396. return ret
  1397. .then((value) => {
  1398. triggerSubscriptions(afterCallbackList, value);
  1399. return value;
  1400. })
  1401. .catch((error) => {
  1402. triggerSubscriptions(onErrorCallbackList, error);
  1403. return Promise.reject(error);
  1404. });
  1405. }
  1406. // trigger after callbacks
  1407. triggerSubscriptions(afterCallbackList, ret);
  1408. return ret;
  1409. };
  1410. wrappedAction[ACTION_MARKER] = true;
  1411. wrappedAction[ACTION_NAME] = name; // will be set later
  1412. // @ts-expect-error: we are intentionally limiting the returned type to just Fn
  1413. // because all the added properties are internals that are exposed through `$onAction()` only
  1414. return wrappedAction;
  1415. };
  1416. const _hmrPayload = /*#__PURE__*/ vueDemi.markRaw({
  1417. actions: {},
  1418. getters: {},
  1419. state: [],
  1420. hotState,
  1421. });
  1422. const partialStore = {
  1423. _p: pinia,
  1424. // _s: scope,
  1425. $id,
  1426. $onAction: addSubscription.bind(null, actionSubscriptions),
  1427. $patch,
  1428. $reset,
  1429. $subscribe(callback, options = {}) {
  1430. const removeSubscription = addSubscription(subscriptions, callback, options.detached, () => stopWatcher());
  1431. const stopWatcher = scope.run(() => vueDemi.watch(() => pinia.state.value[$id], (state) => {
  1432. if (options.flush === 'sync' ? isSyncListening : isListening) {
  1433. callback({
  1434. storeId: $id,
  1435. type: exports.MutationType.direct,
  1436. events: debuggerEvents,
  1437. }, state);
  1438. }
  1439. }, assign({}, $subscribeOptions, options)));
  1440. return removeSubscription;
  1441. },
  1442. $dispose,
  1443. };
  1444. /* istanbul ignore if */
  1445. if (vueDemi.isVue2) {
  1446. // start as non ready
  1447. partialStore._r = false;
  1448. }
  1449. const store = vueDemi.reactive((process.env.NODE_ENV !== 'production') || ((((process.env.NODE_ENV !== 'production') || false) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT)
  1450. ? assign({
  1451. _hmrPayload,
  1452. _customProperties: vueDemi.markRaw(new Set()), // devtools custom properties
  1453. }, partialStore
  1454. // must be added later
  1455. // setupStore
  1456. )
  1457. : partialStore);
  1458. // store the partial store now so the setup of stores can instantiate each other before they are finished without
  1459. // creating infinite loops.
  1460. pinia._s.set($id, store);
  1461. const runWithContext = (pinia._a && pinia._a.runWithContext) || fallbackRunWithContext;
  1462. // TODO: idea create skipSerialize that marks properties as non serializable and they are skipped
  1463. const setupStore = runWithContext(() => pinia._e.run(() => (scope = vueDemi.effectScope()).run(() => setup({ action }))));
  1464. // overwrite existing actions to support $onAction
  1465. for (const key in setupStore) {
  1466. const prop = setupStore[key];
  1467. if ((vueDemi.isRef(prop) && !isComputed(prop)) || vueDemi.isReactive(prop)) {
  1468. // mark it as a piece of state to be serialized
  1469. if ((process.env.NODE_ENV !== 'production') && hot) {
  1470. vueDemi.set(hotState.value, key, vueDemi.toRef(setupStore, key));
  1471. // createOptionStore directly sets the state in pinia.state.value so we
  1472. // can just skip that
  1473. }
  1474. else if (!isOptionsStore) {
  1475. // in setup stores we must hydrate the state and sync pinia state tree with the refs the user just created
  1476. if (initialState && shouldHydrate(prop)) {
  1477. if (vueDemi.isRef(prop)) {
  1478. prop.value = initialState[key];
  1479. }
  1480. else {
  1481. // probably a reactive object, lets recursively assign
  1482. // @ts-expect-error: prop is unknown
  1483. mergeReactiveObjects(prop, initialState[key]);
  1484. }
  1485. }
  1486. // transfer the ref to the pinia state to keep everything in sync
  1487. /* istanbul ignore if */
  1488. if (vueDemi.isVue2) {
  1489. vueDemi.set(pinia.state.value[$id], key, prop);
  1490. }
  1491. else {
  1492. pinia.state.value[$id][key] = prop;
  1493. }
  1494. }
  1495. /* istanbul ignore else */
  1496. if ((process.env.NODE_ENV !== 'production')) {
  1497. _hmrPayload.state.push(key);
  1498. }
  1499. // action
  1500. }
  1501. else if (typeof prop === 'function') {
  1502. const actionValue = (process.env.NODE_ENV !== 'production') && hot ? prop : action(prop, key);
  1503. // this a hot module replacement store because the hotUpdate method needs
  1504. // to do it with the right context
  1505. /* istanbul ignore if */
  1506. if (vueDemi.isVue2) {
  1507. vueDemi.set(setupStore, key, actionValue);
  1508. }
  1509. else {
  1510. // @ts-expect-error
  1511. setupStore[key] = actionValue;
  1512. }
  1513. /* istanbul ignore else */
  1514. if ((process.env.NODE_ENV !== 'production')) {
  1515. _hmrPayload.actions[key] = prop;
  1516. }
  1517. // list actions so they can be used in plugins
  1518. // @ts-expect-error
  1519. optionsForPlugin.actions[key] = prop;
  1520. }
  1521. else if ((process.env.NODE_ENV !== 'production')) {
  1522. // add getters for devtools
  1523. if (isComputed(prop)) {
  1524. _hmrPayload.getters[key] = isOptionsStore
  1525. ? // @ts-expect-error
  1526. options.getters[key]
  1527. : prop;
  1528. if (IS_CLIENT) {
  1529. const getters = setupStore._getters ||
  1530. // @ts-expect-error: same
  1531. (setupStore._getters = vueDemi.markRaw([]));
  1532. getters.push(key);
  1533. }
  1534. }
  1535. }
  1536. }
  1537. // add the state, getters, and action properties
  1538. /* istanbul ignore if */
  1539. if (vueDemi.isVue2) {
  1540. Object.keys(setupStore).forEach((key) => {
  1541. vueDemi.set(store, key, setupStore[key]);
  1542. });
  1543. }
  1544. else {
  1545. assign(store, setupStore);
  1546. // allows retrieving reactive objects with `storeToRefs()`. Must be called after assigning to the reactive object.
  1547. // Make `storeToRefs()` work with `reactive()` #799
  1548. assign(vueDemi.toRaw(store), setupStore);
  1549. }
  1550. // use this instead of a computed with setter to be able to create it anywhere
  1551. // without linking the computed lifespan to wherever the store is first
  1552. // created.
  1553. Object.defineProperty(store, '$state', {
  1554. get: () => ((process.env.NODE_ENV !== 'production') && hot ? hotState.value : pinia.state.value[$id]),
  1555. set: (state) => {
  1556. /* istanbul ignore if */
  1557. if ((process.env.NODE_ENV !== 'production') && hot) {
  1558. throw new Error('cannot set hotState');
  1559. }
  1560. $patch(($state) => {
  1561. // @ts-expect-error: FIXME: shouldn't error?
  1562. assign($state, state);
  1563. });
  1564. },
  1565. });
  1566. // add the hotUpdate before plugins to allow them to override it
  1567. /* istanbul ignore else */
  1568. if ((process.env.NODE_ENV !== 'production')) {
  1569. store._hotUpdate = vueDemi.markRaw((newStore) => {
  1570. store._hotUpdating = true;
  1571. newStore._hmrPayload.state.forEach((stateKey) => {
  1572. if (stateKey in store.$state) {
  1573. const newStateTarget = newStore.$state[stateKey];
  1574. const oldStateSource = store.$state[stateKey];
  1575. if (typeof newStateTarget === 'object' &&
  1576. isPlainObject(newStateTarget) &&
  1577. isPlainObject(oldStateSource)) {
  1578. patchObject(newStateTarget, oldStateSource);
  1579. }
  1580. else {
  1581. // transfer the ref
  1582. newStore.$state[stateKey] = oldStateSource;
  1583. }
  1584. }
  1585. // patch direct access properties to allow store.stateProperty to work as
  1586. // store.$state.stateProperty
  1587. vueDemi.set(store, stateKey, vueDemi.toRef(newStore.$state, stateKey));
  1588. });
  1589. // remove deleted state properties
  1590. Object.keys(store.$state).forEach((stateKey) => {
  1591. if (!(stateKey in newStore.$state)) {
  1592. vueDemi.del(store, stateKey);
  1593. }
  1594. });
  1595. // avoid devtools logging this as a mutation
  1596. isListening = false;
  1597. isSyncListening = false;
  1598. pinia.state.value[$id] = vueDemi.toRef(newStore._hmrPayload, 'hotState');
  1599. isSyncListening = true;
  1600. vueDemi.nextTick().then(() => {
  1601. isListening = true;
  1602. });
  1603. for (const actionName in newStore._hmrPayload.actions) {
  1604. const actionFn = newStore[actionName];
  1605. vueDemi.set(store, actionName, action(actionFn, actionName));
  1606. }
  1607. // TODO: does this work in both setup and option store?
  1608. for (const getterName in newStore._hmrPayload.getters) {
  1609. const getter = newStore._hmrPayload.getters[getterName];
  1610. const getterValue = isOptionsStore
  1611. ? // special handling of options api
  1612. vueDemi.computed(() => {
  1613. setActivePinia(pinia);
  1614. return getter.call(store, store);
  1615. })
  1616. : getter;
  1617. vueDemi.set(store, getterName, getterValue);
  1618. }
  1619. // remove deleted getters
  1620. Object.keys(store._hmrPayload.getters).forEach((key) => {
  1621. if (!(key in newStore._hmrPayload.getters)) {
  1622. vueDemi.del(store, key);
  1623. }
  1624. });
  1625. // remove old actions
  1626. Object.keys(store._hmrPayload.actions).forEach((key) => {
  1627. if (!(key in newStore._hmrPayload.actions)) {
  1628. vueDemi.del(store, key);
  1629. }
  1630. });
  1631. // update the values used in devtools and to allow deleting new properties later on
  1632. store._hmrPayload = newStore._hmrPayload;
  1633. store._getters = newStore._getters;
  1634. store._hotUpdating = false;
  1635. });
  1636. }
  1637. if ((((process.env.NODE_ENV !== 'production') || false) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT) {
  1638. const nonEnumerable = {
  1639. writable: true,
  1640. configurable: true,
  1641. // avoid warning on devtools trying to display this property
  1642. enumerable: false,
  1643. };
  1644. ['_p', '_hmrPayload', '_getters', '_customProperties'].forEach((p) => {
  1645. Object.defineProperty(store, p, assign({ value: store[p] }, nonEnumerable));
  1646. });
  1647. }
  1648. /* istanbul ignore if */
  1649. if (vueDemi.isVue2) {
  1650. // mark the store as ready before plugins
  1651. store._r = true;
  1652. }
  1653. // apply all plugins
  1654. pinia._p.forEach((extender) => {
  1655. /* istanbul ignore else */
  1656. if ((((process.env.NODE_ENV !== 'production') || false) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT) {
  1657. const extensions = scope.run(() => extender({
  1658. store: store,
  1659. app: pinia._a,
  1660. pinia,
  1661. options: optionsForPlugin,
  1662. }));
  1663. Object.keys(extensions || {}).forEach((key) => store._customProperties.add(key));
  1664. assign(store, extensions);
  1665. }
  1666. else {
  1667. assign(store, scope.run(() => extender({
  1668. store: store,
  1669. app: pinia._a,
  1670. pinia,
  1671. options: optionsForPlugin,
  1672. })));
  1673. }
  1674. });
  1675. if ((process.env.NODE_ENV !== 'production') &&
  1676. store.$state &&
  1677. typeof store.$state === 'object' &&
  1678. typeof store.$state.constructor === 'function' &&
  1679. !store.$state.constructor.toString().includes('[native code]')) {
  1680. console.warn(`[🍍]: The "state" must be a plain object. It cannot be\n` +
  1681. `\tstate: () => new MyClass()\n` +
  1682. `Found in store "${store.$id}".`);
  1683. }
  1684. // only apply hydrate to option stores with an initial state in pinia
  1685. if (initialState &&
  1686. isOptionsStore &&
  1687. options.hydrate) {
  1688. options.hydrate(store.$state, initialState);
  1689. }
  1690. isListening = true;
  1691. isSyncListening = true;
  1692. return store;
  1693. }
  1694. // allows unused stores to be tree shaken
  1695. /*! #__NO_SIDE_EFFECTS__ */
  1696. function defineStore(
  1697. // TODO: add proper types from above
  1698. idOrOptions, setup, setupOptions) {
  1699. let id;
  1700. let options;
  1701. const isSetupStore = typeof setup === 'function';
  1702. if (typeof idOrOptions === 'string') {
  1703. id = idOrOptions;
  1704. // the option store setup will contain the actual options in this case
  1705. options = isSetupStore ? setupOptions : setup;
  1706. }
  1707. else {
  1708. options = idOrOptions;
  1709. id = idOrOptions.id;
  1710. if ((process.env.NODE_ENV !== 'production') && typeof id !== 'string') {
  1711. throw new Error(`[🍍]: "defineStore()" must be passed a store id as its first argument.`);
  1712. }
  1713. }
  1714. function useStore(pinia, hot) {
  1715. const hasContext = vueDemi.hasInjectionContext();
  1716. pinia =
  1717. // in test mode, ignore the argument provided as we can always retrieve a
  1718. // pinia instance with getActivePinia()
  1719. ((process.env.NODE_ENV === 'test') && activePinia && activePinia._testing ? null : pinia) ||
  1720. (hasContext ? vueDemi.inject(piniaSymbol, null) : null);
  1721. if (pinia)
  1722. setActivePinia(pinia);
  1723. if ((process.env.NODE_ENV !== 'production') && !activePinia) {
  1724. throw new Error(`[🍍]: "getActivePinia()" was called but there was no active Pinia. Are you trying to use a store before calling "app.use(pinia)"?\n` +
  1725. `See https://pinia.vuejs.org/core-concepts/outside-component-usage.html for help.\n` +
  1726. `This will fail in production.`);
  1727. }
  1728. pinia = activePinia;
  1729. if (!pinia._s.has(id)) {
  1730. // creating the store registers it in `pinia._s`
  1731. if (isSetupStore) {
  1732. createSetupStore(id, setup, options, pinia);
  1733. }
  1734. else {
  1735. createOptionsStore(id, options, pinia);
  1736. }
  1737. /* istanbul ignore else */
  1738. if ((process.env.NODE_ENV !== 'production')) {
  1739. // @ts-expect-error: not the right inferred type
  1740. useStore._pinia = pinia;
  1741. }
  1742. }
  1743. const store = pinia._s.get(id);
  1744. if ((process.env.NODE_ENV !== 'production') && hot) {
  1745. const hotId = '__hot:' + id;
  1746. const newStore = isSetupStore
  1747. ? createSetupStore(hotId, setup, options, pinia, true)
  1748. : createOptionsStore(hotId, assign({}, options), pinia, true);
  1749. hot._hotUpdate(newStore);
  1750. // cleanup the state properties and the store from the cache
  1751. delete pinia.state.value[hotId];
  1752. pinia._s.delete(hotId);
  1753. }
  1754. if ((process.env.NODE_ENV !== 'production') && IS_CLIENT) {
  1755. const currentInstance = vueDemi.getCurrentInstance();
  1756. // save stores in instances to access them devtools
  1757. if (currentInstance &&
  1758. currentInstance.proxy &&
  1759. // avoid adding stores that are just built for hot module replacement
  1760. !hot) {
  1761. const vm = currentInstance.proxy;
  1762. const cache = '_pStores' in vm ? vm._pStores : (vm._pStores = {});
  1763. cache[id] = store;
  1764. }
  1765. }
  1766. // StoreGeneric cannot be casted towards Store
  1767. return store;
  1768. }
  1769. useStore.$id = id;
  1770. return useStore;
  1771. }
  1772. let mapStoreSuffix = 'Store';
  1773. /**
  1774. * Changes the suffix added by `mapStores()`. Can be set to an empty string.
  1775. * Defaults to `"Store"`. Make sure to extend the MapStoresCustomization
  1776. * interface if you are using TypeScript.
  1777. *
  1778. * @param suffix - new suffix
  1779. */
  1780. function setMapStoreSuffix(suffix // could be 'Store' but that would be annoying for JS
  1781. ) {
  1782. mapStoreSuffix = suffix;
  1783. }
  1784. /**
  1785. * Allows using stores without the composition API (`setup()`) by generating an
  1786. * object to be spread in the `computed` field of a component. It accepts a list
  1787. * of store definitions.
  1788. *
  1789. * @example
  1790. * ```js
  1791. * export default {
  1792. * computed: {
  1793. * // other computed properties
  1794. * ...mapStores(useUserStore, useCartStore)
  1795. * },
  1796. *
  1797. * created() {
  1798. * this.userStore // store with id "user"
  1799. * this.cartStore // store with id "cart"
  1800. * }
  1801. * }
  1802. * ```
  1803. *
  1804. * @param stores - list of stores to map to an object
  1805. */
  1806. function mapStores(...stores) {
  1807. if ((process.env.NODE_ENV !== 'production') && Array.isArray(stores[0])) {
  1808. console.warn(`[🍍]: Directly pass all stores to "mapStores()" without putting them in an array:\n` +
  1809. `Replace\n` +
  1810. `\tmapStores([useAuthStore, useCartStore])\n` +
  1811. `with\n` +
  1812. `\tmapStores(useAuthStore, useCartStore)\n` +
  1813. `This will fail in production if not fixed.`);
  1814. stores = stores[0];
  1815. }
  1816. return stores.reduce((reduced, useStore) => {
  1817. // @ts-expect-error: $id is added by defineStore
  1818. reduced[useStore.$id + mapStoreSuffix] = function () {
  1819. return useStore(this.$pinia);
  1820. };
  1821. return reduced;
  1822. }, {});
  1823. }
  1824. /**
  1825. * Allows using state and getters from one store without using the composition
  1826. * API (`setup()`) by generating an object to be spread in the `computed` field
  1827. * of a component.
  1828. *
  1829. * @param useStore - store to map from
  1830. * @param keysOrMapper - array or object
  1831. */
  1832. function mapState(useStore, keysOrMapper) {
  1833. return Array.isArray(keysOrMapper)
  1834. ? keysOrMapper.reduce((reduced, key) => {
  1835. reduced[key] = function () {
  1836. // @ts-expect-error: FIXME: should work?
  1837. return useStore(this.$pinia)[key];
  1838. };
  1839. return reduced;
  1840. }, {})
  1841. : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1842. // @ts-expect-error
  1843. reduced[key] = function () {
  1844. const store = useStore(this.$pinia);
  1845. const storeKey = keysOrMapper[key];
  1846. // for some reason TS is unable to infer the type of storeKey to be a
  1847. // function
  1848. return typeof storeKey === 'function'
  1849. ? storeKey.call(this, store)
  1850. : // @ts-expect-error: FIXME: should work?
  1851. store[storeKey];
  1852. };
  1853. return reduced;
  1854. }, {});
  1855. }
  1856. /**
  1857. * Alias for `mapState()`. You should use `mapState()` instead.
  1858. * @deprecated use `mapState()` instead.
  1859. */
  1860. const mapGetters = mapState;
  1861. /**
  1862. * Allows directly using actions from your store without using the composition
  1863. * API (`setup()`) by generating an object to be spread in the `methods` field
  1864. * of a component.
  1865. *
  1866. * @param useStore - store to map from
  1867. * @param keysOrMapper - array or object
  1868. */
  1869. function mapActions(useStore, keysOrMapper) {
  1870. return Array.isArray(keysOrMapper)
  1871. ? keysOrMapper.reduce((reduced, key) => {
  1872. // @ts-expect-error
  1873. reduced[key] = function (...args) {
  1874. // @ts-expect-error: FIXME: should work?
  1875. return useStore(this.$pinia)[key](...args);
  1876. };
  1877. return reduced;
  1878. }, {})
  1879. : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1880. // @ts-expect-error
  1881. reduced[key] = function (...args) {
  1882. // @ts-expect-error: FIXME: should work?
  1883. return useStore(this.$pinia)[keysOrMapper[key]](...args);
  1884. };
  1885. return reduced;
  1886. }, {});
  1887. }
  1888. /**
  1889. * Allows using state and getters from one store without using the composition
  1890. * API (`setup()`) by generating an object to be spread in the `computed` field
  1891. * of a component.
  1892. *
  1893. * @param useStore - store to map from
  1894. * @param keysOrMapper - array or object
  1895. */
  1896. function mapWritableState(useStore, keysOrMapper) {
  1897. return Array.isArray(keysOrMapper)
  1898. ? keysOrMapper.reduce((reduced, key) => {
  1899. reduced[key] = {
  1900. get() {
  1901. return useStore(this.$pinia)[key];
  1902. },
  1903. set(value) {
  1904. return (useStore(this.$pinia)[key] = value);
  1905. },
  1906. };
  1907. return reduced;
  1908. }, {})
  1909. : Object.keys(keysOrMapper).reduce((reduced, key) => {
  1910. reduced[key] = {
  1911. get() {
  1912. return useStore(this.$pinia)[keysOrMapper[key]];
  1913. },
  1914. set(value) {
  1915. return (useStore(this.$pinia)[keysOrMapper[key]] = value);
  1916. },
  1917. };
  1918. return reduced;
  1919. }, {});
  1920. }
  1921. /**
  1922. * Creates an object of references with all the state, getters, and plugin-added
  1923. * state properties of the store. Similar to `toRefs()` but specifically
  1924. * designed for Pinia stores so methods and non reactive properties are
  1925. * completely ignored.
  1926. *
  1927. * @param store - store to extract the refs from
  1928. */
  1929. function storeToRefs(store) {
  1930. // See https://github.com/vuejs/pinia/issues/852
  1931. // It's easier to just use toRefs() even if it includes more stuff
  1932. if (vueDemi.isVue2) {
  1933. // @ts-expect-error: toRefs include methods and others
  1934. return vueDemi.toRefs(store);
  1935. }
  1936. else {
  1937. const rawStore = vueDemi.toRaw(store);
  1938. const refs = {};
  1939. for (const key in rawStore) {
  1940. const value = rawStore[key];
  1941. // There is no native method to check for a computed
  1942. // https://github.com/vuejs/core/pull/4165
  1943. if (value.effect) {
  1944. // @ts-expect-error: too hard to type correctly
  1945. refs[key] =
  1946. // ...
  1947. vueDemi.computed({
  1948. get: () => store[key],
  1949. set(value) {
  1950. store[key] = value;
  1951. },
  1952. });
  1953. }
  1954. else if (vueDemi.isRef(value) || vueDemi.isReactive(value)) {
  1955. // @ts-expect-error: the key is state or getter
  1956. refs[key] =
  1957. // ---
  1958. vueDemi.toRef(store, key);
  1959. }
  1960. }
  1961. return refs;
  1962. }
  1963. }
  1964. /**
  1965. * Vue 2 Plugin that must be installed for pinia to work. Note **you don't need
  1966. * this plugin if you are using Nuxt.js**. Use the `buildModule` instead:
  1967. * https://pinia.vuejs.org/ssr/nuxt.html.
  1968. *
  1969. * @example
  1970. * ```js
  1971. * import Vue from 'vue'
  1972. * import { PiniaVuePlugin, createPinia } from 'pinia'
  1973. *
  1974. * Vue.use(PiniaVuePlugin)
  1975. * const pinia = createPinia()
  1976. *
  1977. * new Vue({
  1978. * el: '#app',
  1979. * // ...
  1980. * pinia,
  1981. * })
  1982. * ```
  1983. *
  1984. * @param _Vue - `Vue` imported from 'vue'.
  1985. */
  1986. const PiniaVuePlugin = function (_Vue) {
  1987. // Equivalent of
  1988. // app.config.globalProperties.$pinia = pinia
  1989. _Vue.mixin({
  1990. beforeCreate() {
  1991. const options = this.$options;
  1992. if (options.pinia) {
  1993. const pinia = options.pinia;
  1994. // HACK: taken from provide(): https://github.com/vuejs/composition-api/blob/main/src/apis/inject.ts#L31
  1995. /* istanbul ignore else */
  1996. if (!this._provided) {
  1997. const provideCache = {};
  1998. Object.defineProperty(this, '_provided', {
  1999. get: () => provideCache,
  2000. set: (v) => Object.assign(provideCache, v),
  2001. });
  2002. }
  2003. this._provided[piniaSymbol] = pinia;
  2004. // propagate the pinia instance in an SSR friendly way
  2005. // avoid adding it to nuxt twice
  2006. /* istanbul ignore else */
  2007. if (!this.$pinia) {
  2008. this.$pinia = pinia;
  2009. }
  2010. pinia._a = this;
  2011. if (IS_CLIENT) {
  2012. // this allows calling useStore() outside of a component setup after
  2013. // installing pinia's plugin
  2014. setActivePinia(pinia);
  2015. }
  2016. if ((((process.env.NODE_ENV !== 'production') || false) && !(process.env.NODE_ENV === 'test')) && IS_CLIENT) {
  2017. registerPiniaDevtools(pinia._a, pinia);
  2018. }
  2019. }
  2020. else if (!this.$pinia && options.parent && options.parent.$pinia) {
  2021. this.$pinia = options.parent.$pinia;
  2022. }
  2023. },
  2024. destroyed() {
  2025. delete this._pStores;
  2026. },
  2027. });
  2028. };
  2029. exports.PiniaVuePlugin = PiniaVuePlugin;
  2030. exports.acceptHMRUpdate = acceptHMRUpdate;
  2031. exports.createPinia = createPinia;
  2032. exports.defineStore = defineStore;
  2033. exports.disposePinia = disposePinia;
  2034. exports.getActivePinia = getActivePinia;
  2035. exports.mapActions = mapActions;
  2036. exports.mapGetters = mapGetters;
  2037. exports.mapState = mapState;
  2038. exports.mapStores = mapStores;
  2039. exports.mapWritableState = mapWritableState;
  2040. exports.setActivePinia = setActivePinia;
  2041. exports.setMapStoreSuffix = setMapStoreSuffix;
  2042. exports.shouldHydrate = shouldHydrate;
  2043. exports.skipHydrate = skipHydrate;
  2044. exports.storeToRefs = storeToRefs;