All files utils.js

97.81% Statements 403/412
92.51% Branches 235/254
100% Functions 101/101
97.79% Lines 400/409

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 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441                                  2320x 7x   2313x 4813x 1368x     945x       199x       54x 4x   54x 17x   37x       4x       51x       759x       6x       39x       844x 283x   561x       65x 17x   48x                   295x 118x   177x 177x 174x   3x                     17x 1x   16x 7x   9x       13x 5x   8x                     61x 4x   57x 35x   22x                             346x   201x   145x   88x     57x                             78x 44x   34x 29x 29x 28x   1x 1x       5x                     17x 1x   16x 7x   9x                       195x         535x 177x     18x       263289x       73342x       70807x         77x       258096x                       58x       755x       58x       9x               58x               58x               58x               58x               58x       1x 1x 1x       34x 34x 34x 34x 104x 70x   104x 104x 104x 28x   104x 104x 104x   33x       1x 1x               2x               22x 22x 2x   20x         20x             3x         1x       1x             98x       4x       8x     8x 8x 8x 16x 16x 16x   8x       70x 70x 70x       70x 15x 15x   55x 47x 47x   8x 8x 8x                   69x 1x     68x 21x 21x   47x 1x 1x   46x 2x 2x   44x 5x 5x   39x 1x 1x   38x 31x 31x   7x 4x 4x     3x                                                                                                                   41x 41x 345x 552x     41x 40x                             18x 4x     4x 4x 3x     1x   14x 14x 14x   4x 4x 4x     6x 6x 6x 3x                 1x 10x   8x     2x         57x 4x 4x 4x   4x         4x   53x 9x 9x 9x 9x 24x 24x 24x   9x         9x         44x       18x                             26x 36x 36x 13x     26x                         187x 4x   183x                       39x 8x       31x 31x     5x   26x                       25x 10x               15x 15x     1x   14x                 1x                 1x                   294x                   94x                   2x                     188x                       59x 1x     58x 58x 58x   144x 58x   86x 86x   58x                           1809x   1076x 1076x 1076x 733x 733x 733x   1076x                       9x 9x 14x 14x 10x   14x       9x 9x 4x   5x     9x                     4x 4x                       117x 117x                       1076x 1076x                     1082x                     1082x 957x   125x 118x       7x       1082x                             18x 18x 1x   17x               17x                   17x                       5x                                   70x 70x   70x                       70x 70x 70x 52x   18x 18x 14x   4x       20x 17x   3x 3x                                       23x 1x     22x 22x 22x 24x 19x   5x 5x 5x 3x 3x   2x 2x       19x 19x 19x 19x 19x           19x                     19x 1x     19x 17x   2x                                 23x 2x   21x 7x     14x 14x 20x 5x   15x   15x 9x   6x   5x                           7x 7x 8x 8x     4x     3x                             175x 8x 8x 8x 8x   167x     175x 2x   173x         175x                           55x     55x 55x   7x 1x 1x   6x 6x   7x 7x 2x   7x   48x                           3x                             6x 3x   6x 6x 3x 3x   6x       1x 2x       1x             1x     1x       169x       40x       1262x 5x 1x   4x   1257x 1x   1256x       72553x             1493911x             72453x             128207x                 101x 101x 101x   100x           99x       101x 99x   101x               1x 1x       100x   100x 1x 1x     99x 99x 99x       100x 100x         1x                                                                                                                                        
'use strict';
 
// NOTE: This file is used in a MediaWiki context as well, and so MUST parse as a
// stand-alone JS file without use of require().
//
// DO NOT modify javascript/src/utils.js directly.
// Modify javascript/shared/es6UtilsModule.js, then
// regenerate javascript/src/utils.js with
//
//      $ npm run run-rollup
 
/**
 * A wrapper for normal-from ZObjects, for use in the function orchestrator.
 */
class ZWrapperBase {}
 
function checkTypeShallowly( ZObject, keys ) {
	if ( ZObject === null || ZObject === undefined ) {
		return false;
	}
	for ( const key of keys ) {
		if ( ZObject[ key ] === undefined ) {
			return false;
		}
	}
	return true;
}
 
function isZArgumentReference( ZObject ) {
	return checkTypeShallowly( ZObject, [ 'Z1K1', 'Z18K1' ] );
}
 
function isZBoolean( ZObject ) {
	while ( checkTypeShallowly( ZObject, [ 'Z1K1', 'Z40K1' ] ) ) {
		ZObject = ZObject.Z40K1;
	}
	if ( !isZReference( ZObject ) ) {
		return false;
	}
	return ( ZObject.Z9K1 === 'Z41' || ZObject.Z9K1 === 'Z42' );
}
 
function isZEnvelope( ZObject ) {
	return checkTypeShallowly( ZObject, [ 'Z1K1', 'Z22K1', 'Z22K2' ] );
}
 
function isZFunction( ZObject ) {
	return checkTypeShallowly( ZObject, [ 'Z1K1', 'Z8K1', 'Z8K2', 'Z8K3', 'Z8K4', 'Z8K5' ] );
}
 
function isZFunctionCall( ZObject ) {
	return checkTypeShallowly( ZObject, [ 'Z1K1', 'Z7K1' ] );
}
 
function isZKeyReference( ZObject ) {
	return checkTypeShallowly( ZObject, [ 'Z1K1', 'Z39K1' ] );
}
 
function isZQuote( ZObject ) {
	return checkTypeShallowly( ZObject, [ 'Z1K1', 'Z99K1' ] );
}
 
function isZReference( ZObject ) {
	if ( !checkTypeShallowly( ZObject, [ 'Z1K1', 'Z9K1' ] ) ) {
		return false;
	}
	return ZObject.Z1K1 === 'Z9' && ZObject.Z9K1.match( /^Z[1-9]\d*$/ ) !== null;
}
 
function isZString( ZObject ) {
	if ( !checkTypeShallowly( ZObject, [ 'Z1K1', 'Z6K1' ] ) ) {
		return false;
	}
	return ZObject.Z1K1 === 'Z6' && isString( ZObject.Z6K1 );
}
 
/**
 * Checks if given ZObject is a Z4 literal
 *
 * @param {Object} ZObject
 * @return {boolean} true || false
 */
function isZType( ZObject ) {
	if ( !checkTypeShallowly( ZObject, [ 'Z1K1', 'Z4K1', 'Z4K2', 'Z4K3' ] ) ) {
		return false;
	}
	const identity = ZObject.Z4K1;
	if ( isMemberOfDangerTrio( identity ) || isZType( identity ) ) {
		return true;
	}
	return false;
}
 
/**
 * Finds the Z9/Reference identity of a Z46/Type converter to code. If the identity is
 * not eventually given as a Z9/Reference, returns null.
 *
 * @param {Object} Z46 a Type converter from code
 * @return {Object|null} the Z46's Z9/Reference identity
 */
function findTypeConverterToCodeIdentity( Z46 ) {
	if ( Z46 === undefined ) {
		return null;
	}
	if ( isZReference( Z46 ) ) {
		return Z46;
	}
	return findTypeConverterToCodeIdentity( Z46.Z46K1 );
}
 
function findBooleanIdentity( Z40 ) {
	if ( Z40.Z40K1 === undefined ) {
		return Z40;
	}
	return findBooleanIdentity( Z40.Z40K1 );
}
 
/**
 * Finds the Z9/Reference identity of a Z8/Function. If the identity is
 * not eventually given as a Z9/Reference, returns null.
 *
 * @param {Object} Z8 a Function
 * @return {Object|null} the Z8's Z9/Reference identity
 */
function findFunctionIdentity( Z8 ) {
	if ( Z8 === undefined ) {
		return null;
	}
	if ( isZReference( Z8 ) ) {
		return Z8;
	}
	return findFunctionIdentity( Z8.Z8K5 );
}
 
/**
 * Finds the identity of a type.
 * This might be a Function Call (in the case of * a generic type)
 * or a Reference.
 * In any case, this function will return the most nested possible identity,
 * so, if Z4K1 points to a Z4, the function will recurse.
 *
 * @param {Object} Z4 a Type
 * @return {Object|null} the Z4's identity;
 * (for when we only want an identity (e.g., to build ZObject keys))
 */
function findTypeIdentity( Z4 ) {
	if ( isZFunctionCall( Z4 ) || isZReference( Z4 ) ) {
		// Identity can be a function call or reference.
		return Z4;
	}
	if ( isZType( Z4 ) ) {
		// Otherwise, recurse..
		return findTypeIdentity( Z4.Z4K1 );
	}
	// Not a valid identity for a Type.
	return null;
}
 
/**
 * Finds the definition of given type.
 * If a type's Z4K1/Identity is given as a Z4, this function will recurse
 * until it finds the lowest-nested Z4 whose Identity is not a Z4.
 * There is one special case: if this function is called with a Z9/Reference
 * that points to a built-in Type, it is acceptable for it to return
 * that Z9.
 *
 * @param {Object} Z4 a Type
 * @return {Object|null} the complete Z4 or Z9 if called with a built-in reference
 */
function findTypeDefinition( Z4 ) {
	if ( isZReference( Z4 ) && isBuiltInType( Z4.Z9K1 ) ) {
		return Z4;
	}
	if ( isZType( Z4 ) ) {
		const identity = Z4.Z4K1;
		if ( isZFunctionCall( identity ) || isZReference( identity ) ) {
			return Z4;
		}
		Eif ( isZType( identity ) ) {
			return findTypeDefinition( identity );
		}
	}
	// Not a valid definition for a Type.
	return null;
}
 
/**
 * Finds the Z9/Reference identity of a Z64/Type converter from code. If the identity is
 * not eventually given as a Z9/Reference, returns null.
 *
 * @param {Object} Z64 a Type converter from code
 * @return {Object|null} the Z46's Z9/Reference identity
 */
function findTypeConverterFromCodeIdentity( Z64 ) {
	if ( Z64 === undefined ) {
		return null;
	}
	if ( isZReference( Z64 ) ) {
		return Z64;
	}
	return findTypeConverterFromCodeIdentity( Z64.Z64K1 );
}
 
/**
 * Type-checks Z1 against Function Call, Reference, and Argument Reference.
 * Returns the true if Z1 can plausibly be interpreted as belonging to one of
 * those three types, else false.
 *
 * @param {Object} Z1 object to be validated
 * @return {boolean} whether Z1's type is any of the Danger Trio
 */
function isMemberOfDangerTrio( Z1 ) {
	for ( const typeComparisonFunction of [
		isZArgumentReference,
		isZFunctionCall,
		isZReference
	] ) {
		if ( typeComparisonFunction( Z1 ) ) {
			return true;
		}
	}
	return false;
}
 
function isString( s ) {
	return typeof s === 'string' || s instanceof String;
}
 
function isArray( a ) {
	return Array.isArray( a );
}
 
function isObject( o ) {
	return !isArray( o ) && typeof o === 'object' && o !== null;
}
 
function isKey( k ) {
	// eslint-disable-next-line security/detect-unsafe-regex
	return k.match( /^(Z[1-9]\d*)?K[1-9]\d*$/ ) !== null;
}
 
function isZid( k ) {
	return k.match( /^Z[1-9]\d*$/ ) !== null;
}
 
/**
 * Uses of isReference have been changed to isZObjectReference, per T373852,
 * but we are keeping it for a possible future revival.
 *
 * @param {string} z
 * @return {boolean} Whether the string is lexically valid as a reference
 */
function isReference( z ) {
	// Note that A1 and Q34 are References but K2 isn't.
	return z.match( /^[A-JL-Z][1-9]\d*$/ ) !== null;
}
 
function isZObjectReference( z ) {
	return z.match( /^Z[1-9]\d*$/ ) !== null;
}
 
function isGlobalKey( k ) {
	return k.match( /^Z[1-9]\d*K[1-9]\d*$/ ) !== null;
}
 
function kidFromGlobalKey( k ) {
	return k.match( /^Z[1-9]\d*(K[1-9]\d*)$/ )[ 1 ];
}
 
/**
 * @param {string} s
 * @return {boolean} Whether the string is syntactically valid as a Wikidata Item identifier
 */
function isItemId( s ) {
	return s.match( /^Q[1-9]\d*$/ ) !== null;
}
 
/**
 * @param {string} s
 * @return {boolean} Whether the string is syntactically valid as a Wikidata Property identifier
 */
function isPropertyId( s ) {
	return s.match( /^P[1-9]\d*$/ ) !== null;
}
 
/**
 * @param {string} s
 * @return {boolean} Whether the string is syntactically valid as a Wikidata Lexeme identifier
 */
function isLexemeId( s ) {
	return s.match( /^L[1-9]\d*$/ ) !== null;
}
 
/**
 * @param {string} s
 * @return {boolean} Whether the string is syntactically valid as a Wikidata Lexeme form identifier
 */
function isLexemeFormId( s ) {
	return s.match( /^L[1-9]\d*-F[1-9]\d*$/ ) !== null;
}
 
/**
 * @param {string} s
 * @return {boolean} Whether the string is syntactically valid as a Wikidata Lexeme sense identifier
 */
function isLexemeSenseId( s ) {
	return s.match( /^L[1-9]\d*-S[1-9]\d*$/ ) !== null;
}
 
function createErrorWithZObjectPayload( errorMessage, payload ) {
	const responseError = new Error( errorMessage );
	responseError.errorZObjectPayload = payload;
	return responseError;
}
 
function accumulateKeyGeneralWithHints( zObject, accumulate, hintMap ) {
	const keys = Object.keys( zObject );
	keys.sort();
	accumulate( ':' );
	for ( let i = 0; i < keys.length; ++i ) {
		if ( i > 0 ) {
			accumulate( ',' );
		}
		const key = keys[ i ];
		let accumulateKey = hintMap.get( key );
		if ( accumulateKey === undefined ) {
			accumulateKey = accumulateZObjectKeyForNormalized;
		}
		const value = zObject[ key ];
		accumulate( key, '|' );
		accumulateKey( value, accumulate );
	}
	accumulate( ',,' );
}
 
function accumulateKeyForBoolean( zBoolean, accumulate ) {
	const identity = findBooleanIdentity( zBoolean );
	accumulate( 'Z40K1|', identity.Z9K1 );
}
 
// FIXME: Instead of dontAccumulate, use `null` and also omit keys?
function dontAccumulate() {}
 
function accumulateKeyForFunctionLiteral( zFunction, accumulate ) {
	// Create a key for a general object using only the function signature.
	accumulateKeyGeneralWithHints( zFunction, accumulate, new Map( [
		[ 'Z1K1', accumulateKeyForType ],
		[ 'Z8K3', dontAccumulate ],
		[ 'Z8K4', dontAccumulate ],
		[ 'Z8K5', dontAccumulate ] ] ) );
}
 
function accumulateKeyForFunction( zFunction, accumulate ) {
	const identity = findFunctionIdentity( zFunction );
	if ( identity === null ) {
		accumulateKeyForFunctionLiteral( zFunction, accumulate );
	} else {
		accumulateKeyForReference( identity, accumulate );
	}
}
 
function accumulateKeyForFunctionCall( zFunctionCall, accumulate ) {
	accumulateKeyGeneralWithHints(
		zFunctionCall, accumulate, new Map( [
			[ 'Z1K1', accumulateKeyForType ],
			[ 'Z7K1', accumulateKeyForFunction ] ] ) );
}
 
function accumulateKeyForObject( zObject, accumulate ) {
	accumulateKeyGeneralWithHints(
		zObject, accumulate, new Map( [ [ 'Z1K1', accumulateKeyForType ] ] ) );
}
 
function accumulateJSON( zQuotedMaterial, accumulate ) {
	accumulate( stableStringify( zQuotedMaterial ) );
}
 
function accumulateKeyForQuote( zQuote, accumulate ) {
	accumulateKeyGeneralWithHints(
		zQuote, accumulate, new Map( [
			[ 'Z1K1', accumulateKeyForType ],
			[ 'Z99K1', accumulateJSON ] ] ) );
}
 
function accumulateKeyForReference( zReference, accumulate ) {
	accumulate( 'Z9K1|', zReference.Z9K1 );
}
 
function accumulateKeyForString( zString, accumulate ) {
	accumulate( 'Z6K1|', zString.Z6K1 );
}
 
function accumulateKeyForLiteralType( zType, accumulate ) {
	const intermediateObject = {
		Z1K1: { Z1K1: 'Z9', Z9K1: 'Z4' }
	};
	const hintMap = new Map();
	hintMap.set( 'Z1K1', accumulateKeyForType );
	for ( const Z3 of convertZListToItemArray( zType.Z4K2 || [] ) ) {
		const key = Z3.Z3K2.Z6K1;
		intermediateObject[ key ] = Z3.Z3K1;
		hintMap.set( key, accumulateKeyForType );
	}
	accumulateKeyGeneralWithHints( intermediateObject, accumulate, hintMap );
}
 
function accumulateKeyForType( zType, accumulate ) {
	const identity = findTypeIdentity( zType );
	const typeDefinition = findTypeDefinition( zType );
	Iif ( identity === null ) {
		throw createErrorWithZObjectPayload(
			'Invalid ZObject input for type', zType );
	}
	if ( isZFunctionCall( identity ) ) {
		accumulateKeyForFunctionCall( identity, accumulate );
		return;
	}
	if ( isZReference( identity ) && isBuiltInType( identity.Z9K1 ) ) {
		accumulateKeyForReference( identity, accumulate );
		return;
	}
	Eif ( isZType( typeDefinition ) ) {
		accumulateKeyForLiteralType( typeDefinition, accumulate );
		return;
	}
	if ( isZReference( identity ) ) {
		accumulateKeyForReference( identity, accumulate );
		return;
	}
	throw createErrorWithZObjectPayload( 'Invalid identity for Type', identity );
}
 
function accumulateZObjectKeyForNormalized( normalized, accumulate ) {
	if ( !isObject( normalized ) ) {
		throw createErrorWithZObjectPayload(
			'Invalid ZObject input', wrapInQuote( normalized ) );
	}
	if ( isZType( normalized ) ) {
		accumulateKeyForType( normalized, accumulate );
		return;
	}
	if ( isZBoolean( normalized ) ) {
		accumulateKeyForBoolean( normalized, accumulate );
		return;
	}
	if ( isZFunction( normalized ) ) {
		accumulateKeyForFunction( normalized, accumulate );
		return;
	}
	if ( isZFunctionCall( normalized ) ) {
		accumulateKeyForFunctionCall( normalized, accumulate );
		return;
	}
	if ( isZQuote( normalized ) ) {
		accumulateKeyForQuote( normalized, accumulate );
		return;
	}
	if ( isZReference( normalized ) ) {
		accumulateKeyForReference( normalized, accumulate );
		return;
	}
	if ( isZString( normalized ) ) {
		accumulateKeyForString( normalized, accumulate );
		return;
	}
	// ZObject isn't a type, so create a ZObjectKey.
	accumulateKeyForObject( normalized, accumulate );
}
 
/**
 * Generate a unique identifier for a Z4/Type (or any ZObject).
 *
 * FIXME: UPDATE THIS TO REFLECT NEW FORMAT
 *
 * If the type is built-in, its unique identifier will simply be its ZID.
 *
 * If the type is ultimately defined by a generic Z8/Function, the unique
 * identifier will consist of the ZID of the Function, followed by the unique
 * idenifiers of its arguments (enclosed in parentheses, comma-separated), e.g.
 *
 *  {
 *      Z1K1: Z7,
 *      Z7K1: Z831,
 *      Z831K1: Z6,
 *      Z831K2: Z40
 *  }
 *  ( a.k.a. Pair( String, Boolean ) )
 *
 * produces a key like
 *
 *  "Z831(Z6,Z40)"
 *
 * If the type is user-defined, the unique identifier will be the keys IDs and unique
 * identifiers of the type's attributes (enclosed in angle brackets, comma-
 * separated), e.g.
 *
 *  {
 *      ...
 *      Z4K2: [
 *          { Z3K1: Z40, Z3K2: Z123K1 },
 *          { Z3K1: Z6,  Z3K2: Z123K2 },
 *          { Z3K1: Z86, Z3K2: Z123K3 }
 *      ]
 * }
 *
 * produces a key like
 *
 *  "<Z123K1:Z40,Z123K2:Z6,Z123K3:Z86>"
 *
 * Otherwise, if the object is not a type, the unique identifier will be
 * the unique identifier of the object's type specification (Z1K1), then
 * a stable string representation of JSON corresponding to the remaining
 * key-value pairs in the object (enclosed by braces). So the unique
 * identifier of a ZString (Z6) corresponding to "vittles" will look like
 *
 *  "Z6{Z6K1:vittles}"
 *
 * @param {Object} ZObject a ZObject
 * @return {Object} (Simple|Generic|UserDefined)TypeKey or ZObjectKey
 * @throws {Error} If input is not a valid ZObject.
 */
function createZObjectKey( ZObject ) {
	// FIXME: Give normalize the same treatment--should have an ES6 part
	// and a CommonJS wrapper.
	const zObjectKeyParts = [];
	const accumulate = ( ...parts ) => {
		for ( const part of parts ) {
			zObjectKeyParts.push( part );
		}
	};
	accumulateZObjectKeyForNormalized( ZObject, accumulate );
	return zObjectKeyParts.join( '' );
}
 
/**
 * Recursively checks that two objects are equal. This function will work well
 * for anything that can be represented in pure JSON: Objects, Arrays, strings,
 * numbers, null, and even undefined. This function may not work with container
 * types such as Maps or Sets.
 *
 * @param {Object} o1 first object to be compared
 * @param {Object} o2 second object to be compared
 * @return {boolean} whether the two objects are equal
 */
function deepEqual( o1, o2 ) {
	// First, consider the case that both are arrays.
	if ( isArray( o1 ) && isArray( o2 ) ) {
		Iif ( o1.length !== o2.length ) {
			return false;
		}
		for ( let i = 0; i < o1.length; ++i ) {
			if ( !deepEqual( o1[ i ], o2[ i ] ) ) {
				return false;
			}
		}
		return true;
	}
	const isObject1 = isObject( o1 );
	const isObject2 = isObject( o2 );
	if ( isObject1 && isObject2 ) {
		// Both input objects are of type Object; compare recursively.
		const o1Keys = Object.keys( o1 );
		const o2Keys = new Set( Object.keys( o2 ) );
		for ( const key of o1Keys ) {
			// Both objects have the key, so we do recursive comparison and
			// remove the key from the o2Keys set.
			Eif ( o2Keys.has( key ) ) {
				o2Keys.delete( key );
				if ( !deepEqual( o1[ key ], o2[ key ] ) ) {
					return false;
				}
			} else {
				// o1 has a key that o2 lacks, so the objects are not equal.
				return false;
			}
		}
		// If o2Keys.size is not zero, then o2's keys are a superset of o1's,
		// and the objects are not equal.
		return o2Keys.size === 0;
	} else if ( !isObject1 && !isObject2 ) {
		// Neither input object is of type Object; we can use ===.
		return o1 === o2;
	} else {
		// Only one input object is of type Object; they cannot be equal.
		return false;
	}
}
 
function stableStringify( jsonObject ) {
	if ( isArray( jsonObject ) ) {
		const children = [];
		for ( const child of jsonObject ) {
			children.push( stableStringify( child ) );
		}
		const parts = [
			'[',
			children.join( ',' ),
			']'
		];
		return parts.join( '' );
	}
	if ( isObject( jsonObject ) ) {
		const keys = Object.keys( jsonObject );
		keys.sort();
		const children = [];
		for ( const key of keys ) {
			const value = jsonObject[ key ];
			const stringifiedValue = stableStringify( value );
			children.push( stableStringify( key ) + ':' + stringifiedValue );
		}
		const parts = [
			'{',
			children.join( ',' ),
			'}'
		];
		return parts.join( '' );
	}
 
	// If the object is not an array or Object, it is terminal (string, Number,
	// null, etc.), and we can fall back on the normal JSON.stringify.
	return JSON.stringify( jsonObject );
}
 
function deepCopy( o ) {
	return JSON.parse( JSON.stringify( o ) );
}
 
/**
 * Recursively freezes an object and its properties so that it cannot be
 * modified or extended.
 *
 * Use this function with caution. In the context of ZObjects, this
 * function should be safe. But for other use cases, make sure there are no
 * cycles in the object or properites that are not supposed to be frozen (window).
 *
 * @param {*} o any object.
 * @return {*} the same object that was the input, but frozen.
 */
function deepFreeze( o ) {
	Object.keys( o ).forEach( ( property ) => {
		const child = o[ property ];
		if ( child && ( typeof child === 'object' ) && !Object.isFrozen( child ) ) {
			deepFreeze( child );
		}
	} );
	return Object.freeze( o );
}
 
/**
 * Create a Z24 / Void object.  (Z24 is the only possible value of the type
 * Z21 / Unit).
 *
 * @param {boolean} canonical whether output should be in canonical form
 * @return {Object} a reference to Z24
 *
 * TODO (T289301): This should read its outputs from a configuration file.
 */
function makeVoid( canonical = false ) {
	if ( canonical ) {
		return 'Z24';
	}
	return { Z1K1: 'Z9', Z9K1: 'Z24' };
}
 
/**
 * Checks whether the input is a reference to the given ZID.
 *
 * @param {Object | string} ZObject a ZObject
 * @param {string} ZID the ZID to be compared against
 * @return {boolean} true iff ZObject is a reference with the given ZID
 */
function isThisReference( ZObject, ZID ) {
	// Canonical-form reference.
	if ( isString( ZObject ) ) {
		return ZObject === ZID;
	}
	// Normal-form reference.
	let theReference;
	try {
		theReference = ZObject.Z9K1;
	} catch ( e ) {
		// Z9K1 of ZObject could not be accessed, probably because ZObject was undefined.
		return false;
	}
	return theReference === ZID;
}
 
/**
 * Checks whether the input is a Z24 / Void.  Allows for either canonical
 * or normalized input (corresponding to what makeVoid produces).
 *
 * @param {Object | string} v item to be checked
 * @return {boolean} whether v is a Z24
 */
function isVoid( v ) {
	// Case 1: v is a reference to Z24.
	if ( isThisReference( v, 'Z24' ) ) {
		return true;
	}
 
	// Case 2: v is an object whose type is the reference Z21.
	// FIXME: This is still not correct. If v.Z1K1 is a Z4 whose Z4K1/Identity is
	// Z21, this should (but won't) return true. We can't use find*Identity here
	// because find*Identity is defined only for normal-form objects.
	let maybeVoidType;
	try {
		maybeVoidType = v.Z1K1;
	} catch ( e ) {
		// Z1K1 of v could not be accessed, probably because v was undefined.
		return false;
	}
	return isThisReference( maybeVoidType, 'Z21' );
}
 
/**
 * Z9 Reference to Z41 (true).
 *
 * @return {Object} a reference to Z41 (true)
 */
function makeTrue() {
	return { Z1K1: { Z1K1: 'Z9', Z9K1: 'Z40' }, Z40K1: { Z1K1: 'Z9', Z9K1: 'Z41' } };
}
 
/**
 * Z9 Reference to Z42 (false).
 *
 * @return {Object} a reference to Z42 (false)
 */
function makeFalse() {
	return { Z1K1: { Z1K1: 'Z9', Z9K1: 'Z40' }, Z40K1: { Z1K1: 'Z9', Z9K1: 'Z42' } };
}
 
/**
 * Retrieves the head of a ZList.
 *
 * @param {Object} ZList a generic typed list (Z881)
 * @return {Object} the head list element, K1
 */
function getHead( ZList ) {
	return ZList.K1;
}
 
/**
 * Retrieves the tail of a ZList.
 *
 * @param {Object} ZList a generic typed list (Z881)
 * @return {Array} the tail list element, K2
 */
function getTail( ZList ) {
	return ZList.K2;
}
 
/**
 * Sets the tail of a ZList.
 *
 * @param {Object} ZList a generic typed list (Z881)
 * @param {Object} newValue object to be set as new tail
 */
function setTail( ZList, newValue ) {
	ZList.K2 = newValue;
}
 
/**
 * Determines whether an already-validated ZList is empty. Because the list has
 * already been validated, it is sufficient to check for the presence of K1.
 *
 * @param {Object} ZList a generic typed list (Z881)
 * @return {boolean} whether ZList is empty
 */
function isEmptyZList( ZList ) {
	return getHead( ZList ) === undefined;
}
 
/**
 * Turns a ZList into a simple JS array for ease of iteration.
 *
 * @param {Object} ZList a generic typed list (Z881)
 * @return {Array} an array consisting of all elements of ZList
 *
 * @throws Error if called with undefined
 */
function convertZListToItemArray( ZList ) {
	if ( ZList === undefined ) {
		throw new Error( 'convertZListToItemArray called with undefined' );
	}
 
	let tail = ZList;
	const result = [];
	while ( true ) {
		// FIXME: This should only be called on "an already-validated ZList", which this isn't?
		if ( isEmptyZList( tail ) ) {
			break;
		}
		result.push( getHead( tail ) );
		tail = getTail( tail );
	}
	return result;
}
 
/**
 * Turns a JS array into a Typed List.
 *
 * @param {Array} array an array of ZObjects
 * @param {string} headKey key to be used for list head (K1)
 * @param {string} tailKey key to be used for list tail (K2)
 * @param {Object} tailType list type
 * @return {Object} a Typed List corresponding to the input array
 */
function convertArrayToZListInternal( array, headKey, tailKey, tailType ) {
	function createTail() {
		return { Z1K1: tailType };
	}
	const result = createTail();
	let tail = result;
	for ( const element of array ) {
		tail[ headKey ] = element;
		tail[ tailKey ] = createTail();
		tail = tail[ tailKey ];
	}
	return result;
}
 
/**
 * Infers the shared type of an array of normal-form ZObjects.
 *
 * @param {Array} array an array of ZObjects
 * @param {boolean} canonical whether to output in canonical form
 * @return {Object} type of all the elements of the list or Z1
 */
function inferItemType( array, canonical = false ) {
	let headType;
	const Z1K1s = new Set();
	for ( const element of array ) {
		let theType = element.Z1K1;
		if ( isZString( element ) || isZReference( element ) ) {
			theType = wrapInZ9( theType );
		}
		Z1K1s.add( createZObjectKey( theType ) );
	}
 
	// If inferred type is a resolver type, return Z1 instead
	const resolverTypes = [ 'Z9K1|Z9', 'Z9K1|Z7', 'Z9K1|Z18' ];
	if ( ( Z1K1s.size === 1 ) && ( !resolverTypes.includes( Z1K1s.values().next().value ) ) ) {
		headType = array[ 0 ].Z1K1;
	} else {
		headType = 'Z1';
	}
 
	return ( isString( headType ) && !canonical ) ? { Z1K1: 'Z9', Z9K1: headType } : headType;
}
 
/**
 * Turns a JS array of items into a Typed List after inferring the element type..
 * The items must be in normal form.
 *
 * @param {Array} array an array of ZObjects
 * @return {Object} a Typed List corresponding to the input array
 */
function convertItemArrayToZList( array ) {
	const headType = inferItemType( array );
	return convertArrayToKnownTypedList( array, headType, /* canonical= */ false );
}
 
/**
 * Turns a benjamin array into a Typed List. The benjamin array is an array
 * where the first item describes the types of the following ZObjects.
 *
 * @param {Array} array an array of ZObjects
 * @param {boolean} canonical whether to output in canonical form
 * @return {Object} a Typed List corresponding to the input array
 */
function convertBenjaminArrayToZList( array, canonical = false ) {
	const headType = array.length >= 1 ? array[ 0 ] : ( canonical ? 'Z1' : { Z1K1: 'Z9', Z9K1: 'Z1' } );
	return convertArrayToKnownTypedList( array.slice( 1 ), headType, canonical );
}
 
/**
 * Turns a JS array into a Typed List of a known type.
 *
 * @param {Array} array an array of ZObjects
 * @param {string} type the known type of the typed list
 * @param {boolean} canonical whether to output in canonical form
 * @return {Object} a Typed List corresponding to the input array
 */
function convertArrayToKnownTypedList( array, type, canonical = false ) {
	const listType = getTypedListType( type, canonical );
	return convertArrayToZListInternal( array, 'K1', 'K2', listType );
}
 
/**
 * Creates the type value of a Typed List given the expected type of its elements.
 *
 * @param {Object|string} elementType for the list, in normal form
 * @param {boolean} canonical whether to output in canonical form
 * @return {Object} the type of a typed list where the elements are the given type
 */
function getTypedListType( elementType, canonical = false ) {
	const listType = {
		Z1K1: canonical ? 'Z7' : wrapInZ9( 'Z7' ),
		Z7K1: canonical ? 'Z881' : wrapInZ9( 'Z881' )
	};
 
	// elementType can be a string or an object
	// If it's a string, the type is a canonical reference
	// If it's an object, it may be:
	// 1. a normal reference, e.g. { Z1K1: Z9, Z9K1: Z6 }
	// 2. a canonical function call, e.g. { Z1K1: Z7, Z7K1: Z885, Z885K1: Z500 }
	// 3. a normal function call, e.g. {Z1K1:{ Z1K1: Z9, Z9K1: Z7 }, Z7K1:{ Z1K1: Z9, Z9K1: Z999 }}
	if ( isString( elementType ) ) {
		listType.Z881K1 = canonical ? elementType : wrapInZ9( elementType );
	} else {
		if ( elementType.Z1K1 === 'Z9' ) {
			listType.Z881K1 = canonical ? elementType.Z9K1 : elementType;
		} else {
			// FIXME (T304619): If the type is described by a function call,
			// it could be either normal or canonical
			listType.Z881K1 = elementType;
		}
	}
 
	return listType;
}
 
/**
 * Create a new, empty ZMap with the given valueType.
 * At present, the key type of a ZMap can only be Z6 / String or Z39 / Key reference.
 * TODO (T302015) When ZMap keys are extended beyond Z6/Z39, update accordingly
 *
 * @param {Object} keyType A Z9 instance in normal form
 * @param {Object} valueType A ZObject in normal form
 * @return {Object} a Z883 / ZMap with no entries, in normal form
 *
 * @throws Error if given keyType is not supported.
 */
function makeEmptyZMap( keyType, valueType ) {
	const allowedKeyTypes = [ 'Z6', 'Z39' ];
	if ( !allowedKeyTypes.includes( keyType.Z9K1 ) ) {
		throw new Error( 'makeEmptyZMap called with invalid keyType' );
	}
	const mapType = {
		Z1K1: { Z1K1: 'Z9', Z9K1: 'Z7' },
		Z7K1: { Z1K1: 'Z9', Z9K1: 'Z883' },
		Z883K1: keyType,
		Z883K2: valueType
	};
	// The map's K1 property is a list of pairs, and it's required to be present
	// even when empty
	const listType = {
		Z1K1: { Z1K1: 'Z9', Z9K1: 'Z7' },
		Z7K1: { Z1K1: 'Z9', Z9K1: 'Z881' },
		Z881K1: {
			Z1K1: { Z1K1: 'Z9', Z9K1: 'Z7' },
			Z7K1: { Z1K1: 'Z9', Z9K1: 'Z882' },
			Z882K1: keyType,
			Z882K2: valueType
		}
	};
	return {
		Z1K1: mapType,
		K1: { Z1K1: listType }
	};
}
 
/**
 * Create a new, empty ZMap for responses in a Z22/ResponseEnvelope.
 *
 * @return {Object} a Z883 / ZMap with no entries, in normal form
 */
function makeEmptyZResponseEnvelopeMap() {
	return makeEmptyZMap(
		{ Z1K1: 'Z9', Z9K1: 'Z6' },
		{ Z1K1: 'Z9', Z9K1: 'Z1' }
	);
}
 
/**
 * If an object has an .asJSON() method, calls that method and returns the result;
 * otherwise, returns the original object intact.
 *
 * This is a last resort function, to be called sparingly. If we are calling this
 * function, it means we have received a ZWrapper from function-orchestrator
 * code.
 *
 * @param {Object} ZObject a ZObject which may be a ZWrapper
 * @return {Object} the ZObject intact or converted to bare JSON
 */
function maybeAsJSON( ZObject ) {
	try {
		return ZObject.asJSON();
	} catch ( e ) {
		return ZObject;
	}
}
 
/**
 * Does a quick check to determine if the given ZObject is a Z883 / Map.
 * Does not validate the ZObject (i.e., assumes the ZObject is well-formed).
 *
 * @param {Object} ZObject a Z1/ZObject, in canonical or normal form
 * @return {boolean}
 */
function isZMap( ZObject ) {
	const typeAsJSON = maybeAsJSON( ZObject.Z1K1 );
	const typeIdentity = findTypeIdentity( typeAsJSON );
	if ( !typeIdentity ) {
		return false;
	}
	const typeFunction = typeIdentity.Z7K1;
	if ( typeFunction !== undefined ) {
		return typeFunction === 'Z883' || typeFunction.Z9K1 === 'Z883';
	}
	return false;
}
 
function isSameKey( zMapKey, soughtKey ) {
	if ( isZString( zMapKey ) && isZString( soughtKey ) ) {
		return zMapKey.Z6K1 === soughtKey.Z6K1;
	}
	Eif ( isZKeyReference( zMapKey ) && isZKeyReference( soughtKey ) ) {
		return zMapKey.Z39K1.Z6K1 === soughtKey.Z39K1.Z6K1;
	}
	return false;
}
 
/**
 * Ensures there is an entry for the given key / value in the given ZMap.  If there is
 * already an entry for the given key, overwrites the corresponding value.  Otherwise,
 * creates a new entry. N.B.: Modifies the value of the ZMap's K1 in place.
 *
 * TODO (T302015) When ZMap keys are extended beyond Z6/Z39, update accordingly
 *
 * @param {Object} ZMap a Z883/Typed map, in normal form
 * @param {Object} key a Z6 or Z39 instance, in normal form
 * @param {Object} value a Z1/ZObject, in normal form
 * @param {Function} callback a function to call on new entries before returning
 *
 * @throws Error if given ZMap is undefined.
 */
function setZMapValue( ZMap, key, value, callback = null ) {
	if ( ZMap === undefined ) {
		throw new Error( 'setZMapValue called with undefined' );
	}
 
	let penultimateTail = null;
	let tail = ZMap.K1;
	while ( true ) {
		if ( isEmptyZList( tail ) ) {
			break;
		}
		const entry = getHead( tail );
		const entryKey = entry.K1;
		if ( isSameKey( entryKey, key ) ) {
			entry.K2 = value;
			return;
		}
		penultimateTail = tail;
		tail = getTail( tail );
	}
 
	// The key isn't present in the map, so add an entry for it
	const ZMapType = findTypeIdentity( ZMap.Z1K1 );
	const listType = tail.Z1K1;
	const keyType = ZMapType.Z883K1;
	const valueType = ZMapType.Z883K2;
	const pairType = {
		Z1K1: { Z1K1: 'Z9', Z9K1: 'Z7' },
		Z7K1: { Z1K1: 'Z9', Z9K1: 'Z882' },
		Z882K1: keyType,
		Z882K2: valueType
	};
	let newTail = {
		Z1K1: listType,
		K1: {
			Z1K1: pairType,
			K1: key,
			K2: value
		},
		K2: {
			Z1K1: listType
		}
	};
	if ( callback !== null ) {
		newTail = callback( newTail );
	}
 
	if ( penultimateTail === null ) {
		ZMap.K1 = newTail;
	} else {
		setTail( penultimateTail, newTail );
	}
}
 
/**
 * 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 normal OR canonical form
 * @param {Object} key a Z6 or Z39 instance, in normal OR canonical form (but same form as ZMap)
 * @return {Object} a Z1/Object, the value of the map entry with the given key,
 * or undefined if there is no such entry
 *
 * @throws Error if given ZMap is undefined.
 */
function getZMapValue( ZMap, key ) {
	if ( ZMap === undefined ) {
		throw new Error( 'getZMapValue called with undefined' );
	}
	if ( isArray( ZMap.K1 ) ) {
		return getValueFromCanonicalZMap( ZMap, key );
	}
 
	let tail = ZMap.K1;
	while ( tail !== undefined ) {
		if ( isEmptyZList( tail ) ) {
			break;
		}
		const entry = getHead( tail );
 
		if ( isSameKey( entry.K1, key ) ) {
			return entry.K2;
		}
		tail = getTail( tail );
	}
	return undefined;
}
 
/**
 * Return the ZMap value corresponding to the given key, if present.
 * INTERNAL to this file; external callers use getZMapValue.
 * 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} 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.K1;
	for ( let i = 1; i < K1Array.length; i++ ) {
		const entry = K1Array[ i ];
		if ( ( entry.K1 === key ) ||
			( entry.K1.Z1K1 === 'Z6' && key.Z1K1 === 'Z6' && entry.K1.Z6K1 === key.Z6K1 ) ||
			( entry.K1.Z1K1 === 'Z39' && key.Z1K1 === 'Z39' && entry.K1.Z39K1 === key.Z39K1 ) ) {
			return entry.K2;
		}
	}
	return undefined;
}
 
/**
 * Creates a map-based Z22 containing result and metadata.  metadata is normally a Z883 / Map.
 * However, if metadata is a Z5 / Error object, we place it in a new ZMap, as the value of an entry
 * with key "errors", as a programming convenience.
 *
 * @param {Object} result Z22K1 of resulting Z22
 * @param {Object} metadata Z22K2 of resulting Z22 - either a Z883 / Map or a Z5 / Error
 * @param {boolean} canonical whether output should be in canonical form
 * @return {Object} a Z22
 */
function makeMappedResultEnvelope( result = null, metadata = null, canonical = false ) {
	let ZMap;
	if ( metadata && !isZMap( metadata ) && ( metadata.Z1K1 === 'Z5' || metadata.Z1K1.Z9K1 === 'Z5' ) ) {
		const keyType = { Z1K1: 'Z9', Z9K1: 'Z6' };
		const valueType = { Z1K1: 'Z9', Z9K1: 'Z1' };
		ZMap = makeEmptyZMap( keyType, valueType );
		setZMapValue( ZMap, { Z1K1: 'Z6', Z6K1: 'errors' }, metadata );
	} else {
		ZMap = metadata;
	}
	let envelopeType;
	if ( canonical ) {
		envelopeType = 'Z22';
	} else {
		envelopeType = {
			Z1K1: 'Z9',
			Z9K1: 'Z22'
		};
	}
	return {
		Z1K1: envelopeType,
		Z22K1: result === null ? makeVoid( canonical ) : result,
		Z22K2: ZMap === null ? makeVoid( canonical ) : ZMap
	};
}
 
/**
 * Retrieves the Z5/Error, if present, from the given Z22/Evaluation result (envelope).
 *
 * @param {Object} envelope a Z22/Evaluation result (envelope), in normal OR canonical form
 * @return {Object} a Z5/Error if the envelope contains an error; Z24/void otherwise
 */
function getError( envelope ) {
	Iif ( envelope instanceof ZWrapperBase ) {
		return envelope.getError();
	}
	const metadata = envelope.Z22K2;
	if ( isZMap( metadata ) ) {
		let canonical, key;
		if ( isArray( metadata.K1 ) ) {
			canonical = true;
			key = 'errors';
		} else {
			canonical = false;
			key = { Z1K1: 'Z6', Z6K1: 'errors' };
		}
		let error = getZMapValue( metadata, key );
		if ( error === undefined ) {
			error = makeVoid( canonical );
		}
		return error;
	} else { // metadata is Z24/void
		return metadata;
	}
}
 
/**
 * This is called internally when setMetadataValue encounters a ZWrapper/
 * ZWrapperBase instance. It should only ever be used with normal-form
 * ZObjects.
 *
 * @param {ZWrapperBase} envelope a wrapped Z22
 * @param {Object} key a Z6
 * @param {Object} value a Z1
 */
function setWrappedMetadataValue( envelope, key, value ) {
	envelope.setMetadata( key.Z6K1, value );
}
 
/**
 * Ensures there is an entry for the given key / value in the metadata map
 * of the given Z22 / Evaluation result (envelope).  If the envelope has
 * no metadata map, creates one.  If there is already an entry for the given key,
 * overwrites the corresponding value.  Otherwise, creates a new entry.
 * N.B.: May modify the value of Z22K2 and the ZMap's K1 in place.
 *
 * @param {Object} envelope a Z22/Evaluation result, in normal form
 * @param {Object} key a Z6 or Z39 instance, in normal form
 * @param {Object} value a Z1/ZObject, in normal form
 */
function setMetadataValue( envelope, key, value ) {
	if ( envelope instanceof ZWrapperBase ) {
		setWrappedMetadataValue( envelope, key, value );
	}
	let zMap = envelope.Z22K2;
	if ( zMap === undefined || isVoid( zMap ) ) {
		zMap = makeEmptyZResponseEnvelopeMap();
		envelope.Z22K2 = zMap;
	}
	setZMapValue( zMap, key, value );
}
 
function setMetadataValues( envelope, newPairs ) {
	for ( const [ key, value ] of newPairs ) {
		setMetadataValue( envelope, key, value );
	}
}
 
const builtInTypesArray_ = Object.freeze( [
	'Z1', 'Z11', 'Z12', 'Z14', 'Z16', 'Z17', 'Z18', 'Z2', 'Z20', 'Z21',
	'Z22', 'Z23', 'Z3', 'Z31', 'Z32', 'Z39', 'Z4', 'Z40', 'Z5', 'Z50', 'Z6',
	'Z60', 'Z61', 'Z7', 'Z8', 'Z80', 'Z86', 'Z9', 'Z99',
	'Z6001', 'Z6002', 'Z6003', 'Z6004', 'Z6005', 'Z6006',
	'Z6091', 'Z6092', 'Z6094', 'Z6095', 'Z6096'
] );
const builtInTypes_ = new Set( builtInTypesArray_ );
 
function builtInTypes() {
	return builtInTypesArray_;
}
 
function isBuiltInType( ZID ) {
	return builtInTypes_.has( ZID );
}
 
function isUserDefined( ZID ) {
	return !builtInTypes_.has( ZID );
}
 
function inferType( object ) {
	if ( isString( object ) ) {
		if ( isZObjectReference( object ) ) {
			return 'Z9';
		}
		return 'Z6';
	}
	if ( isArray( object ) ) {
		return 'LIST';
	}
	return object.Z1K1;
}
 
function wrapInZ6( zid ) {
	return {
		Z1K1: 'Z6',
		Z6K1: zid
	};
}
 
function wrapInZ9( zid ) {
	return {
		Z1K1: 'Z9',
		Z9K1: zid
	};
}
 
function wrapInKeyReference( key ) {
	return {
		Z1K1: wrapInZ9( 'Z39' ),
		Z39K1: wrapInZ6( key )
	};
}
 
function wrapInQuote( data ) {
	return {
		Z1K1: wrapInZ9( 'Z99' ),
		Z99K1: data
	};
}
 
class MutexLock {
 
	constructor() {
		this.resolve_ = null;
		this.isReleased_ = false;
		Object.defineProperty( this, 'isReleased', {
			get: function () {
				return this.isReleased_;
			}
		} );
	}
 
	setResolve( resolve ) {
		this.resolve_ = resolve;
	}
 
	release() {
		if ( this.resolve_ !== null ) {
			this.resolve_();
		}
		this.isReleased_ = true;
	}
 
}
 
class Mutex {
 
	constructor() {
		this.lastLock_ = new MutexLock();
		this.lastLock_.release();
	}
 
	acquire() {
		const nextLock = new MutexLock();
		let result;
		if ( this.lastLock_.isReleased ) {
			result = new Promise( ( resolve ) => {
				resolve( nextLock );
			} );
		} else {
			result = new Promise( ( resolve ) => {
				this.lastLock_.setResolve( () => {
					resolve( nextLock );
				} );
			} );
		}
		this.lastLock_ = nextLock;
		return result;
	}
 
}
 
module.exports = {
	builtInTypes,
	convertItemArrayToZList,
	convertBenjaminArrayToZList,
	convertArrayToKnownTypedList,
	convertZListToItemArray,
	createZObjectKey,
	findTypeConverterToCodeIdentity,
	findBooleanIdentity,
	findFunctionIdentity,
	findTypeConverterFromCodeIdentity,
	findTypeDefinition,
	findTypeIdentity,
	inferItemType,
	isMemberOfDangerTrio,
	isZArgumentReference,
	isZBoolean,
	isZEnvelope,
	isZFunction,
	isZFunctionCall,
	isZObjectReference,
	isZReference,
	isZString,
	isZType,
	isString,
	isArray,
	isObject,
	isKey,
	isZid,
	isReference,
	isItemId,
	isPropertyId,
	isLexemeId,
	isLexemeFormId,
	isLexemeSenseId,
	isGlobalKey,
	deepEqual,
	deepCopy,
	deepFreeze,
	getHead,
	getTail,
	getTypedListType,
	inferType,
	isBuiltInType,
	isEmptyZList,
	isUserDefined,
	kidFromGlobalKey,
	makeFalse,
	makeMappedResultEnvelope,
	makeTrue,
	makeVoid,
	Mutex,
	isVoid,
	wrapInKeyReference,
	wrapInQuote,
	wrapInZ6,
	wrapInZ9,
	makeEmptyZMap,
	makeEmptyZResponseEnvelopeMap,
	isZMap,
	setZMapValue,
	getZMapValue,
	getError,
	setMetadataValue,
	setMetadataValues,
	stableStringify,
	ZWrapperBase
};