All files / ext.wikilambda.edit/store/modules library.js

96.47% Statements 137/142
84.05% Branches 58/69
100% Functions 32/32
96.45% Lines 136/141

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549                    17x 17x 17x 17x   17x                                                                 604x 602x 602x 602x 601x     3x   604x                           47x       111x 2x         109x   108x   108x 107x 107x   107x       60x 60x 60x         46x       46x 46x       1x   106x         2x                               45x   41x                               903x   882x                               851x 851x   161x                                 11x 11x 10x 10x   1x   10x                                 28x 28x       28x 28x 14x   14x     14x   4x                                 16x 16x     16x 16x   16x             15x       1x         6x                                 26x 26x 1x   25x 25x 1x     24x   26x                         1118x 559x   559x                   443x 436x                     1149x                                       572x 572x     572x   572x       1582x         601x       1582x 376x         572x     572x 572x 67x       572x 67x   67x 559x       67x 559x     67x       572x                                     65x 65x         65x 65x 65x   65x   443x           443x 443x             443x             443x 442x         442x 442x           443x 443x       443x         268x   268x 661x       661x   661x         661x 661x           268x 1x 1x 1x   268x 1x 1x 1x   268x         30x   30x 46x       46x   46x         46x 46x     30x             443x       65x            
/*!
 * WikiLambda Vue editor:  Vuex library module: fetch, store and
 * provide auxiliary data from other ZObejcts (labels, keys, etc.).
 * It also contains other helper getters to retrieve details of other
 * stored auxiliary objects such as functions, languages, etc.
 *
 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
 * @license MIT
 */
 
const Constants = require( '../../Constants.js' ),
	apiUtils = require( '../../mixins/api.js' ).methods,
	typeUtils = require( '../../mixins/typeUtils.js' ).methods,
	LabelData = require( '../classes/LabelData.js' );
 
module.exports = exports = {
	state: {
		/**
		 * Collection of ZPersistent objects fetched
		 * and indexed by their ZID.
		 */
		objects: {},
		/**
		 * Collection of LabelData object indexed by the identifier of
		 * the ZKey, ZPersistentObject or ZArgumentDeclaration.
		 */
		labels: {},
		/**
		 * Collection of the requested zids and the resolving promises
		 * zid: promise
		 */
		requests: {}
	},
	getters: {
		/**
		 * Returns the string value of the language Iso code if the object
		 * has been fetched and is stored in the state.
		 * If not available, returns the input zid.
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getLanguageIsoCodeOfZLang: function ( state ) {
			/**
			 * @param {string} zid
			 * @return {string}
			 */
			function findLanguageCode( zid ) {
				if ( state.objects[ zid ] ) {
					const zobject = state.objects[ zid ][ Constants.Z_PERSISTENTOBJECT_VALUE ];
					const ztype = zobject[ Constants.Z_OBJECT_TYPE ];
					if ( ztype === Constants.Z_NATURAL_LANGUAGE ) {
						return zobject[ Constants.Z_NATURAL_LANGUAGE_ISO_CODE ];
					}
				}
				return zid;
			}
			return findLanguageCode;
		},
		/**
		 * Given a global ZKey (ZnKm) it returns a string that reflects
		 * its expected value type (if any). Else it returns Z1.
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getExpectedTypeOfKey: function ( state ) {
			/**
			 * @param {string} key
			 * @return {string}
			 */
			return function ( key ) {
 
				// If the key is undefined, then this is the root object,
				// the expected type is always Z2/Persistent object type
				if ( key === undefined ) {
					return Constants.Z_PERSISTENTOBJECT;
				}
 
				// TODO (T324251): if this is an array index, (an integer),
				// should we return the expected type for the typed list?
				if ( typeUtils.isGlobalKey( key ) ) {
					let type;
					const zid = typeUtils.getZidOfGlobalKey( key );
 
					if ( state.objects[ zid ] ) {
						const zobject = state.objects[ zid ][ Constants.Z_PERSISTENTOBJECT_VALUE ];
						const ztype = zobject[ Constants.Z_OBJECT_TYPE ];
 
						switch ( ztype ) {
							// Return the key value type if zid belongs to a type
							case Constants.Z_TYPE:
								// eslint-disable-next-line no-case-declarations
								const zkey = typeUtils.getKeyFromKeyList( key, zobject[ Constants.Z_TYPE_KEYS ] );
								type = zkey ? zkey[ Constants.Z_KEY_TYPE ] : Constants.Z_OBJECT;
								break;
 
							// Return the argument type if the zid belongs to a function
							case Constants.Z_FUNCTION:
								// eslint-disable-next-line no-case-declarations
								const zarg = typeUtils.getArgFromArgList(
									key,
									zobject[ Constants.Z_FUNCTION_ARGUMENTS ]
								);
								type = zarg ? zarg[ Constants.Z_ARGUMENT_TYPE ] : Constants.Z_OBJECT;
								break;
 
							// If not found, return Z1/ZObject (any) type
							default:
								return Constants.Z_OBJECT;
						}
						return type;
					}
				}
 
				// If key is a not found, a list index or a local key, return Z1/Object (any) type
				return Constants.Z_OBJECT;
			};
		},
		/**
		 * Returns the persisted object for a given ZID if that was
		 * fetched from the DB and saved in the state. Else returns undefined
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getStoredObject: function ( state ) {
			/**
			 * @param {string} zid of the ZPersistentObject
			 * @return {Object|undefined} persisted ZObject
			 */
			function findPersistedObject( zid ) {
				return state.objects[ zid ];
			}
			return findPersistedObject;
		},
		/**
		 * Returns the LabelData of the ID of a ZKey, ZPersistentObject or ZArgumentDeclaration.
		 * The label is in the user selected language, if available, or else in the closest fallback.
		 * If not available, returns undefined.
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getLabelData: function ( state ) {
			/**
			 * @param {string} id of the ZPersistentObject, ZKey or ZArgumentDeclaration
			 * @return {LabelData|undefined} contains zid, label and lang properties
			 */
			function findLabelData( id ) {
				return state.labels[ id ];
			}
			return findLabelData;
		},
		/**
		 * Returns the string label of the ID of a ZKey, ZPersistentObject or ZArgumentDeclaration
		 * or the string ID if the label is not available.
		 *
		 * @param {Object} _state
		 * @param {Object} getters
		 * @return {Function}
		 */
		getLabel: function ( _state, getters ) {
			/**
			 * @param {string} id of the ZPersistentObject, ZKey or ZArgumentDeclaration
			 * @return {string} label or id
			 */
			function findLabel( id ) {
				const labelData = getters.getLabelData( id );
				return labelData ? labelData.label : id;
			}
			return findLabel;
		},
		/**
		 * Returns the array of implementations or tests connected to a persisted
		 * Function stored in the library, given the Function Zid and the key
		 * identifying the object list (tests or implementations)
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getConnectedObjects: function ( state ) {
			/**
			 * @param {string} zid
			 * @param {string} key
			 * @return {Array}
			 */
			function findConnectedObjects( zid, key ) {
				const func = state.objects[ zid ];
				if ( func ) {
					const imps = func[ Constants.Z_PERSISTENTOBJECT_VALUE ][ key ];
					return imps ? imps.slice( 1 ) : [];
				}
				return [];
			}
			return findConnectedObjects;
		},
		/**
		 * Returns the type of an implementation stored in the
		 * global state, given its Zid. The type will be
		 * composition/Z14K2, built-in/Z14K4, or code/Z14K3.
		 * If the implementation Zid is unknown returns undefined.
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getTypeOfImplementation: function ( state ) {
			/**
			 * @param {string} zid
			 * @return {string | undefined}
			 */
			function findImplementationType( zid ) {
				let implementation = state.objects[ zid ];
				Iif ( !implementation ) {
					return undefined;
				}
 
				implementation = implementation[ Constants.Z_PERSISTENTOBJECT_VALUE ];
				if ( Constants.Z_IMPLEMENTATION_COMPOSITION in implementation ) {
					return Constants.Z_IMPLEMENTATION_COMPOSITION;
				}
				Iif ( Constants.Z_IMPLEMENTATION_BUILT_IN in implementation ) {
					return Constants.Z_IMPLEMENTATION_BUILT_IN;
				}
				return Constants.Z_IMPLEMENTATION_CODE;
			}
			return findImplementationType;
		},
		/**
		 * Returns the language code of an implementation stored
		 * in the global state, given its Zid. If the implementation
		 * is not of type code (but composition or built-in) returns
		 * undefined.
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getLanguageOfImplementation: function ( state ) {
			/**
			 * @param {string} zid
			 * @return {string | undefined}
			 */
			function findImplementationLanguage( zid ) {
				let implementation = state.objects[ zid ];
				Iif ( !implementation ) {
					return undefined;
				}
				implementation = implementation[ Constants.Z_PERSISTENTOBJECT_VALUE ];
				Eif ( Constants.Z_IMPLEMENTATION_CODE in implementation ) {
					// If code is literal: return literal
					if (
						typeUtils.isTruthyOrEqual( implementation, [
							Constants.Z_IMPLEMENTATION_CODE,
							Constants.Z_CODE_LANGUAGE,
							Constants.Z_PROGRAMMING_LANGUAGE_CODE
						] )
					) {
						return implementation[ Constants.Z_IMPLEMENTATION_CODE ][
							Constants.Z_CODE_LANGUAGE ][ Constants.Z_PROGRAMMING_LANGUAGE_CODE ];
					}
					// Else, code is reference: return zid
					return implementation[ Constants.Z_IMPLEMENTATION_CODE ][
						Constants.Z_CODE_LANGUAGE ];
				}
				return undefined;
			}
			return findImplementationLanguage;
		},
		/**
		 * Given a function Zid, it inspects its function definition
		 * stored in the state and returns an array of its arguments.
		 * It returns undefined if the function is not available or the
		 * zid does not belong to a valid function.
		 *
		 * @param {Object} state
		 * @return {Function}
		 */
		getInputsOfFunctionZid: function ( state ) {
			/**
			 * @param {string} zid
			 * @return {Array}
			 */
			function findInputs( zid ) {
				const func = state.objects[ zid ];
				if ( func === undefined ) {
					return [];
				}
				const obj = func[ Constants.Z_PERSISTENTOBJECT_VALUE ];
				if ( obj[ Constants.Z_OBJECT_TYPE ] !== Constants.Z_FUNCTION ) {
					return [];
				}
				// Remove benjamin type item
				return obj[ Constants.Z_FUNCTION_ARGUMENTS ].slice( 1 );
			}
			return findInputs;
		}
	},
	mutations: {
		/**
		 * Set request state for each zid
		 *
		 * @param {Object} state
		 * @param {Object} payload
		 * @param {string} payload.zid
		 * @param {Promise} payload.request
		 */
		setZidRequest: function ( state, payload ) {
			if ( payload.request ) {
				state.requests[ payload.zid ] = payload.request;
			} else {
				delete state.requests[ payload.zid ];
			}
		},
		/**
		 * Add zid info to the state
		 *
		 * @param {Object} state
		 * @param {Object} payload
		 */
		setStoredObject: function ( state, payload ) {
			if ( !( payload.zid in state.objects ) ) {
				state.objects[ payload.zid ] = payload.info;
			}
		},
		/**
		 * Save the LabelData object for a given ID
		 * of a ZPersistentObject, ZKey or ZArgumentDeclaration.
		 *
		 * @param {Object} state
		 * @param {LabelData} labelData
		 */
		setLabel: function ( state, labelData ) {
			state.labels[ labelData.zid ] = labelData;
		}
	},
	actions: {
		/**
		 * Orchestrates the calls to wikilambdaload_zobject api to fetch
		 * a given set of ZIDs. This method takes care of the following requirements:
		 *
		 * * Zids are requested in batches of max 50 items.
		 * * Zids are only requested once.
		 * * Every zid is stored along with their request while it's being fetched.
		 * * Once it's fetched, the request is cleared.
		 * * The returning promise only resolves when all of the batches have returned.
		 *
		 * @param {Object} context
		 * @param {Object} payload
		 * @param {Array} payload.zids array of zids to fetch
		 * @return {Promise}
		 */
		fetchZids: function ( context, payload ) {
			let requestZids = [];
			const allPromises = [];
			const {
				zids = []
			} = payload;
 
			zids.forEach( ( zid ) => {
				// Ignore if:
				// * Zid is Z0
				// * Zid has already been fetched
				if ( zid &&
					( zid !== Constants.NEW_ZID_PLACEHOLDER ) &&
					!( zid in context.state.objects ) &&
					!( zid in context.state.requests )
				) {
					requestZids.push( zid );
				}
				// Capture pending promise to await if:
				// * Zid is waiting to be fetched
				if ( zid in context.state.requests ) {
					allPromises.push( context.state.requests[ zid ] );
				}
			} );
 
			// Keep only unique values
			requestZids = [ ...new Set( requestZids ) ];
 
			// Batch zids in groups of max 50 items
			const batches = [];
			for ( let i = 0; i < requestZids.length; i += Constants.API_REQUEST_ITEMS_LIMIT ) {
				batches.push( requestZids.slice( i, i + Constants.API_REQUEST_ITEMS_LIMIT ) );
			}
 
			// For each batch, generate a Promise
			for ( const batch of batches ) {
				const batchPromise = context.dispatch( 'performFetchZids', { zids: batch } ).then( () => {
					// Once it's back, unset active request
					batch.forEach( ( zid ) => {
						context.commit( 'setZidRequest', { zid, request: null } );
					} );
				} );
				// Set active request
				batch.forEach( ( zid ) => {
					context.commit( 'setZidRequest', { zid, request: batchPromise } );
				} );
				// Collect batch promises
				allPromises.push( batchPromise );
			}
 
			// Return pending and new promises for all the requested zids
			return Promise.all( allPromises );
		},
		/**
		 * Calls the api wikilambdaload_zobjects with a set of Zids and
		 * with or without language property. The language will always be
		 * requested so that the backend takes care of the language ballback
		 * logic. The only moment in wich we will not specify a language
		 * property is when requesting the root ZObject on initialization
		 *
		 * Once received the response, stores the full object in the objects
		 * array and the labels for the Zids, ZKey and ZArgument ids in the
		 * labels store object. The labels returned are already in the
		 * preferred language (or closest fallback available).
		 *
		 * @param {Object} context
		 * @param {Object} payload
		 * @return {Promise}
		 */
		performFetchZids: function ( context, payload ) {
			return new Promise( ( resolve ) => {
				apiUtils.fetchZObjects( {
					zids: payload.zids.join( '|' ),
					language: context.getters.getUserLangCode,
					dependencies: true
				} ).then( ( response ) => {
					const requestedZids = payload.zids;
					const returnedZids = Object.keys( response );
					const dependentZids = [];
 
					returnedZids.forEach( ( zid ) => {
						// If the requested zid returned error, do nothing
						Iif ( !( 'success' in response[ zid ] ) ) {
							return;
						}
 
						// 1. State mutation:
						// Add zObject to the state objects array
						const persistentObject = response[ zid ].data;
						context.commit( 'setStoredObject', {
							zid: zid,
							info: persistentObject
						} );
 
						// 2. State mutation:
						// Add zObject label in user's selected language
						const multiStr = persistentObject[
							Constants.Z_PERSISTENTOBJECT_LABEL
						][ Constants.Z_MULTILINGUALSTRING_VALUE ].slice( 1 );
 
						// The returned multilingual strings will only contain one monolingual string
						// (or none) as they have already been filtered by the back-end to the given
						// language or any of its available fallbacks.
						if ( multiStr.length === 1 ) {
							const labelData = new LabelData(
								zid,
								multiStr[ 0 ][ Constants.Z_MONOLINGUALSTRING_VALUE ],
								multiStr[ 0 ][ Constants.Z_MONOLINGUALSTRING_LANGUAGE ]
							);
							dependentZids.push( multiStr[ 0 ][ Constants.Z_MONOLINGUALSTRING_LANGUAGE ] );
							context.commit( 'setLabel', labelData );
						}
 
						// 3. State mutation:
						// Add the key or argument labels from the selected language to the store
						let objects;
						const objectValue = persistentObject[ Constants.Z_PERSISTENTOBJECT_VALUE ];
						const zType = ( typeof objectValue === 'object' ) ?
							objectValue[ Constants.Z_OBJECT_TYPE ] :
							undefined;
 
						switch ( zType ) {
 
							case Constants.Z_TYPE:
								// If the zObject is a type, get all key labels
								// and commit to the store
								objects = objectValue[ Constants.Z_TYPE_KEYS ].slice( 1 );
 
								objects.forEach( function ( key ) {
									const keyLabels = key[
										Constants.Z_KEY_LABEL
									][ Constants.Z_MULTILINGUALSTRING_VALUE ].slice( 1 );
 
									Eif ( keyLabels.length === 1 ) {
 
										const labelData = new LabelData(
											key[ Constants.Z_KEY_ID ],
											keyLabels[ 0 ][ Constants.Z_MONOLINGUALSTRING_VALUE ],
											keyLabels[ 0 ][ Constants.Z_MONOLINGUALSTRING_LANGUAGE ]
										);
										dependentZids.push( keyLabels[ 0 ][ Constants.Z_MONOLINGUALSTRING_LANGUAGE ] );
										context.commit( 'setLabel', labelData );
									}
								} );
 
								// If the zObject is a type, get all parser and renderer functions
								// and commit to the store
								if ( Constants.Z_TYPE_RENDERER in objectValue ) {
									const renderer = objectValue[ Constants.Z_TYPE_RENDERER ];
									dependentZids.push( renderer );
									context.commit( 'setRenderer', { type: zid, renderer } );
								}
								if ( Constants.Z_TYPE_PARSER in objectValue ) {
									const parser = objectValue[ Constants.Z_TYPE_PARSER ];
									dependentZids.push( parser );
									context.commit( 'setParser', { type: zid, parser } );
								}
								break;
 
							case Constants.Z_FUNCTION:
								// If the zObject is a function, get all argument
								// declaration labels and commit to the store
								objects = objectValue[ Constants.Z_FUNCTION_ARGUMENTS ].slice( 1 );
 
								objects.forEach( function ( arg ) {
									const argLabels = arg[
										Constants.Z_ARGUMENT_LABEL
									][ Constants.Z_MULTILINGUALSTRING_VALUE ].slice( 1 );
 
									Eif ( argLabels.length === 1 ) {
 
										const labelData = new LabelData(
											arg[ Constants.Z_ARGUMENT_KEY ],
											argLabels[ 0 ][ Constants.Z_MONOLINGUALSTRING_VALUE ],
											argLabels[ 0 ][ Constants.Z_MONOLINGUALSTRING_LANGUAGE ]
										);
										dependentZids.push( argLabels[ 0 ][ Constants.Z_MONOLINGUALSTRING_LANGUAGE ] );
										context.commit( 'setLabel', labelData );
									}
								} );
								break;
 
							default:
								// Do nothing
						}
 
						// Make sure that we fetch all languages stored in the labels library
						context.dispatch( 'fetchZids', { zids: [ ...new Set( dependentZids ) ] } );
					} );
 
					// performFetch must resolve to the list of requested zids
					resolve( requestedZids );
				} );
			} );
		}
	}
};