@growing-web/esm-pack-core
Version:
esm pack build core.
1,322 lines (1,305 loc) โข 81 kB
JavaScript
/*!
* pinia v2.0.13
* (c) 2022 Eduardo San Martin Morote
* @license MIT
*/
var Pinia = (function (exports, vueDemi) {
'use strict';
/**
* setActivePinia must be called to handle SSR at the top of functions like
* `fetch`, `setup`, `serverPrefetch` and others
*/
let activePinia;
/**
* Sets or unsets the active pinia. Used in SSR and internally when calling
* actions and getters
*
* @param pinia - Pinia instance
*/
const setActivePinia = (pinia) => (activePinia = pinia);
/**
* Get the currently active pinia if there is any.
*/
const getActivePinia = () => (vueDemi.getCurrentInstance() && vueDemi.inject(piniaSymbol)) || activePinia;
const piniaSymbol = (Symbol('pinia') );
function getDevtoolsGlobalHook() {
return getTarget().__VUE_DEVTOOLS_GLOBAL_HOOK__;
}
function getTarget() {
// @ts-ignore
return (typeof navigator !== 'undefined' && typeof window !== 'undefined')
? window
: typeof global !== 'undefined'
? global
: {};
}
const isProxyAvailable = typeof Proxy === 'function';
const HOOK_SETUP = 'devtools-plugin:setup';
const HOOK_PLUGIN_SETTINGS_SET = 'plugin:settings:set';
let supported;
let perf;
function isPerformanceSupported() {
var _a;
if (supported !== undefined) {
return supported;
}
if (typeof window !== 'undefined' && window.performance) {
supported = true;
perf = window.performance;
}
else if (typeof global !== 'undefined' && ((_a = global.perf_hooks) === null || _a === void 0 ? void 0 : _a.performance)) {
supported = true;
perf = global.perf_hooks.performance;
}
else {
supported = false;
}
return supported;
}
function now() {
return isPerformanceSupported() ? perf.now() : Date.now();
}
class ApiProxy {
constructor(plugin, hook) {
this.target = null;
this.targetQueue = [];
this.onQueue = [];
this.plugin = plugin;
this.hook = hook;
const defaultSettings = {};
if (plugin.settings) {
for (const id in plugin.settings) {
const item = plugin.settings[id];
defaultSettings[id] = item.defaultValue;
}
}
const localSettingsSaveId = `__vue-devtools-plugin-settings__${plugin.id}`;
let currentSettings = Object.assign({}, defaultSettings);
try {
const raw = localStorage.getItem(localSettingsSaveId);
const data = JSON.parse(raw);
Object.assign(currentSettings, data);
}
catch (e) {
// noop
}
this.fallbacks = {
getSettings() {
return currentSettings;
},
setSettings(value) {
try {
localStorage.setItem(localSettingsSaveId, JSON.stringify(value));
}
catch (e) {
// noop
}
currentSettings = value;
},
now() {
return now();
},
};
if (hook) {
hook.on(HOOK_PLUGIN_SETTINGS_SET, (pluginId, value) => {
if (pluginId === this.plugin.id) {
this.fallbacks.setSettings(value);
}
});
}
this.proxiedOn = new Proxy({}, {
get: (_target, prop) => {
if (this.target) {
return this.target.on[prop];
}
else {
return (...args) => {
this.onQueue.push({
method: prop,
args,
});
};
}
},
});
this.proxiedTarget = new Proxy({}, {
get: (_target, prop) => {
if (this.target) {
return this.target[prop];
}
else if (prop === 'on') {
return this.proxiedOn;
}
else if (Object.keys(this.fallbacks).includes(prop)) {
return (...args) => {
this.targetQueue.push({
method: prop,
args,
resolve: () => { },
});
return this.fallbacks[prop](...args);
};
}
else {
return (...args) => {
return new Promise(resolve => {
this.targetQueue.push({
method: prop,
args,
resolve,
});
});
};
}
},
});
}
async setRealTarget(target) {
this.target = target;
for (const item of this.onQueue) {
this.target.on[item.method](...item.args);
}
for (const item of this.targetQueue) {
item.resolve(await this.target[item.method](...item.args));
}
}
}
function setupDevtoolsPlugin(pluginDescriptor, setupFn) {
const descriptor = pluginDescriptor;
const target = getTarget();
const hook = getDevtoolsGlobalHook();
const enableProxy = isProxyAvailable && descriptor.enableEarlyProxy;
if (hook && (target.__VUE_DEVTOOLS_PLUGIN_API_AVAILABLE__ || !enableProxy)) {
hook.emit(HOOK_SETUP, pluginDescriptor, setupFn);
}
else {
const proxy = enableProxy ? new ApiProxy(descriptor, hook) : null;
const list = target.__VUE_DEVTOOLS_PLUGINS__ = target.__VUE_DEVTOOLS_PLUGINS__ || [];
list.push({
pluginDescriptor: descriptor,
setupFn,
proxy,
});
if (proxy)
setupFn(proxy.proxiedTarget);
}
}
function isPlainObject(
// eslint-disable-next-line @typescript-eslint/no-explicit-any
o) {
return (o &&
typeof o === 'object' &&
Object.prototype.toString.call(o) === '[object Object]' &&
typeof o.toJSON !== 'function');
}
// type DeepReadonly<T> = { readonly [P in keyof T]: DeepReadonly<T[P]> }
// TODO: can we change these to numbers?
/**
* Possible types for SubscriptionCallback
*/
exports.MutationType = void 0;
(function (MutationType) {
/**
* Direct mutation of the state:
*
* - `store.name = 'new name'`
* - `store.$state.name = 'new name'`
* - `store.list.push('new item')`
*/
MutationType["direct"] = "direct";
/**
* Mutated the state with `$patch` and an object
*
* - `store.$patch({ name: 'newName' })`
*/
MutationType["patchObject"] = "patch object";
/**
* Mutated the state with `$patch` and a function
*
* - `store.$patch(state => state.name = 'newName')`
*/
MutationType["patchFunction"] = "patch function";
// maybe reset? for $state = {} and $reset
})(exports.MutationType || (exports.MutationType = {}));
const IS_CLIENT = typeof window !== 'undefined';
/*
* FileSaver.js A saveAs() FileSaver implementation.
*
* Originally by Eli Grey, adapted as an ESM module by Eduardo San Martin
* Morote.
*
* License : MIT
*/
// The one and only way of getting global scope in all environments
// https://stackoverflow.com/q/3277182/1008999
const _global = /*#__PURE__*/ (() => 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 })();
function bom(blob, { autoBom = false } = {}) {
// prepend BOM for UTF-8 XML and text/* types (including HTML)
// note: your browser will automatically convert UTF-16 U+FEFF to EF BB BF
if (autoBom &&
/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(blob.type)) {
return new Blob([String.fromCharCode(0xfeff), blob], { type: blob.type });
}
return blob;
}
function download(url, name, opts) {
const xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.onload = function () {
saveAs(xhr.response, name, opts);
};
xhr.onerror = function () {
console.error('could not download file');
};
xhr.send();
}
function corsEnabled(url) {
const xhr = new XMLHttpRequest();
// use sync to avoid popup blocker
xhr.open('HEAD', url, false);
try {
xhr.send();
}
catch (e) { }
return xhr.status >= 200 && xhr.status <= 299;
}
// `a.click()` doesn't work for all browsers (#465)
function click(node) {
try {
node.dispatchEvent(new MouseEvent('click'));
}
catch (e) {
const evt = document.createEvent('MouseEvents');
evt.initMouseEvent('click', true, true, window, 0, 0, 0, 80, 20, false, false, false, false, 0, null);
node.dispatchEvent(evt);
}
}
const _navigator =
typeof navigator === 'object' ? navigator : { userAgent: '' };
// Detect WebView inside a native macOS app by ruling out all browsers
// We just need to check for 'Safari' because all other browsers (besides Firefox) include that too
// https://www.whatismybrowser.com/guides/the-latest-user-agent/macos
const isMacOSWebView = /*#__PURE__*/ (() => /Macintosh/.test(_navigator.userAgent) &&
/AppleWebKit/.test(_navigator.userAgent) &&
!/Safari/.test(_navigator.userAgent))();
const saveAs = !IS_CLIENT
? () => { } // noop
: // Use download attribute first if possible (#193 Lumia mobile) unless this is a macOS WebView or mini program
typeof HTMLAnchorElement !== 'undefined' &&
'download' in HTMLAnchorElement.prototype &&
!isMacOSWebView
? downloadSaveAs
: // Use msSaveOrOpenBlob as a second approach
'msSaveOrOpenBlob' in _navigator
? msSaveAs
: // Fallback to using FileReader and a popup
fileSaverSaveAs;
function downloadSaveAs(blob, name = 'download', opts) {
const a = document.createElement('a');
a.download = name;
a.rel = 'noopener'; // tabnabbing
// TODO: detect chrome extensions & packaged apps
// a.target = '_blank'
if (typeof blob === 'string') {
// Support regular links
a.href = blob;
if (a.origin !== location.origin) {
if (corsEnabled(a.href)) {
download(blob, name, opts);
}
else {
a.target = '_blank';
click(a);
}
}
else {
click(a);
}
}
else {
// Support blobs
a.href = URL.createObjectURL(blob);
setTimeout(function () {
URL.revokeObjectURL(a.href);
}, 4e4); // 40s
setTimeout(function () {
click(a);
}, 0);
}
}
function msSaveAs(blob, name = 'download', opts) {
if (typeof blob === 'string') {
if (corsEnabled(blob)) {
download(blob, name, opts);
}
else {
const a = document.createElement('a');
a.href = blob;
a.target = '_blank';
setTimeout(function () {
click(a);
});
}
}
else {
// @ts-ignore: works on windows
navigator.msSaveOrOpenBlob(bom(blob, opts), name);
}
}
function fileSaverSaveAs(blob, name, opts, popup) {
// Open a popup immediately do go around popup blocker
// Mostly only available on user interaction and the fileReader is async so...
popup = popup || open('', '_blank');
if (popup) {
popup.document.title = popup.document.body.innerText = 'downloading...';
}
if (typeof blob === 'string')
return download(blob, name, opts);
const force = blob.type === 'application/octet-stream';
const isSafari = /constructor/i.test(String(_global.HTMLElement)) || 'safari' in _global;
const isChromeIOS = /CriOS\/[\d]+/.test(navigator.userAgent);
if ((isChromeIOS || (force && isSafari) || isMacOSWebView) &&
typeof FileReader !== 'undefined') {
// Safari doesn't allow downloading of blob URLs
const reader = new FileReader();
reader.onloadend = function () {
let url = reader.result;
if (typeof url !== 'string') {
popup = null;
throw new Error('Wrong reader.result type');
}
url = isChromeIOS
? url
: url.replace(/^data:[^;]*;/, 'data:attachment/file;');
if (popup) {
popup.location.href = url;
}
else {
location.assign(url);
}
popup = null; // reverse-tabnabbing #460
};
reader.readAsDataURL(blob);
}
else {
const url = URL.createObjectURL(blob);
if (popup)
popup.location.assign(url);
else
location.href = url;
popup = null; // reverse-tabnabbing #460
setTimeout(function () {
URL.revokeObjectURL(url);
}, 4e4); // 40s
}
}
/**
* Shows a toast or console.log
*
* @param message - message to log
* @param type - different color of the tooltip
*/
function toastMessage(message, type) {
const piniaMessage = '๐ ' + message;
if (typeof __VUE_DEVTOOLS_TOAST__ === 'function') {
__VUE_DEVTOOLS_TOAST__(piniaMessage, type);
}
else if (type === 'error') {
console.error(piniaMessage);
}
else if (type === 'warn') {
console.warn(piniaMessage);
}
else {
console.log(piniaMessage);
}
}
function isPinia(o) {
return '_a' in o && 'install' in o;
}
function checkClipboardAccess() {
if (!('clipboard' in navigator)) {
toastMessage(`Your browser doesn't support the Clipboard API`, 'error');
return true;
}
}
function checkNotFocusedError(error) {
if (error instanceof Error &&
error.message.toLowerCase().includes('document is not focused')) {
toastMessage('You need to activate the "Emulate a focused page" setting in the "Rendering" panel of devtools.', 'warn');
return true;
}
return false;
}
async function actionGlobalCopyState(pinia) {
if (checkClipboardAccess())
return;
try {
await navigator.clipboard.writeText(JSON.stringify(pinia.state.value));
toastMessage('Global state copied to clipboard.');
}
catch (error) {
if (checkNotFocusedError(error))
return;
toastMessage(`Failed to serialize the state. Check the console for more details.`, 'error');
console.error(error);
}
}
async function actionGlobalPasteState(pinia) {
if (checkClipboardAccess())
return;
try {
pinia.state.value = JSON.parse(await navigator.clipboard.readText());
toastMessage('Global state pasted from clipboard.');
}
catch (error) {
if (checkNotFocusedError(error))
return;
toastMessage(`Failed to deserialize the state from clipboard. Check the console for more details.`, 'error');
console.error(error);
}
}
async function actionGlobalSaveState(pinia) {
try {
saveAs(new Blob([JSON.stringify(pinia.state.value)], {
type: 'text/plain;charset=utf-8',
}), 'pinia-state.json');
}
catch (error) {
toastMessage(`Failed to export the state as JSON. Check the console for more details.`, 'error');
console.error(error);
}
}
let fileInput;
function getFileOpener() {
if (!fileInput) {
fileInput = document.createElement('input');
fileInput.type = 'file';
fileInput.accept = '.json';
}
function openFile() {
return new Promise((resolve, reject) => {
fileInput.onchange = async () => {
const files = fileInput.files;
if (!files)
return resolve(null);
const file = files.item(0);
if (!file)
return resolve(null);
return resolve({ text: await file.text(), file });
};
// @ts-ignore: TODO: changed from 4.3 to 4.4
fileInput.oncancel = () => resolve(null);
fileInput.onerror = reject;
fileInput.click();
});
}
return openFile;
}
async function actionGlobalOpenStateFile(pinia) {
try {
const open = await getFileOpener();
const result = await open();
if (!result)
return;
const { text, file } = result;
pinia.state.value = JSON.parse(text);
toastMessage(`Global state imported from "${file.name}".`);
}
catch (error) {
toastMessage(`Failed to export the state as JSON. Check the console for more details.`, 'error');
console.error(error);
}
}
function formatDisplay(display) {
return {
_custom: {
display,
},
};
}
const PINIA_ROOT_LABEL = '๐ Pinia (root)';
const PINIA_ROOT_ID = '_root';
function formatStoreForInspectorTree(store) {
return isPinia(store)
? {
id: PINIA_ROOT_ID,
label: PINIA_ROOT_LABEL,
}
: {
id: store.$id,
label: store.$id,
};
}
function formatStoreForInspectorState(store) {
if (isPinia(store)) {
const storeNames = Array.from(store._s.keys());
const storeMap = store._s;
const state = {
state: storeNames.map((storeId) => ({
editable: true,
key: storeId,
value: store.state.value[storeId],
})),
getters: storeNames
.filter((id) => storeMap.get(id)._getters)
.map((id) => {
const store = storeMap.get(id);
return {
editable: false,
key: id,
value: store._getters.reduce((getters, key) => {
getters[key] = store[key];
return getters;
}, {}),
};
}),
};
return state;
}
const state = {
state: Object.keys(store.$state).map((key) => ({
editable: true,
key,
value: store.$state[key],
})),
};
// avoid adding empty getters
if (store._getters && store._getters.length) {
state.getters = store._getters.map((getterName) => ({
editable: false,
key: getterName,
value: store[getterName],
}));
}
if (store._customProperties.size) {
state.customProperties = Array.from(store._customProperties).map((key) => ({
editable: true,
key,
value: store[key],
}));
}
return state;
}
function formatEventData(events) {
if (!events)
return {};
if (Array.isArray(events)) {
// TODO: handle add and delete for arrays and objects
return events.reduce((data, event) => {
data.keys.push(event.key);
data.operations.push(event.type);
data.oldValue[event.key] = event.oldValue;
data.newValue[event.key] = event.newValue;
return data;
}, {
oldValue: {},
keys: [],
operations: [],
newValue: {},
});
}
else {
return {
operation: formatDisplay(events.type),
key: formatDisplay(events.key),
oldValue: events.oldValue,
newValue: events.newValue,
};
}
}
function formatMutationType(type) {
switch (type) {
case exports.MutationType.direct:
return 'mutation';
case exports.MutationType.patchFunction:
return '$patch';
case exports.MutationType.patchObject:
return '$patch';
default:
return 'unknown';
}
}
// timeline can be paused when directly changing the state
let isTimelineActive = true;
const componentStateTypes = [];
const MUTATIONS_LAYER_ID = 'pinia:mutations';
const INSPECTOR_ID = 'pinia';
/**
* Gets the displayed name of a store in devtools
*
* @param id - id of the store
* @returns a formatted string
*/
const getStoreType = (id) => '๐ ' + id;
/**
* Add the pinia plugin without any store. Allows displaying a Pinia plugin tab
* as soon as it is added to the application.
*
* @param app - Vue application
* @param pinia - pinia instance
*/
function registerPiniaDevtools(app, pinia) {
setupDevtoolsPlugin({
id: 'dev.esm.pinia',
label: 'Pinia ๐',
logo: 'https://pinia.vuejs.org/logo.svg',
packageName: 'pinia',
homepage: 'https://pinia.vuejs.org',
componentStateTypes,
app,
}, (api) => {
if (typeof api.now !== 'function') {
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.');
}
api.addTimelineLayer({
id: MUTATIONS_LAYER_ID,
label: `Pinia ๐`,
color: 0xe5df88,
});
api.addInspector({
id: INSPECTOR_ID,
label: 'Pinia ๐',
icon: 'storage',
treeFilterPlaceholder: 'Search stores',
actions: [
{
icon: 'content_copy',
action: () => {
actionGlobalCopyState(pinia);
},
tooltip: 'Serialize and copy the state',
},
{
icon: 'content_paste',
action: async () => {
await actionGlobalPasteState(pinia);
api.sendInspectorTree(INSPECTOR_ID);
api.sendInspectorState(INSPECTOR_ID);
},
tooltip: 'Replace the state with the content of your clipboard',
},
{
icon: 'save',
action: () => {
actionGlobalSaveState(pinia);
},
tooltip: 'Save the state as a JSON file',
},
{
icon: 'folder_open',
action: async () => {
await actionGlobalOpenStateFile(pinia);
api.sendInspectorTree(INSPECTOR_ID);
api.sendInspectorState(INSPECTOR_ID);
},
tooltip: 'Import the state from a JSON file',
},
],
});
api.on.inspectComponent((payload, ctx) => {
const proxy = (payload.componentInstance &&
payload.componentInstance.proxy);
if (proxy && proxy._pStores) {
const piniaStores = payload.componentInstance.proxy._pStores;
Object.values(piniaStores).forEach((store) => {
payload.instanceData.state.push({
type: getStoreType(store.$id),
key: 'state',
editable: true,
value: store._isOptionsAPI
? {
_custom: {
value: store.$state,
actions: [
{
icon: 'restore',
tooltip: 'Reset the state of this store',
action: () => store.$reset(),
},
],
},
}
: store.$state,
});
if (store._getters && store._getters.length) {
payload.instanceData.state.push({
type: getStoreType(store.$id),
key: 'getters',
editable: false,
value: store._getters.reduce((getters, key) => {
try {
getters[key] = store[key];
}
catch (error) {
// @ts-expect-error: we just want to show it in devtools
getters[key] = error;
}
return getters;
}, {}),
});
}
});
}
});
api.on.getInspectorTree((payload) => {
if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
let stores = [pinia];
stores = stores.concat(Array.from(pinia._s.values()));
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);
}
});
api.on.getInspectorState((payload) => {
if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
const inspectedStore = payload.nodeId === PINIA_ROOT_ID
? pinia
: pinia._s.get(payload.nodeId);
if (!inspectedStore) {
// this could be the selected store restored for a different project
// so it's better not to say anything here
return;
}
if (inspectedStore) {
payload.state = formatStoreForInspectorState(inspectedStore);
}
}
});
api.on.editInspectorState((payload, ctx) => {
if (payload.app === app && payload.inspectorId === INSPECTOR_ID) {
const inspectedStore = payload.nodeId === PINIA_ROOT_ID
? pinia
: pinia._s.get(payload.nodeId);
if (!inspectedStore) {
return toastMessage(`store "${payload.nodeId}" not found`, 'error');
}
const { path } = payload;
if (!isPinia(inspectedStore)) {
// access only the state
if (path.length !== 1 ||
!inspectedStore._customProperties.has(path[0]) ||
path[0] in inspectedStore.$state) {
path.unshift('$state');
}
}
else {
// Root access, we can omit the `.value` because the devtools API does it for us
path.unshift('state');
}
isTimelineActive = false;
payload.set(inspectedStore, path, payload.state.value);
isTimelineActive = true;
}
});
api.on.editComponentState((payload) => {
if (payload.type.startsWith('๐')) {
const storeId = payload.type.replace(/^๐\s*/, '');
const store = pinia._s.get(storeId);
if (!store) {
return toastMessage(`store "${storeId}" not found`, 'error');
}
const { path } = payload;
if (path[0] !== 'state') {
return toastMessage(`Invalid path for store "${storeId}":\n${path}\nOnly state can be modified.`);
}
// rewrite the first entry to be able to directly set the state as
// well as any other path
path[0] = '$state';
isTimelineActive = false;
payload.set(store, path, payload.state.value);
isTimelineActive = true;
}
});
});
}
function addStoreToDevtools(app, store) {
if (!componentStateTypes.includes(getStoreType(store.$id))) {
componentStateTypes.push(getStoreType(store.$id));
}
setupDevtoolsPlugin({
id: 'dev.esm.pinia',
label: 'Pinia ๐',
logo: 'https://pinia.vuejs.org/logo.svg',
packageName: 'pinia',
homepage: 'https://pinia.vuejs.org',
componentStateTypes,
app,
settings: {
logStoreChanges: {
label: 'Notify about new/deleted stores',
type: 'boolean',
defaultValue: true,
},
// useEmojis: {
// label: 'Use emojis in messages โก๏ธ',
// type: 'boolean',
// defaultValue: true,
// },
},
}, (api) => {
// gracefully handle errors
const now = typeof api.now === 'function' ? api.now.bind(api) : Date.now;
store.$onAction(({ after, onError, name, args }) => {
const groupId = runningActionId++;
api.addTimelineEvent({
layerId: MUTATIONS_LAYER_ID,
event: {
time: now(),
title: '๐ซ ' + name,
subtitle: 'start',
data: {
store: formatDisplay(store.$id),
action: formatDisplay(name),
args,
},
groupId,
},
});
after((result) => {
activeAction = undefined;
api.addTimelineEvent({
layerId: MUTATIONS_LAYER_ID,
event: {
time: now(),
title: '๐ฌ ' + name,
subtitle: 'end',
data: {
store: formatDisplay(store.$id),
action: formatDisplay(name),
args,
result,
},
groupId,
},
});
});
onError((error) => {
activeAction = undefined;
api.addTimelineEvent({
layerId: MUTATIONS_LAYER_ID,
event: {
time: now(),
logType: 'error',
title: '๐ฅ ' + name,
subtitle: 'end',
data: {
store: formatDisplay(store.$id),
action: formatDisplay(name),
args,
error,
},
groupId,
},
});
});
}, true);
store._customProperties.forEach((name) => {
vueDemi.watch(() => vueDemi.unref(store[name]), (newValue, oldValue) => {
api.notifyComponentUpdate();
api.sendInspectorState(INSPECTOR_ID);
if (isTimelineActive) {
api.addTimelineEvent({
layerId: MUTATIONS_LAYER_ID,
event: {
time: now(),
title: 'Change',
subtitle: name,
data: {
newValue,
oldValue,
},
groupId: activeAction,
},
});
}
}, { deep: true });
});
store.$subscribe(({ events, type }, state) => {
api.notifyComponentUpdate();
api.sendInspectorState(INSPECTOR_ID);
if (!isTimelineActive)
return;
// rootStore.state[store.id] = state
const eventData = {
time: now(),
title: formatMutationType(type),
data: {
store: formatDisplay(store.$id),
...formatEventData(events),
},
groupId: activeAction,
};
// reset for the next mutation
activeAction = undefined;
if (type === exports.MutationType.patchFunction) {
eventData.subtitle = 'โคต๏ธ';
}
else if (type === exports.MutationType.patchObject) {
eventData.subtitle = '๐งฉ';
}
else if (events && !Array.isArray(events)) {
eventData.subtitle = events.type;
}
if (events) {
eventData.data['rawEvent(s)'] = {
_custom: {
display: 'DebuggerEvent',
type: 'object',
tooltip: 'raw DebuggerEvent[]',
value: events,
},
};
}
api.addTimelineEvent({
layerId: MUTATIONS_LAYER_ID,
event: eventData,
});
}, { detached: true, flush: 'sync' });
const hotUpdate = store._hotUpdate;
store._hotUpdate = vueDemi.markRaw((newStore) => {
hotUpdate(newStore);
api.addTimelineEvent({
layerId: MUTATIONS_LAYER_ID,
event: {
time: now(),
title: '๐ฅ ' + store.$id,
subtitle: 'HMR update',
data: {
store: formatDisplay(store.$id),
info: formatDisplay(`HMR update`),
},
},
});
// update the devtools too
api.notifyComponentUpdate();
api.sendInspectorTree(INSPECTOR_ID);
api.sendInspectorState(INSPECTOR_ID);
});
const { $dispose } = store;
store.$dispose = () => {
$dispose();
api.notifyComponentUpdate();
api.sendInspectorTree(INSPECTOR_ID);
api.sendInspectorState(INSPECTOR_ID);
api.getSettings().logStoreChanges &&
toastMessage(`Disposed "${store.$id}" store ๐`);
};
// trigger an update so it can display new registered stores
api.notifyComponentUpdate();
api.sendInspectorTree(INSPECTOR_ID);
api.sendInspectorState(INSPECTOR_ID);
api.getSettings().logStoreChanges &&
toastMessage(`"${store.$id}" store installed ๐`);
});
}
let runningActionId = 0;
let activeAction;
/**
* Patches a store to enable action grouping in devtools by wrapping the store with a Proxy that is passed as the
* context of all actions, allowing us to set `runningAction` on each access and effectively associating any state
* mutation to the action.
*
* @param store - store to patch
* @param actionNames - list of actionst to patch
*/
function patchActionForGrouping(store, actionNames) {
// original actions of the store as they are given by pinia. We are going to override them
const actions = actionNames.reduce((storeActions, actionName) => {
// use toRaw to avoid tracking #541
storeActions[actionName] = vueDemi.toRaw(store)[actionName];
return storeActions;
}, {});
for (const actionName in actions) {
store[actionName] = function () {
// setActivePinia(store._p)
// the running action id is incremented in a before action hook
const _actionId = runningActionId;
const trackedStore = new Proxy(store, {
get(...args) {
activeAction = _actionId;
return Reflect.get(...args);
},
set(...args) {
activeAction = _actionId;
return Reflect.set(...args);
},
});
return actions[actionName].apply(trackedStore, arguments);
};
}
}
/**
* pinia.use(devtoolsPlugin)
*/
function devtoolsPlugin({ app, store, options }) {
// HMR module
if (store.$id.startsWith('__hot:')) {
return;
}
// detect option api vs setup api
if (options.state) {
store._isOptionsAPI = true;
}
// only wrap actions in option-defined stores as this technique relies on
// wrapping the context of the action with a proxy
if (typeof options.state === 'function') {
patchActionForGrouping(
// @ts-expect-error: can cast the store...
store, Object.keys(options.actions));
const originalHotUpdate = store._hotUpdate;
// Upgrade the HMR to also update the new actions
vueDemi.toRaw(store)._hotUpdate = function (newStore) {
originalHotUpdate.apply(this, arguments);
patchActionForGrouping(store, Object.keys(newStore._hmrPayload.actions));
};
}
addStoreToDevtools(app,
// FIXME: is there a way to allow the assignment from Store<Id, S, G, A> to StoreGeneric?
store);
}
/**
* Creates a Pinia instance to be used by the application
*/
function createPinia() {
const scope = vueDemi.effectScope(true);
// NOTE: here we could check the window object for a state and directly set it
// if there is anything like it with Vue 3 SSR
const state = scope.run(() => vueDemi.ref({}));
let _p = [];
// plugins added before calling app.use(pinia)
let toBeInstalled = [];
const pinia = vueDemi.markRaw({
install(app) {
// this allows calling useStore() outside of a component setup after
// installing pinia's plugin
setActivePinia(pinia);
if (!vueDemi.isVue2) {
pinia._a = app;
app.provide(piniaSymbol, pinia);
app.config.globalProperties.$pinia = pinia;
/* istanbul ignore else */
if (IS_CLIENT) {
registerPiniaDevtools(app, pinia);
}
toBeInstalled.forEach((plugin) => _p.push(plugin));
toBeInstalled = [];
}
},
use(plugin) {
if (!this._a && !vueDemi.isVue2) {
toBeInstalled.push(plugin);
}
else {
_p.push(plugin);
}
return this;
},
_p,
// it's actually undefined here
// @ts-expect-error
_a: null,
_e: scope,
_s: new Map(),
state,
});
// pinia devtools rely on dev only features so they cannot be forced unless
// the dev build of Vue is used
if (IS_CLIENT) {
pinia.use(devtoolsPlugin);
}
return pinia;
}
/**
* Checks if a function is a `StoreDefinition`.
*
* @param fn - object to test
* @returns true if `fn` is a StoreDefinition
*/
const isUseStore = (fn) => {
return typeof fn === 'function' && typeof fn.$id === 'string';
};
/**
* Mutates in place `newState` with `oldState` to _hot update_ it. It will
* remove any key not existing in `newState` and recursively merge plain
* objects.
*
* @param newState - new state object to be patched
* @param oldState - old state that should be used to patch newState
* @returns - newState
*/
function patchObject(newState, oldState) {
// no need to go through symbols because they cannot be serialized anyway
for (const key in oldState) {
const subPatch = oldState[key];
// skip the whole sub tree
if (!(key in newState)) {
continue;
}
const targetValue = newState[key];
if (isPlainObject(targetValue) &&
isPlainObject(subPatch) &&
!vueDemi.isRef(subPatch) &&
!vueDemi.isReactive(subPatch)) {
newState[key] = patchObject(targetValue, subPatch);
}
else {
// objects are either a bit more complex (e.g. refs) or primitives, so we
// just set the whole thing
if (vueDemi.isVue2) {
vueDemi.set(newState, key, subPatch);
}
else {
newState[key] = subPatch;
}
}
}
return newState;
}
/**
* Creates an _accept_ function to pass to `import.meta.hot` in Vite applications.
*
* @example
* ```js
* const useUser = defineStore(...)
* if (import.meta.hot) {
* import.meta.hot.accept(acceptHMRUpdate(useUser, import.meta.hot))
* }
* ```
*
* @param initialUseStore - return of the defineStore to hot update
* @param hot - `import.meta.hot`
*/
function acceptHMRUpdate(initialUseStore, hot) {
return (newModule) => {
const pinia = hot.data.pinia || initialUseStore._pinia;
if (!pinia) {
// this store is still not used
return;
}
// preserve the pinia instance across loads
hot.data.pinia = pinia;
// console.log('got data', newStore)
for (const exportName in newModule) {
const useStore = newModule[exportName];
// console.log('checking for', exportName)
if (isUseStore(useStore) && pinia._s.has(useStore.$id)) {
// console.log('Accepting update for', useStore.$id)
const id = useStore.$id;
if (id !== initialUseStore.$id) {
console.warn(`The id of the store changed from "${initialUseStore.$id}" to "${id}". Reloading.`);
// return import.meta.hot.invalidate()
return hot.invalidate();
}
const existingStore = pinia._s.get(id);
if (!existingStore) {
console.log(`[Pinia]: skipping hmr because store doesn't exist yet`);
return;
}
useStore(pinia, existingStore);
}
}
};
}
const noop = () => { };
function addSubscription(subscriptions, callback, detached, onCleanup = noop) {
subscriptions.push(callback);
const removeSubscription = () => {
const idx = subscriptions.indexOf(callback);
if (idx > -1) {
subscriptions.splice(idx, 1);
onCleanup();
}
};
if (!detached && vueDemi.getCurrentInstance()) {
vueDemi.onUnmounted(removeSubscription);
}
return removeSubscription;
}
function triggerSubscriptions(subscriptions, ...args) {
subscriptions.slice().forEach((callback) => {
callback(...args);
});
}
function mergeReactiveObjects(target, patchToApply) {
// no need to go through symbols because they cannot be serialized anyway
for (const key in patchToApply) {
if (!patchToApply.hasOwnProperty(key))
continue;
const subPatch = patchToApply[key];
const targetValue = target[key];
if (isPlainObject(targetValue) &&
isPlainObject(subPatch) &&
target.hasOwnProperty(key) &&
!vueDemi.isRef(subPatch) &&
!vueDemi.isReactive(subPatch)) {
target[key] = mergeReactiveObjects(targetValue, subPatch);
}
else {
// @ts-expect-error: subPatch is a valid value
target[key] = subPatch;
}
}
return target;
}
const skipHydrateSymbol = Symbol('pinia:skipHydration')
;
const skipHydrateMap = /*#__PURE__*/ new WeakMap();
function skipHydrate(obj) {
return vueDemi.isVue2
? // in @vue/composition-api, the refs are sealed so defineProperty doesn't work...
/* istanbul ignore next */ skipHydrateMap.set(obj, 1) && obj
: Object.defineProperty(obj, skipHydrateSymbol, {});
}
function shouldHydrate(obj) {
return vueDemi.isVue2
? /* istanbul ignore next */ !skipHydrateMap.has(obj)
: !isPlainObject(obj) || !obj.hasOwnProperty(skipHydrateSymbol);
}
const { assign } = Object;
function isComputed(o) {
return !!(vueDemi.isRef(o) && o.effect);
}
function createOptionsStore(id, options, pinia, hot) {
const { state, actions, getters } = options;
const initialState = pinia.state.value[id];
let store;
function setup() {
if (!initialState && (!hot)) {
/* istanbul ignore if */
if (vueDemi.isVue2) {
vueDemi.set(pinia.state.value, id, state ? state() : {});
}
else {
pinia.state.value[id] = state ? state() : {};
}
}
// avoid creating a state in pinia.state.value
const localState = hot
? // use ref() to unwrap refs inside state TODO: check if this is still necessary
vueDemi.toRefs(vueDemi.ref(state ? state() : {}).value)
: vueDemi.toRefs(pinia.state.value[id]);
return assign(localState, actions, Object.keys(getters || {}).reduce((computedGetters, name) => {
computedGetters[name] = vueDemi.markRaw(vueDemi.computed(() => {
setActivePinia(pinia);
// it was created just before
const store = pinia._s.get(id);
// allow cross using stores
/* istanbul ignore next */
if (vueDemi.isVue2 && !store._r)
return;
// @ts-expect-error
// return getters![name].call(context, co