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

90.83% Statements 109/120
86.95% Branches 100/115
94.44% Functions 17/18
90.59% Lines 106/117

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                      40x 40x       40x 40x     686x   686x 153x 153x 21x   132x     533x 533x 532x     1x       74x 122x                                                 1345x   1345x 2x 1343x 159x 1184x 151x 276x   1033x     686x 347x           347x 74x         347x 896x     1343x       235x       2x                       2384x     2384x 1x 2383x 1258x 945x         313x         1125x 320x 553x     805x 805x 2005x   205x 205x   1800x 1x       1x   1799x 34x 34x   1765x 169x 169x   1596x     2383x                         231x   231x 690x   690x 690x               3x                       165x 165x 165x 2596x 165x 165x                                       36x     1x 1x 1x 1x 1x 1x   1x 35x     10x 10x 10x 10x 10x     10x           40x                                       36x 36x 11x   1x 10x   6x   4x   11x   25x                               40x                                       29x 29x 17x   17x   50x   33x       29x     40x                  
/**
 * WikiLambda Vue editor: schemata mixin
 * Mixin with functions to canonicalize and normalize ZObjects.
 * This is distinct from the function-schemata as the UI
 * relies of slightly different requirements for normalization.
 *
 * @copyright 2020– Abstract Wikipedia team; see AUTHORS.txt
 * @license MIT
 */
'use strict';
 
var 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 ) {
	var objectType = zobject[ Constants.Z_OBJECT_TYPE ];
 
	if ( objectType === Constants.Z_STRING ) {
		var Z6 = zobject[ Constants.Z_STRING_VALUE ];
		if ( Z6 && typeof Z6.match === 'function' && Z6.match( referenceRe ) ) {
			return zobject;
		}
		return Z6 || '';
	}
 
	var Z9 = zobject[ Constants.Z_REFERENCE_ID ];
	if ( Z9 && typeof Z9.match === 'function' && Z9.match( referenceRe ) ) {
		return Z9;
	}
 
	return '';
}
 
function filterUndefinedLabels( allLabels ) {
	return allLabels.filter( function ( label ) {
		return label[ Constants.Z_OBJECT_TYPE ] !== Constants.Z_MONOLINGUALSTRING ||
		!!label[ Constants.Z_MONOLINGUALSTRING_VALUE ];
	} );
}
 
function canonicalize( zobject ) {
	function listifyArray( zlist, arr ) {
		var 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( canonicalize( head ) );
		}
 
		if ( tail ) {
			return listifyArray( tail, arr );
		} else {
			return arr;
		}
	}
 
	var 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 canonicalize( element );
		} );
	} else if (
		[ Constants.Z_REFERENCE, Constants.Z_STRING ].includes( zobject[ Constants.Z_OBJECT_TYPE ] )
	) {
		canon = canonicalizeZ6OrZ9( zobject );
	} else Iif ( zobject[ Constants.Z_OBJECT_TYPE ] &&
		zobject[ Constants.Z_OBJECT_TYPE ][ Constants.Z_REFERENCE_ID ] === Constants.Z_TYPED_LIST
	) {
		canon = canonicalize( listifyArray( zobject ) );
	} else {
		// remove any 'undefined' labels
		if ( zobject[ Constants.Z_MULTILINGUALSTRING_VALUE ] ) {
			zobject[ Constants.Z_MULTILINGUALSTRING_VALUE ] = filterUndefinedLabels(
				zobject[ Constants.Z_MULTILINGUALSTRING_VALUE ]
			);
		}
 
		Object.keys( zobject ).forEach( function ( key ) {
			canon[ key ] = canonicalize( 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;
}
 
/**
 * Return the ZObject in semi-normalized form. This means that the strings
 * and references will be normalized, but a canonical list will still be
 * left as a canonical list. This has also been referred to as Hybrid form
 *
 * @param {Object | Array | string} zobject
 * @return {Object|Array|undefined}
 */
function normalize( zobject ) {
	var normal = {},
		keys;
 
	if ( typeof zobject === 'undefined' ) {
		return undefined;
	} else if ( typeof zobject === 'string' ) {
		if ( typeUtils.getZObjectType( zobject ) === Constants.Z_REFERENCE ) {
			normal = {
				Z1K1: Constants.Z_REFERENCE,
				Z9K1: zobject
			};
		} else {
			normal = {
				Z1K1: Constants.Z_STRING,
				Z6K1: zobject
			};
		}
	} else if ( Array.isArray( zobject ) ) {
		normal = zobject.map( function ( element ) {
			return normalize( element );
		} );
	} else {
		keys = Object.keys( zobject );
		for ( var i = 0; i < keys.length; i++ ) {
			if ( keys[ i ] === Constants.Z_OBJECT_TYPE && (
				zobject.Z1K1 === Constants.Z_STRING || zobject.Z1K1 === Constants.Z_REFERENCE ) ) {
				normal.Z1K1 = zobject.Z1K1;
				continue;
			}
			if ( keys[ i ] === Constants.Z_PERSISTENTOBJECT_ID && isString( zobject.Z2K1 ) ) {
				normal.Z2K1 = {
					Z1K1: Constants.Z_STRING,
					Z6K1: zobject.Z2K1
				};
				continue;
			}
			if ( keys[ i ] === Constants.Z_STRING_VALUE && isString( zobject.Z6K1 ) ) {
				normal.Z6K1 = zobject.Z6K1;
				continue;
			}
			if ( keys[ i ] === Constants.Z_REFERENCE_ID && isString( zobject.Z9K1 ) ) {
				normal.Z9K1 = zobject.Z9K1;
				continue;
			}
			normal[ keys[ i ] ] = normalize( zobject[ keys[ i ] ] );
		}
	}
	return normal;
}
 
/**
 * 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 ];
		if ( ( 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 );
	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 ) {
	var 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: {
		canonicalizeZObject: canonicalize,
		normalizeZObject: normalize,
		getValueFromCanonicalZMap: getValueFromCanonicalZMap,
		extractErrorStructure: extractErrorStructure,
		extractZIDs: extractZIDs
	}
};