All files / ext.wikilambda.edit/mixins schemata.js

99.19% Statements 123/124
90.75% Branches 108/119
100% Functions 16/16
99.17% Lines 120/121

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                          42x 42x       42x 42x     1131x   1131x 175x 175x 23x   152x     956x 956x 909x     47x                                   8x 8x   8x 5x     8x 3x     8x 3x   5x       2260x   2260x 2x 2258x 457x 1801x 164x 305x   1637x     1131x 506x                 5x 5x 501x         2x 2x   499x 1420x     2258x       267x       3x                       3345x     3345x 1x 3344x 1834x 1457x         377x         1510x 442x 786x   1068x         2x       2x 2x   1066x 1066x 2697x   222x 222x   2475x 16x       16x   2459x 55x 55x   2404x 165x 165x   2239x     3344x                         4x   4x 4x   4x 4x               4x                       239x   239x 239x 2302x 239x 239x                                       53x     2x 2x 2x 2x 2x 2x   2x 51x     14x 14x 14x 14x 14x     14x           42x                                       53x 53x 16x   2x 14x   6x   8x   16x   37x                               42x                                       45x 45x 28x   28x   75x   47x       45x     42x                  
/**
 * WikiLambda Vue editor: schemata mixin
 * Mixin with functions to convert zobjects between hybrid and canonical forms.
 * Thsse conversions are distinct from canonicalize and normalize of function-schemata; hybrid form
 * meets slightly different representational requirements of the UI layer.
 *
 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
 * @license MIT
 */
'use strict';
 
/* eslint-disable no-implicit-globals */
 
const Constants = require( '../Constants.js' ),
	typeUtils = require( './typeUtils.js' ).methods;
 
// Note: This is intentionally "wrong" in that it allows for Z0.
// It excludes letters so as not to apply to keys (containing a 'K').
const referenceRe = /^Z0*[1-9]*\d*$/;
const errorTypeReferenceRe = /^Z5\d{2}$/;
 
function canonicalizeZ6OrZ9( zobject ) {
	const objectType = zobject[ Constants.Z_OBJECT_TYPE ];
 
	if ( objectType === Constants.Z_STRING ) {
		const Z6 = zobject[ Constants.Z_STRING_VALUE ];
		if ( Z6 && typeof Z6.match === 'function' && Z6.match( referenceRe ) ) {
			return zobject;
		}
		return Z6 || '';
	}
 
	const Z9 = zobject[ Constants.Z_REFERENCE_ID ];
	if ( Z9 && typeof Z9.match === 'function' && Z9.match( referenceRe ) ) {
		return Z9;
	}
 
	return '';
}
 
/**
 * Transform a ZObject from hybrid form to canonical form.  In hybrid form, strings and references are in normal
 * form, but lists are in canonical form. If called on a ZObject already in canonical form, returns the ZObject
 * unchanged.
 *
 * This also handles lists in normal form; this is done defensively, because the orchestrator can still return normal
 * form sometimes (T354917). Normal forms are not handled as thoroughly as function-schemata's canonicalize.
 *
 * @param {Object | Array | string | undefined} zobject
 * @return {Object | Array | string | undefined}
 */
function hybridToCanonical( zobject ) {
	// Given a typed list in normal form, convert its elements to canonical and return them in an array
	// (while ignoring its Z1K1)
	function zlistToArray( zlist, arr ) {
		const head = zlist[ Constants.Z_TYPED_OBJECT_ELEMENT_1 ],
			tail = zlist[ Constants.Z_TYPED_OBJECT_ELEMENT_2 ];
 
		if ( typeof arr === 'undefined' ) {
			arr = [];
		}
 
		if ( head ) {
			arr.push( hybridToCanonical( head ) );
		}
 
		if ( tail ) {
			return zlistToArray( tail, arr );
		} else {
			return arr;
		}
	}
 
	let canon = {};
 
	if ( typeof zobject === 'undefined' ) {
		return undefined;
	} else if ( typeof zobject === 'string' ) {
		canon = zobject;
	} else if ( Array.isArray( zobject ) ) {
		canon = zobject.map( function ( element ) {
			return hybridToCanonical( element );
		} );
	} else if (
		[ Constants.Z_REFERENCE, Constants.Z_STRING ].includes( zobject[ Constants.Z_OBJECT_TYPE ] )
	) {
		canon = canonicalizeZ6OrZ9( zobject );
	} else if (
		// Allow for typed lists in normal form, where the list's Z_OBJECT_TYPE is a function call.
		// See also the header comments for this function.
		typeUtils.isTruthyOrEqual( zobject, [
			Constants.Z_OBJECT_TYPE,
			Constants.Z_FUNCTION_CALL_FUNCTION,
			Constants.Z_REFERENCE_ID
		], Constants.Z_TYPED_LIST )
	) {
		const itemType = zobject[ Constants.Z_OBJECT_TYPE ][ Constants.Z_TYPED_LIST_TYPE ];
		canon = [ hybridToCanonical( itemType ), ...hybridToCanonical( zlistToArray( zobject ) ) ];
	} else if ( zobject[ Constants.Z_OBJECT_TYPE ] &&
		// Accommodate both hybrid form and canonical
		( zobject[ Constants.Z_OBJECT_TYPE ][ Constants.Z_REFERENCE_ID ] === Constants.Z_QUOTE ||
			zobject[ Constants.Z_OBJECT_TYPE ] === Constants.Z_QUOTE )
	) {
		canon[ Constants.Z_OBJECT_TYPE ] = Constants.Z_QUOTE;
		canon[ Constants.Z_QUOTE_VALUE ] = zobject[ Constants.Z_QUOTE_VALUE ];
	} else {
		Object.keys( zobject ).forEach( function ( key ) {
			canon[ key ] = hybridToCanonical( zobject[ key ] );
		} );
	}
	return canon;
}
 
function isString( s ) {
	return typeof s === 'string' || s instanceof String;
}
 
function isZid( k ) {
	return k.match( /^Z[1-9]\d*$/ ) !== null;
}
 
/**
 * Transform a ZObject from canonical form to hybrid form.  In hybrid form, strings and references are in normal
 * form, but lists remain in canonical form. If called on a ZObject already in hybrid form, returns the ZObject
 * unchanged.
 *
 * @param {Object | Array | string} zobject
 * @return {Object|Array|undefined}
 */
function canonicalToHybrid( zobject ) {
	let hybrid = {},
		keys;
 
	if ( typeof zobject === 'undefined' ) {
		return undefined;
	} else if ( typeof zobject === 'string' ) {
		if ( typeUtils.getZObjectType( zobject ) === Constants.Z_REFERENCE ) {
			hybrid = {
				Z1K1: Constants.Z_REFERENCE,
				Z9K1: zobject
			};
		} else {
			hybrid = {
				Z1K1: Constants.Z_STRING,
				Z6K1: zobject
			};
		}
	} else if ( Array.isArray( zobject ) ) {
		hybrid = zobject.map( function ( element ) {
			return canonicalToHybrid( element );
		} );
	} else if ( zobject[ Constants.Z_OBJECT_TYPE ] &&
		// Accommodate both hybrid form and canonical
		( zobject[ Constants.Z_OBJECT_TYPE ][ Constants.Z_REFERENCE_ID ] === Constants.Z_QUOTE ||
			zobject[ Constants.Z_OBJECT_TYPE ] === Constants.Z_QUOTE )
	) {
		const normalType = {
			Z1K1: Constants.Z_REFERENCE,
			Z9K1: Constants.Z_QUOTE
		};
		hybrid[ Constants.Z_OBJECT_TYPE ] = normalType;
		hybrid[ Constants.Z_QUOTE_VALUE ] = zobject[ Constants.Z_QUOTE_VALUE ];
	} else {
		keys = Object.keys( zobject );
		for ( let i = 0; i < keys.length; i++ ) {
			if ( keys[ i ] === Constants.Z_OBJECT_TYPE && (
				zobject.Z1K1 === Constants.Z_STRING || zobject.Z1K1 === Constants.Z_REFERENCE ) ) {
				hybrid.Z1K1 = zobject.Z1K1;
				continue;
			}
			if ( keys[ i ] === Constants.Z_PERSISTENTOBJECT_ID && isString( zobject.Z2K1 ) ) {
				hybrid.Z2K1 = {
					Z1K1: Constants.Z_STRING,
					Z6K1: zobject.Z2K1
				};
				continue;
			}
			if ( keys[ i ] === Constants.Z_STRING_VALUE && isString( zobject.Z6K1 ) ) {
				hybrid.Z6K1 = zobject.Z6K1;
				continue;
			}
			if ( keys[ i ] === Constants.Z_REFERENCE_ID && isString( zobject.Z9K1 ) ) {
				hybrid.Z9K1 = zobject.Z9K1;
				continue;
			}
			hybrid[ keys[ i ] ] = canonicalToHybrid( zobject[ keys[ i ] ] );
		}
	}
	return hybrid;
}
 
/**
 * Return the ZMap value corresponding to the given key, if present.
 * TODO (T302015) When ZMap keys are extended beyond Z6/Z39, update accordingly
 *
 * @param {Object} zMap a Z883/Typed map, in canonical form
 * @param {Object} key a Z6 or Z39 instance, in canonical form
 * @return {Object|undefined} a Z1/Object, the value of the map entry with the given key,
 * or undefined if there is no such entry
 */
function getValueFromCanonicalZMap( zMap, key ) {
	const K1Array = zMap[ Constants.Z_TYPED_OBJECT_ELEMENT_1 ];
	// Ignore first item in the canonical form array; this is a string representing the type
	for ( let i = 1; i < K1Array.length; i++ ) {
		const entry = K1Array[ i ];
		// To accommodate our current programming practices, we need to allow for either key here:
		const currentKey = entry[ Constants.Z_TYPED_OBJECT_ELEMENT_1 ] || entry[ Constants.Z_TYPED_PAIR_TYPE1 ];
		Eif ( ( currentKey === key ) ||
			( currentKey[ Constants.Z_OBJECT_TYPE ] === Constants.Z_STRING &&
				key[ Constants.Z_OBJECT_TYPE ] === Constants.Z_STRING &&
				currentKey[ Constants.Z_STRING_VALUE ] === key[ Constants.Z_STRING_VALUE ] ) ||
			( currentKey[ Constants.Z_OBJECT_TYPE ] === Constants.Z_KEY_REFERENCE &&
				key[ Constants.Z_OBJECT_TYPE ] === Constants.Z_KEY_REFERENCE &&
				currentKey[ Constants.Z_KEY_REFERENCE_ID ] === key[ Constants.Z_KEY_REFERENCE_ID ] ) ) {
			// To accommodate our current programming practices, we need to allow for either key here:
			return entry[ Constants.Z_TYPED_OBJECT_ELEMENT_2 ] || entry[ Constants.Z_TYPED_PAIR_TYPE2 ];
		}
	}
}
 
/**
 * Finds all of the ZIDs appearing in an arbitrary ZObject.
 *
 * @param {Object|string} zobject a Z1/Object
 * @return {Set} Set of (string) ZIDs
 */
function extractZIDs( zobject ) {
	const str = JSON.stringify( zobject );
	// eslint-disable-next-line security/detect-unsafe-regex
	const regexp = /"(Z[1-9]\d*)(K[1-9]\d*)?"/g;
	const matches = [ ...str.matchAll( regexp ) ];
	const allZids = matches.map( ( groups ) => groups[ 1 ] );
	const uniqueZids = [ ...new Set( allZids ) ];
	return uniqueZids;
}
 
/**
 * Checks if a given zobject is a suberror (a zobject whose type is an instance of Z50/'Error type').
 * If so, returns a JS object with keys errorType and (optionally) explanation.  If not, returns null.
 *
 * The 'explanation' is an explanatory string for this suberror.
 * Such strings are expected for Z500, but are also generated in the orchestrator for
 * some other error types. In addition to explanatory strings, a few other useful keys
 * with string values will show up here, e.g. Z503K1/'feature name' and Z504K1/ZID.
 *
 * Allows for the more relaxed Z5/Error format from the orchestrator, in which the suberror's
 * type appears directly as the value of Z1K1/type, and also the stricter format, in which
 * it appears in a function call to Z885/'Errortype to type'.  Z885K1 is the 'errortype' key of Z885.
 *
 * @param {Object} zobject
 * @return {Array} of objects
 */
function checkIfSuberror( zobject ) {
	if ( typeof zobject === 'object' && zobject.Z1K1 && typeof zobject.Z1K1 === 'string' &&
		zobject.Z1K1.match( errorTypeReferenceRe ) ) {
		// Handle the relaxed Z5/Error format from the orchestrator
		const suberror = {};
		suberror.errorType = zobject.Z1K1;
		const stringKey = suberror.errorType + 'K1';
		const k1String = zobject[ stringKey ];
		Eif ( k1String && isString( k1String ) && !isZid( k1String ) ) {
			suberror.explanation = k1String;
		}
		return suberror;
	} else if ( typeof zobject === 'object' && zobject.Z1K1 && typeof zobject.Z1K1 === 'object' &&
		zobject.Z1K1.Z885K1 && typeof zobject.Z1K1.Z885K1 === 'string' &&
		zobject.Z1K1.Z885K1.match( errorTypeReferenceRe ) ) {
		const suberror = {};
		suberror.errorType = zobject.Z1K1.Z885K1;
		const stringKey = 'K1';
		const k1String = zobject[ stringKey ];
		Iif ( k1String && isString( k1String ) && !isZid( k1String ) ) {
			suberror.explanation = k1String;
		}
		return suberror;
	}
}
 
// These error types have no keys whose values contain nested error content.  If a error type ZID
// appears here, extractErrorStructure will not search through any children of a zobject of that type.
const errorTypesNotToTraverse = new Set( [ 'Z501', 'Z505', 'Z508', 'Z511', 'Z512', 'Z513', 'Z516',
	'Z531', 'Z532', 'Z533', 'Z534', 'Z535', 'Z536', 'Z537', 'Z542', 'Z547', 'Z548', 'Z551', 'Z553' ] );
 
/**
 * Traverses a ZObject to find all the suberrors.  (A suberror is a zobject
 * whose type is an instance of Z50/'Error type'). Example:
 *   { Z1K1: 'Z500', Z500K1: 'Could not find argument Z811K1' }
 * For each suberror found, the result includes a JS object with properties
 * 'errorType', 'children', and (optionally) 'explanation'.  Example:
 *   { errorType: 'Z500', explanation: 'Could not find argument Z811K1', children: [] }
 *
 * The 'children', if any, are additional suberrors found within the nested ZObjects of
 * this suberror.
 *
 * zobject is normally a Z5 in the top level call, but doesn't have to be.
 *
 * @param {Object} zobject
 * @return {Array} of objects
 */
function extractErrorStructure( zobject ) {
	const subError = checkIfSuberror( zobject );
	if ( subError ) {
		if ( subError.explanation ) {
			// In this special case, there won't be any nested suberrors; look no further
			subError.children = [];
		} else if ( errorTypesNotToTraverse.has( subError.errorType ) ) {
			// Also in this case, there won't be any nested suberrors; look no further
			subError.children = [];
		} else {
			subError.children = extractNestedSuberrors( zobject, subError.errorType );
		}
		return [ subError ];
	}
	return extractNestedSuberrors( zobject, null );
}
 
/**
 * For each suberror type, these are its keys whose values should be included
 * in the traversal conducted by extractNestedSuberrors(), because
 * they may contain nested error content.  We include both local and global
 * forms of the keys, to make sure all currently generated errors are covered.
 *
 * If a suberror type isn't listed here, *all* of its keys' values will be traversed.
 * It is not necessary for each suberror type to appear here, but if one does,
 * it should *not* appear in errorTypesNotToTraverse.
 *
 * New error types will be handled without updating this map or errorTypesNotToTraverse
 * (albeit not necessarily optimally).
 */
const errorKeysToTraverse = new Map( [
	[ 'Z502', new Set( [ 'Z502K2', 'K2' ] ) ], // Not wellformed, [value]
	[ 'Z506', new Set( [ 'Z506K4', 'K4' ] ) ], // Argument type mismatch, [propagated error]
	[ 'Z507', new Set( [ 'Z507K2', 'K2' ] ) ], // Error in evaluation, [propagated error]
	[ 'Z517', new Set( [ 'Z517K4', 'K4' ] ) ], // Return type mismatch, [propagated error]
	[ 'Z518', new Set( [ 'Z518K3', 'K3' ] ) ] // Object type mismatch, [propagated error]
] );
 
/**
 * Finds all suberrors in the children objects of the given zobject, as described for
 * extractErrorStructure().  In that function we check whether the top-level
 * object is a suberror; here we look at the children objects.
 *
 * Special-purpose function; only meant to be called from extractErrorStructure().
 *
 * @param {Object} zobject
 * @param {string|null} errorType
 * @return {Array} of objects
 */
function extractNestedSuberrors( zobject, errorType ) {
	const nested = [];
	if ( zobject !== null && typeof zobject === 'object' ) {
		const keysToTraverse = errorKeysToTraverse.get( errorType );
		// eslint-disable-next-line es-x/no-object-entries
		Object.entries( zobject ).forEach( ( [ key, value ] ) => {
			// We've already looked inside Z1K1/type; no need to look again
			if ( key !== Constants.Z_OBJECT_TYPE &&
				( keysToTraverse === undefined || keysToTraverse.has( key ) ) ) {
				nested.push( ...extractErrorStructure( value ) );
			}
		} );
	}
	return nested;
}
 
module.exports = exports = {
	methods: {
		hybridToCanonical: hybridToCanonical,
		canonicalToHybrid: canonicalToHybrid,
		getValueFromCanonicalZMap: getValueFromCanonicalZMap,
		extractErrorStructure: extractErrorStructure,
		extractZIDs: extractZIDs
	}
};