# All files / remote serializer.ts

93.74% Statements 554/591
80.2% Branches 243/303
100% Functions 98/98
93.66% Lines 532/568

    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

    2x
    2x
    2x
    2x
    2x

    2x

    2x
    2x
    2x
    2x
    2x

    2x
    2x
    2x

    2x
    2x

    2x
    2x
    2x

    2x
    2x
    2x
    2x
    2x

    2x
    2x
    2x
    2x
    2x
    2x
    2x
    2x

    2x

    5820x

    3032x
    349x
    2683x
    2683x

    2x

    914x
    914x

    2x
    792x
    792x

    2x

    554x

    2x

    6x

    6x

    2x
    1591x

    178x

    1413x

    2x

    31x

    31x

    31x

    2x
    1331x

    2x

    3734x

    2057x

    1677x

    1677x
    1677x
    1677x

    2x

    2057x
    2057x
    2057x
    2057x

    2057x
    2057x
    2057x

    2057x
    2057x

    2057x

    2x
    5x
    5x

    2x
    8x
    8x

    8x

    2x
    634x

    2x
    3492x
    3492x

    2x
    3297x

    2x
    3338x
    3338x

    3338x

    2x
    2444x

    2x
    2670x
    2670x

    2670x

    2670x

    2x
    2333x

    1587x

    746x

    2x
    582x
    582x
    325x

    257x

    2x
    3032x

    3032x

    2x
    3297x

    2x

    3013x

    3013x

    2x

    3338x

    2x
    3608x
    19x
    3589x
    145x
    3444x
    1317x
    2127x
    22x
    22x

    22x
    9x
    13x
    9x
    4x
    4x

    2105x
    1472x
    633x
    327x
    306x
    30x
    276x
    159x

    117x
    5x

    112x
    5x

    107x
    107x

    4259x

    4259x
    4259x
    25x
    4234x
    177x
    4057x
    1355x
    2702x
    20x

    20x
    9x
    11x
    8x
    3x
    3x

    2682x
    1885x
    797x
    407x
    390x

    46x
    46x
    77x
    344x
    242x
    242x

    102x
    8x
    8x
    8x
    8x
    94x
    8x
    8x
    8x
    86x
    86x
    86x
    86x
    86x

    86x

    2x

    1475x

    2x
    538x

    538x

    2x
    870x

    2584x
    2584x
    2584x
    3293x

    2584x

    2943x

    2943x
    2943x
    2943x
    4028x

    2943x

    2x
    327x

    30x
    30x
    30x
    50x

    30x

    2x
    80x

    80x
    80x
    80x
    80x
    80x
    80x

    2x
    5x

    5x

    5x
    5x
    5x

    2x

    85x
    85x
    80x
    5x
    5x

    2x

    402x

    176x

    176x

    36x

    14x

    2x
    660x
    8x

    652x
    250x
    244x
    244x

    6x

    6x
    6x

    402x
    402x
    402x
    6x

    402x

    2x

    2454x

    2454x
    1809x

    1809x

    1809x

    1809x
    1809x
    1809x
    1809x

    645x
    585x
    585x
    585x

    585x

    585x
    585x
    585x
    585x
    585x

    585x
    585x
    585x

    60x
    46x
    46x
    46x
    46x
    46x

    46x
    46x
    46x
    14x
    6x
    6x
    6x
    6x
    6x
    6x
    8x

    8x
    8x
    8x
    8x
    8x
    8x
    8x

    2454x

    2x

    1809x
    845x
    964x
    438x
    526x
    86x
    440x
    426x
    14x
    14x

    2x

    2454x
    2454x
    645x

    1809x
    1809x
    1024x

    785x

    785x

    1571x

    1571x
    1341x

    230x
    32x
    198x
    134x

    64x
    64x

    98x

    1571x
    216x

    1571x

    1078x
    1078x

    1078x
    1001x
    1001x
    1001x
    1001x
    108x
    108x

    893x

    77x
    35x
    35x
    42x
    42x
    42x
    58x

    42x

    42x

    2x
    216x
    216x
    50x

    166x
    166x

    2x
    138x

    138x
    138x

    599x

    599x

    599x
    599x
    26x
    40x

    599x

    625x
    625x

    2x
    98x

    98x

    2x
    58x

    58x
    58x

    2x
    742x

    2x
    255x
    255x

    255x
    255x

    2x

    1591x
    1591x

    1591x
    1591x

    1591x
    1591x

    1591x
    1591x
    178x

    1591x
    1591x
    1591x

    1591x
    1591x
    178x

    1591x
    40x

    1591x
    27x

    1591x

    2x
    327x

    327x
    327x
    327x
    327x

    327x
    327x

    327x
    327x
    66x

    327x
    327x
    327x

    327x
    327x
    31x

    327x
    327x
    21x

    327x
    327x
    15x

    327x

    2x

    558x
    558x
    552x

    6x

    2x
    558x

    552x

    6x

    2x

    1880x

    1880x
    538x

    1342x

    1880x

    1880x
    152x

    1880x

    1591x
    1591x
    178x

    196x

    178x
    160x

    18x

    86x
    86x

    86x
    4x
    82x
    72x
    10x
    10x
    20x
    10x

    1591x
    1591x
    1698x

    327x
    379x

    67x
    67x

    77x

    36x
    36x
    42x
    36x

    2x
    1698x

    2x
    379x

    361x

    18x

    2x
    188x

    2x
    72x

    37x

    15x

    10x

    4x

    6x

    2x
    1894x

    2x
    455x

    2x
    1698x

    2x
    379x

    2x
    188x
    188x

    2x
    72x

    2x
    8x
    4x

    4x
    4x

    2x
    4x

    2x

    2x

    2x

    2x

    2x
    134x
    164x

    2x
    108x
    121x
    108x

    2x

    25472x

     /**
     * Copyright 2017 Google Inc.
     *
     * Licensed under the Apache License, Version 2.0 (the "License");
     * you may not use this file except in compliance with the License.
     * You may obtain a copy of the License at
     *
     *   http://www.apache.org/licenses/LICENSE-2.0
     *
     * Unless required by applicable law or agreed to in writing, software
     * distributed under the License is distributed on an "AS IS" BASIS,
     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     * See the License for the specific language governing permissions and
     * limitations under the License.
     */

    import * as api from '../protos/firestore_proto_api';
    import { Blob } from '../api/blob';
    import { GeoPoint } from '../api/geo_point';
    import { Timestamp } from '../api/timestamp';
    import { DatabaseId } from '../core/database_info';
    import {
      Bound,
      Direction,
      Filter,
      NanFilter,
      NullFilter,
      OrderBy,
      Query,
      RelationFilter,
      RelationOp
    } from '../core/query';
    import { SnapshotVersion } from '../core/snapshot_version';
    import { ProtoByteString, TargetId } from '../core/types';
    import { QueryData, QueryPurpose } from '../local/query_data';
    import { Document, MaybeDocument, NoDocument } from '../model/document';
    import { DocumentKey } from '../model/document_key';
    import * as fieldValue from '../model/field_value';
    import {
      DeleteMutation,
      FieldMask,
      FieldTransform,
      Mutation,
      MutationResult,
      PatchMutation,
      Precondition,
      ServerTimestampTransform,
      SetMutation,
      TransformMutation
    } from '../model/mutation';
    import { FieldPath, ResourcePath } from '../model/path';
    import { assert, fail } from '../util/assert';
    import { Code, FirestoreError } from '../util/error';
    import { AnyJs } from '../util/misc';
    import * as obj from '../util/obj';
    import * as typeUtils from '../util/types';

    import { ExistenceFilter } from './existence_filter';
    import { mapCodeFromRpcCode, mapRpcCodeFromCode } from './rpc_error';
    import {
      DocumentWatchChange,
      ExistenceFilterChange,
      WatchChange,
      WatchTargetChange,
      WatchTargetChangeState
    } from './watch_change';
    import { ApiClientObjectMap } from '../protos/firestore_proto_api';

    const DIRECTIONS = (() => {
      const dirs: { [dir: string]: api.OrderDirection } = {};
      dirs[Direction.ASCENDING.name] = 'ASCENDING';
      dirs[Direction.DESCENDING.name] = 'DESCENDING';
      return dirs;
    })();

    const OPERATORS = (() => {
      const ops: { [op: string]: api.FieldFilterOp } = {};
      ops[RelationOp.LESS_THAN.name] = 'LESS_THAN';
      ops[RelationOp.LESS_THAN_OR_EQUAL.name] = 'LESS_THAN_OR_EQUAL';
      ops[RelationOp.GREATER_THAN.name] = 'GREATER_THAN';
      ops[RelationOp.GREATER_THAN_OR_EQUAL.name] = 'GREATER_THAN_OR_EQUAL';
      ops[RelationOp.EQUAL.name] = 'EQUAL';
      return ops;
    })();

    // A RegExp matching ISO 8601 UTC timestamps with optional fraction.
    const ISO_REG_EXP = new RegExp(/^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.(\d+))?Z$/);

    function assertPresent(value: AnyJs, description: string) {
      assert(!typeUtils.isNullOrUndefined(value), description + ' is missing');
    }

    function parseInt64(value: number | string): number {
      // TODO(bjornick): Handle int64 greater than 53 bits.
      if (typeof value === 'number') {
        return value;
      } else Eif (typeof value === 'string') {
        return Number(value);
      } else {
        return fail("can't parse " + value);
      }
    }

    // This is a supplement to the generated proto interfaces, which fail to account
    // for the fact that a timestamp may be encoded as either a string OR this.
    interface TimestampProto {
      seconds?: string;
      nanos?: number;
    }

    export interface SerializerOptions {
      /**
       * The serializer supports both Protobuf.js and Proto3 JSON formats. By
       * setting this flag to true, the serializer will use the Proto3 JSON format.
       *
       * For a description of the Proto3 JSON format check
       * https://developers.google.com/protocol-buffers/docs/proto3#json
       */
      useProto3Json: boolean;
    }

    /**
     * Generates JsonObject values for the Datastore API suitable for sending to
     * either GRPC stub methods or via the JSON/HTTP REST API.
     * TODO(klimt): We can remove the databaseId argument if we keep the full
     * resource name in documents.
     */
    export class JsonProtoSerializer {
      constructor(
        private databaseId: DatabaseId,
        private options: SerializerOptions
      ) {}

      private emptyByteString(): ProtoByteString {
        Eif (this.options.useProto3Json) {
          return '';
        } else {
          return new Uint8Array(0);
        }
      }

      private unsafeCastProtoByteString(byteString: ProtoByteString): string {
        // byteStrings can be either string or UInt8Array, but the typings say
        // it's always a string. Cast as string to avoid type check failing
        return byteString as string;
      }

      fromRpcStatus(status: api.Status): FirestoreError {
        const code =
          status.code === undefined
            ? Code.UNKNOWN
            : mapCodeFromRpcCode(status.code);
        return new FirestoreError(code, status.message || '');
      }

      /**
       * Returns a value for a number (or undefined) that's appropriate to put into
       * a google.protobuf.Int32Value proto.
       * DO NOT USE THIS FOR ANYTHING ELSE.
       * This method cheats. It's typed as returning "number" because that's what
       * our generated proto interfaces say Int32Value must be. But GRPC actually
       * expects a { value: <number> } struct.
       */
      private toInt32Value(val: number | null): number | undefined {
        if (!typeUtils.isNullOrUndefined(val)) {
          // tslint:disable-next-line:no-any We need to match generated Proto types.
          return { value: val } as any;
        } else {
          return undefined;
        }
      }

      /**
       * Returns a number (or null) from a google.protobuf.Int32Value proto.
       * DO NOT USE THIS FOR ANYTHING ELSE.
       * This method cheats. It's typed as accepting "number" because that's what
       * our generated proto interfaces say Int32Value must be, but it actually
       * accepts { value: number } to match our serialization in toInt32Value().
       */
      private fromInt32Value(val: number | undefined): number | null {
        let result;
        Eif (typeof val === 'object') {
          // tslint:disable-next-line:no-any We need to match generated Proto types.
          result = (val as any).value;
        } else {
          // We accept raw numbers (without the {value: ... } wrapper) for
          // compatibility with legacy persisted data.
          result = val;
        }
        return typeUtils.isNullOrUndefined(result) ? null : result;
      }

      /**
       * Returns a value for a Date that's appropriate to put into a proto.
       * DO NOT USE THIS FOR ANYTHING ELSE.
       * This method cheats. It's typed as returning "string" because that's what
       * our generated proto interfaces say dates must be. But it's easier and safer
       * to actually return a Timestamp proto.
       */
      private toTimestamp(timestamp: Timestamp): string {
        return {
          seconds: timestamp.seconds,
          nanos: timestamp.nanoseconds
          // tslint:disable-next-line:no-any
        } as any;
      }

      private fromTimestamp(date: string | TimestampProto): Timestamp {
        // The json interface (for the browser) will return an iso timestamp string,
        // while the proto js library (for node) will return a
        // google.protobuf.Timestamp instance.
        if (typeof date === 'string') {
          // TODO(b/37282237): Use strings for Proto3 timestamps
          // assert(this.options.useProto3Json,
          //   'The timestamp string format requires Proto3.');
          return this.fromIso8601String(date);
        } else {
          assert(!!date, 'Cannot deserialize null or undefined timestamp.');
          // TODO(b/37282237): Use strings for Proto3 timestamps
          // assert(!this.options.useProto3Json,
          //   'The timestamp instance format requires Proto JS.');
          const seconds = parseInt64(date.seconds || '0');
          const nanos = date.nanos || 0;
          return new Timestamp(seconds, nanos);
        }
      }

      private fromIso8601String(utc: string): Timestamp {
        // The date string can have higher precision (nanos) than the Date class
        // (millis), so we do some custom parsing here.

        // Parse the nanos right out of the string.
        let nanos = 0;
        const fraction = ISO_REG_EXP.exec(utc);
        assert(!!fraction, 'invalid timestamp: ' + utc);
        Eif (fraction![1]) {
          // Pad the fraction out to 9 digits (nanos).
          let nanoStr = fraction![1];
          nanoStr = (nanoStr + '000000000').substr(0, 9);
          nanos = Number(nanoStr);
        }

        // Parse the date to get the seconds.
        const date = new Date(utc);
        const seconds = Math.floor(date.getTime() / 1000);

        return new Timestamp(seconds, nanos);
      }

      /**
       * Returns a value for bytes that's appropriate to put in a proto.
       * DO NOT USE THIS FOR ANYTHING ELSE.
       * This method cheats. It's typed as returning "string" because that's what
       * our generated proto interfaces say bytes must be. But it should return
       * an Uint8Array in Node.
       */
      private toBytes(bytes: Blob): string {
        Eif (this.options.useProto3Json) {
          return bytes.toBase64();
        } else {
          // The typings say it's a string, but it needs to be a Uint8Array in Node.
          return this.unsafeCastProtoByteString(bytes.toUint8Array());
        }
      }

      /**
       * Parse the blob from the protos into the internal Blob class. Note that the
       * typings assume all blobs are strings, but they are actually Uint8Arrays
       * on Node.
       */
      private fromBlob(blob: string | Uint8Array): Blob {
        Eif (typeof blob === 'string') {
          assert(
            this.options.useProto3Json,
            'Expected bytes to be passed in as Uint8Array, but got a string instead.'
          );
          return Blob.fromBase64String(blob);
        } else {
          assert(
            !this.options.useProto3Json,
            'Expected bytes to be passed in as string, but got something else instead.'
          );
          return Blob.fromUint8Array(blob);
        }
      }

      toVersion(version: SnapshotVersion): string {
        return this.toTimestamp(version.toTimestamp());
      }

      fromVersion(version: string): SnapshotVersion {
        assert(!!version, "Trying to deserialize version that isn't set");
        return SnapshotVersion.fromTimestamp(this.fromTimestamp(version));
      }

      toResourceName(databaseId: DatabaseId, path: ResourcePath): string {
        return this.fullyQualifiedPrefixPath(databaseId)
          .child('documents')
          .child(path)
          .canonicalString();
      }

      fromResourceName(name: string): ResourcePath {
        const resource = ResourcePath.fromString(name);
        assert(
          this.isValidResourceName(resource),
          'Tried to deserialize invalid key ' + resource.toString()
        );
        return resource;
      }

      toName(key: DocumentKey): string {
        return this.toResourceName(this.databaseId, key.path);
      }

      fromName(name: string): DocumentKey {
        const resource = this.fromResourceName(name);
        assert(
          resource.get(1) === this.databaseId.projectId,
          'Tried to deserialize key from different project: ' +
            resource.get(1) +
            ' vs ' +
            this.databaseId.projectId
        );
        assert(
          (!resource.get(3) && !this.databaseId.database) ||
            resource.get(3) === this.databaseId.database,
          'Tried to deserialize key from different database: ' +
            resource.get(3) +
            ' vs ' +
            this.databaseId.database
        );
        return new DocumentKey(this.extractLocalPathFromResourceName(resource));
      }

      toQueryPath(path: ResourcePath): string {
        if (path.length === 0) {
          // If the path is empty, the backend requires we leave off the /documents
          // at the end.
          return this.encodedDatabaseId;
        }
        return this.toResourceName(this.databaseId, path);
      }

      fromQueryPath(name: string): ResourcePath {
        const resourceName = this.fromResourceName(name);
        if (resourceName.length === 4) {
          return ResourcePath.EMPTY_PATH;
        }
        return this.extractLocalPathFromResourceName(resourceName);
      }

      get encodedDatabaseId(): string {
        const path = new ResourcePath([
          'projects',
          this.databaseId.projectId,
          'databases',
          this.databaseId.database
        ]);
        return path.canonicalString();
      }

      private fullyQualifiedPrefixPath(databaseId: DatabaseId): ResourcePath {
        return new ResourcePath([
          'projects',
          databaseId.projectId,
          'databases',
          databaseId.database
        ]);
      }

      private extractLocalPathFromResourceName(
        resourceName: ResourcePath
      ): ResourcePath {
        assert(
          resourceName.length > 4 && resourceName.get(4) === 'documents',
          'tried to deserialize invalid key ' + resourceName.toString()
        );
        return resourceName.popFirst(5);
      }

      private isValidResourceName(path: ResourcePath): boolean {
        // Resource names have at least 4 components (project ID, database ID)
        return (
          path.length >= 4 &&
          path.get(0) === 'projects' &&
          path.get(2) === 'databases'
        );
      }

      toValue(val: fieldValue.FieldValue): api.Value {
        if (val instanceof fieldValue.NullValue) {
          return { nullValue: 'NULL_VALUE' };
        } else if (val instanceof fieldValue.BooleanValue) {
          return { booleanValue: val.value() };
        } else if (val instanceof fieldValue.IntegerValue) {
          return { integerValue: '' + val.value() };
        } else if (val instanceof fieldValue.DoubleValue) {
          const doubleValue = val.value();
          Eif (this.options.useProto3Json) {
            // Proto 3 let's us encode NaN and Infinity as string values as
            // expected by the backend. This is currently not checked by our unit
            // tests because they rely on protobuf.js.
            if (isNaN(doubleValue)) {
              return { doubleValue: 'NaN' } as {};
            } else if (doubleValue === Infinity) {
              return { doubleValue: 'Infinity' } as {};
            } else Eif (doubleValue === -Infinity) {
              return { doubleValue: '-Infinity' } as {};
            }
          }
          return { doubleValue: val.value() };
        } else if (val instanceof fieldValue.StringValue) {
          return { stringValue: val.value() };
        } else if (val instanceof fieldValue.ObjectValue) {
          return { mapValue: this.toMapValue(val) };
        } else if (val instanceof fieldValue.ArrayValue) {
          return { arrayValue: this.toArrayValue(val) };
        } else if (val instanceof fieldValue.TimestampValue) {
          return {
            timestampValue: this.toTimestamp(val.internalValue)
          };
        } else if (val instanceof fieldValue.GeoPointValue) {
          return {
            geoPointValue: {
              latitude: val.value().latitude,
              longitude: val.value().longitude
            }
          };
        } else if (val instanceof fieldValue.BlobValue) {
          return {
            bytesValue: this.toBytes(val.value())
          };
        } else Eif (val instanceof fieldValue.RefValue) {
          return {
            referenceValue: this.toResourceName(val.databaseId, val.key.path)
          };
        } else {
          return fail('Unknown FieldValue ' + JSON.stringify(val));
        }
      }

      fromValue(obj: api.Value): fieldValue.FieldValue {
        // tslint:disable-next-line:no-any
        const type = (obj as any)['value_type'];
        if (hasTag(obj, type, 'nullValue')) {
          return fieldValue.NullValue.INSTANCE;
        } else if (hasTag(obj, type, 'booleanValue')) {
          return fieldValue.BooleanValue.of(obj.booleanValue!);
        } else if (hasTag(obj, type, 'integerValue')) {
          return new fieldValue.IntegerValue(parseInt64(obj.integerValue!));
        } else if (hasTag(obj, type, 'doubleValue')) {
          Eif (this.options.useProto3Json) {
            // Proto 3 uses the string values 'NaN' and 'Infinity'.
            if ((obj.doubleValue as {}) === 'NaN') {
              return fieldValue.DoubleValue.NAN;
            } else if ((obj.doubleValue as {}) === 'Infinity') {
              return fieldValue.DoubleValue.POSITIVE_INFINITY;
            } else Eif ((obj.doubleValue as {}) === '-Infinity') {
              return fieldValue.DoubleValue.NEGATIVE_INFINITY;
            }
          }

          return new fieldValue.DoubleValue(obj.doubleValue!);
        } else if (hasTag(obj, type, 'stringValue')) {
          return new fieldValue.StringValue(obj.stringValue!);
        } else if (hasTag(obj, type, 'mapValue')) {
          return this.fromFields(obj.mapValue!.fields || {});
        } else if (hasTag(obj, type, 'arrayValue')) {
          // "values" is not present if the array is empty
          assertPresent(obj.arrayValue, 'arrayValue');
          const values = obj.arrayValue!.values || [];
          return new fieldValue.ArrayValue(values.map(v => this.fromValue(v)));
        } else if (hasTag(obj, type, 'timestampValue')) {
          assertPresent(obj.timestampValue, 'timestampValue');
          return new fieldValue.TimestampValue(
            this.fromTimestamp(obj.timestampValue!)
          );
        } else if (hasTag(obj, type, 'geoPointValue')) {
          assertPresent(obj.geoPointValue, 'geoPointValue');
          const latitude = obj.geoPointValue!.latitude || 0;
          const longitude = obj.geoPointValue!.longitude || 0;
          return new fieldValue.GeoPointValue(new GeoPoint(latitude, longitude));
        } else if (hasTag(obj, type, 'bytesValue')) {
          assertPresent(obj.bytesValue, 'bytesValue');
          const blob = this.fromBlob(obj.bytesValue!);
          return new fieldValue.BlobValue(blob);
        } else Eif (hasTag(obj, type, 'referenceValue')) {
          assertPresent(obj.referenceValue, 'referenceValue');
          const resourceName = this.fromResourceName(obj.referenceValue!);
          const dbId = new DatabaseId(resourceName.get(1), resourceName.get(3));
          const key = new DocumentKey(
            this.extractLocalPathFromResourceName(resourceName)
          );
          return new fieldValue.RefValue(dbId, key);
        } else {
          return fail('Unknown Value proto ' + JSON.stringify(obj));
        }
      }

      /** Creates an api.Document from key and fields (but no create/update time) */
      toMutationDocument(
        key: DocumentKey,
        fields: fieldValue.ObjectValue
      ): api.Document {
        return {
          name: this.toName(key),
          fields: this.toFields(fields)
        };
      }

      toDocument(document: Document): api.Document {
        assert(
          !document.hasLocalMutations,
          "Can't serialize documents with mutations."
        );
        return {
          name: this.toName(document.key),
          fields: this.toFields(document.data),
          updateTime: this.toTimestamp(document.version.toTimestamp())
        };
      }

      fromDocument(document: api.Document): Document {
        return new Document(
          this.fromName(document.name!),
          this.fromVersion(document.updateTime!),
          this.fromFields(document.fields || {}),
          { hasLocalMutations: false }
        );
      }

      toFields(fields: fieldValue.ObjectValue): { [key: string]: api.Value } {
        const result: { [key: string]: api.Value } = {};
        fields.forEach((key, value) => {
          result[key] = this.toValue(value);
        });
        return result;
      }

      fromFields(object: {}): fieldValue.ObjectValue {
        // Proto map<string, Value> gets mapped to Object, so cast it.
        const map = object as { [key: string]: api.Value };
        let result = fieldValue.ObjectValue.EMPTY;
        obj.forEach(map, (key, value) => {
          result = result.set(new FieldPath([key]), this.fromValue(value));
        });
        return result;
      }

      toMapValue(map: fieldValue.ObjectValue): api.MapValue {
        return {
          fields: this.toFields(map)
        };
      }

      toArrayValue(array: fieldValue.ArrayValue): api.ArrayValue {
        const result: api.Value[] = [];
        array.forEach(value => {
          result.push(this.toValue(value));
        });
        return { values: result };
      }

      private fromFound(doc: api.BatchGetDocumentsResponse): Document {
        assert(
          !!doc.found,
          'Tried to deserialize a found document from a missing document.'
        );
        assertPresent(doc.found!.name, 'doc.found.name');
        assertPresent(doc.found!.updateTime, 'doc.found.updateTime');
        const key = this.fromName(doc.found!.name!);
        const version = this.fromVersion(doc.found!.updateTime!);
        const fields = this.fromFields(doc.found!.fields || {});
        return new Document(key, version, fields, { hasLocalMutations: false });
      }

      private fromMissing(result: api.BatchGetDocumentsResponse): NoDocument {
        assert(
          !!result.missing,
          'Tried to deserialize a missing document from a found document.'
        );
        assert(
          !!result.readTime,
          'Tried to deserialize a missing document without a read time.'
        );
        const key = this.fromName(result.missing!);
        const version = this.fromVersion(result.readTime!);
        return new NoDocument(key, version);
      }

      fromMaybeDocument(result: api.BatchGetDocumentsResponse): MaybeDocument {
        // tslint:disable-next-line:no-any
        const type = (result as any)['result'];
        if (hasTag(result, type, 'found')) {
          return this.fromFound(result);
        } else Eif (hasTag(result, type, 'missing')) {
          return this.fromMissing(result);
        }
        return fail('invalid batch get response: ' + JSON.stringify(result));
      }

      private toWatchTargetChangeState(
        state: WatchTargetChangeState
      ): api.TargetChangeTargetChangeType {
        switch (state) {
          case WatchTargetChangeState.Added:
            return 'ADD';
          case WatchTargetChangeState.Current:
            return 'CURRENT';
          case WatchTargetChangeState.NoChange:
            return 'NO_CHANGE';
          case WatchTargetChangeState.Removed:
            return 'REMOVE';
          case WatchTargetChangeState.Reset:
            return 'RESET';
          default:
            return fail('Unknown WatchTargetChangeState: ' + state);
        }
      }

      toTestWatchChange(watchChange: WatchChange): api.ListenResponse {
        if (watchChange instanceof ExistenceFilterChange) {
          return {
            filter: {
              count: watchChange.existenceFilter.count,
              targetId: watchChange.targetId
            }
          };
        }
        if (watchChange instanceof DocumentWatchChange) {
          if (watchChange.newDoc instanceof Document) {
            const doc = watchChange.newDoc;
            return {
              documentChange: {
                document: {
                  name: this.toName(doc.key),
                  fields: this.toFields(doc.data),
                  updateTime: this.toVersion(doc.version)
                },
                targetIds: watchChange.updatedTargetIds,
                removedTargetIds: watchChange.removedTargetIds
              }
            };
          } else Iif (watchChange.newDoc instanceof NoDocument) {
            const doc = watchChange.newDoc;
            return {
              documentDelete: {
                document: this.toName(doc.key),
                readTime: this.toVersion(doc.version),
                removedTargetIds: watchChange.removedTargetIds
              }
            };
          } else Eif (watchChange.newDoc === null) {
            return {
              documentRemove: {
                document: this.toName(watchChange.key),
                removedTargetIds: watchChange.removedTargetIds
              }
            };
          }
        }
        Eif (watchChange instanceof WatchTargetChange) {
          let cause: api.Status | undefined = undefined;
          if (watchChange.cause) {
            cause = {
              code: mapRpcCodeFromCode(watchChange.cause.code),
              message: watchChange.cause.message
            };
          }
          return {
            targetChange: {
              targetChangeType: this.toWatchTargetChangeState(watchChange.state),
              targetIds: watchChange.targetIds,
              resumeToken: this.unsafeCastProtoByteString(watchChange.resumeToken),
              cause
            }
          };
        }
        return fail('Unrecognized watch change: ' + JSON.stringify(watchChange));
      }

      fromWatchChange(change: api.ListenResponse): WatchChange {
        // tslint:disable-next-line:no-any
        const type = (change as any)['response_type'];
        let watchChange: WatchChange;
        if (hasTag(change, type, 'targetChange')) {
          assertPresent(change.targetChange, 'targetChange');
          // proto3 default value is unset in JSON (undefined), so use 'NO_CHANGE'
          // if unset
          const state = this.fromWatchTargetChangeState(
            change.targetChange!.targetChangeType || 'NO_CHANGE'
          );
          const targetIds: TargetId[] = change.targetChange!.targetIds || [];
          const resumeToken =
            change.targetChange!.resumeToken || this.emptyByteString();
          const causeProto = change.targetChange!.cause;
          const cause = causeProto && this.fromRpcStatus(causeProto);
          watchChange = new WatchTargetChange(
            state,
            targetIds,
            resumeToken,
            cause || null
          );
        } else if (hasTag(change, type, 'documentChange')) {
          assertPresent(change.documentChange, 'documentChange');
          assertPresent(change.documentChange!.document, 'documentChange.name');
          assertPresent(
            change.documentChange!.document!.name,
            'documentChange.document.name'
          );
          assertPresent(
            change.documentChange!.document!.updateTime,
            'documentChange.document.updateTime'
          );
          const entityChange = change.documentChange!;
          const key = this.fromName(entityChange.document!.name!);
          const version = this.fromVersion(entityChange.document!.updateTime!);
          const fields = this.fromFields(entityChange.document!.fields || {});
          const doc = new Document(key, version, fields, {
            hasLocalMutations: false
          });
          const updatedTargetIds = entityChange.targetIds || [];
          const removedTargetIds = entityChange.removedTargetIds || [];
          watchChange = new DocumentWatchChange(
            updatedTargetIds,
            removedTargetIds,
            doc.key,
            doc
          );
        } else if (hasTag(change, type, 'documentDelete')) {
          assertPresent(change.documentDelete, 'documentDelete');
          assertPresent(change.documentDelete!.document, 'documentDelete.document');
          const docDelete = change.documentDelete!;
          const key = this.fromName(docDelete.document!);
          const version = docDelete.readTime
            ? this.fromVersion(docDelete.readTime)
            : SnapshotVersion.forDeletedDoc();
          const doc = new NoDocument(key, version);
          const removedTargetIds = docDelete.removedTargetIds || [];
          watchChange = new DocumentWatchChange([], removedTargetIds, doc.key, doc);
        } else if (hasTag(change, type, 'documentRemove')) {
          assertPresent(change.documentRemove, 'documentRemove');
          assertPresent(change.documentRemove!.document, 'documentRemove');
          const docRemove = change.documentRemove!;
          const key = this.fromName(docRemove.document!);
          const removedTargetIds = docRemove.removedTargetIds || [];
          watchChange = new DocumentWatchChange([], removedTargetIds, key, null);
        } else Eif (hasTag(change, type, 'filter')) {
          // TODO(dimond): implement existence filter parsing with strategy.
          assertPresent(change.filter, 'filter');
          assertPresent(change.filter!.targetId, 'filter.targetId');
          const filter = change.filter;
          const count = filter!.count || 0;
          const existenceFilter = new ExistenceFilter(count);
          const targetId = filter!.targetId!;
          watchChange = new ExistenceFilterChange(targetId, existenceFilter);
        } else {
          return fail('Unknown change type ' + JSON.stringify(change));
        }
        return watchChange;
      }

      fromWatchTargetChangeState(
        state: api.TargetChangeTargetChangeType
      ): WatchTargetChangeState {
        if (state === 'NO_CHANGE') {
          return WatchTargetChangeState.NoChange;
        } else if (state === 'ADD') {
          return WatchTargetChangeState.Added;
        } else if (state === 'REMOVE') {
          return WatchTargetChangeState.Removed;
        } else if (state === 'CURRENT') {
          return WatchTargetChangeState.Current;
        } else Eif (state === 'RESET') {
          return WatchTargetChangeState.Reset;
        } else {
          return fail('Got unexpected TargetChange.state: ' + state);
        }
      }

      versionFromListenResponse(change: api.ListenResponse): SnapshotVersion {
        // We have only reached a consistent snapshot for the entire stream if there
        // is a read_time set and it applies to all targets (i.e. the list of
        // targets is empty). The backend is guaranteed to send such responses.
        // tslint:disable-next-line:no-any
        const type = (change as any)['response_type'];
        if (!hasTag(change, type, 'targetChange')) {
          return SnapshotVersion.MIN;
        }
        const targetChange = change.targetChange!;
        if (targetChange.targetIds && targetChange.targetIds.length) {
          return SnapshotVersion.MIN;
        }
        Iif (!targetChange.readTime) {
          return SnapshotVersion.MIN;
        }
        return this.fromVersion(targetChange.readTime);
      }

      toMutation(mutation: Mutation): api.Write {
        let result: api.Write;
        if (mutation instanceof SetMutation) {
          result = {
            update: this.toMutationDocument(mutation.key, mutation.value)
          };
        } else if (mutation instanceof DeleteMutation) {
          result = { delete: this.toName(mutation.key) };
        } else if (mutation instanceof PatchMutation) {
          result = {
            update: this.toMutationDocument(mutation.key, mutation.data),
            updateMask: this.toDocumentMask(mutation.fieldMask)
          };
        } else Eif (mutation instanceof TransformMutation) {
          result = {
            transform: {
              document: this.toName(mutation.key),
              fieldTransforms: mutation.fieldTransforms.map(transform =>
                this.toFieldTransform(transform)
              )
            }
          };
        } else {
          return fail('Unknown mutation type ' + mutation.type);
        }

        if (!mutation.precondition.isNone) {
          result.currentDocument = this.toPrecondition(mutation.precondition);
        }

        return result;
      }

      fromMutation(proto: api.Write): Mutation {
        const precondition = proto.currentDocument
          ? this.fromPrecondition(proto.currentDocument)
          : Precondition.NONE;

        if (proto.update) {
          assertPresent(proto.update.name, 'name');
          const key = this.fromName(proto.update.name!);
          const value = this.fromFields(proto.update.fields || {});
          if (proto.updateMask) {
            const fieldMask = this.fromDocumentMask(proto.updateMask);
            return new PatchMutation(key, value, fieldMask, precondition);
          } else {
            return new SetMutation(key, value, precondition);
          }
        } else if (proto.delete) {
          const key = this.fromName(proto.delete);
          return new DeleteMutation(key, precondition);
        } else Eif (proto.transform) {
          const key = this.fromName(proto.transform.document!);
          const fieldTransforms = proto.transform.fieldTransforms!.map(transform =>
            this.fromFieldTransform(transform)
          );
          assert(
            precondition.exists === true,
            'Transforms only support precondition "exists == true"'
          );
          return new TransformMutation(key, fieldTransforms);
        } else {
          return fail('unknown mutation proto: ' + JSON.stringify(proto));
        }
      }

      private toPrecondition(precondition: Precondition): api.Precondition {
        assert(!precondition.isNone, "Can't serialize an empty precondition");
        if (precondition.updateTime !== undefined) {
          return {
            updateTime: this.toVersion(precondition.updateTime)
          };
        } else Eif (precondition.exists !== undefined) {
          return { exists: precondition.exists };
        } else {
          return fail('Unknown precondition');
        }
      }

      private fromPrecondition(precondition: api.Precondition): Precondition {
        Iif (precondition.updateTime !== undefined) {
          return Precondition.updateTime(this.fromVersion(precondition.updateTime));
        } else Eif (precondition.exists !== undefined) {
          return Precondition.exists(precondition.exists);
        } else {
          return Precondition.NONE;
        }
      }

      private fromWriteResult(proto: api.WriteResult): MutationResult {
        // NOTE: Deletes don't have an updateTime.
        const version = proto.updateTime
          ? this.fromVersion(proto.updateTime)
          : null;
        let transformResults: fieldValue.FieldValue[] | null = null;
        if (proto.transformResults && proto.transformResults.length > 0) {
          transformResults = proto.transformResults.map(result =>
            this.fromValue(result)
          );
        }
        return new MutationResult(version, transformResults);
      }

      fromWriteResults(protos: api.WriteResult[] | undefined): MutationResult[] {
        return (protos || []).map(proto => this.fromWriteResult(proto));
      }

      private toFieldTransform(fieldTransform: FieldTransform): api.FieldTransform {
        assert(
          fieldTransform.transform instanceof ServerTimestampTransform,
          'Unknown transform: ' + fieldTransform.transform
        );
        return {
          fieldPath: fieldTransform.field.canonicalString(),
          setToServerValue: 'REQUEST_TIME'
        };
      }

      private fromFieldTransform(proto: api.FieldTransform): FieldTransform {
        assert(
          proto.setToServerValue! === 'REQUEST_TIME',
          'Unknown transform proto: ' + JSON.stringify(proto)
        );
        const fieldPath = FieldPath.fromServerFormat(proto.fieldPath!);
        return new FieldTransform(fieldPath, ServerTimestampTransform.instance);
      }

      toDocumentsTarget(query: Query): api.DocumentsTarget {
        return { documents: [this.toQueryPath(query.path)] };
      }

      fromDocumentsTarget(documentsTarget: api.DocumentsTarget): Query {
        const count = documentsTarget.documents!.length;
        assert(
          count === 1,
          'DocumentsTarget contained other than 1 document: ' + count
        );
        const name = documentsTarget.documents![0];
        return Query.atPath(this.fromQueryPath(name));
      }

      toQueryTarget(query: Query): api.QueryTarget {
        // Dissect the path into parent, collectionId, and optional key filter.
        const result: api.QueryTarget = { structuredQuery: {} };
        Iif (query.path.isEmpty()) {
          result.parent = this.toQueryPath(ResourcePath.EMPTY_PATH);
        } else {
          const path = query.path;
          assert(
            path.length % 2 !== 0,
            'Document queries with filters are not supported.'
          );
          result.parent = this.toQueryPath(path.popLast());
          result.structuredQuery!.from = [{ collectionId: path.lastSegment() }];
        }

        const where = this.toFilter(query.filters);
        if (where) {
          result.structuredQuery!.where = where;
        }

        const orderBy = this.toOrder(query.orderBy);
        Eif (orderBy) {
          result.structuredQuery!.orderBy = orderBy;
        }

        const limit = this.toInt32Value(query.limit);
        if (limit !== undefined) {
          result.structuredQuery!.limit = limit;
        }

        if (query.startAt) {
          result.structuredQuery!.startAt = this.toCursor(query.startAt);
        }
        if (query.endAt) {
          result.structuredQuery!.endAt = this.toCursor(query.endAt);
        }

        return result;
      }

      fromQueryTarget(target: api.QueryTarget): Query {
        let path = this.fromQueryPath(target.parent!);

        const query = target.structuredQuery!;
        const fromCount = query.from ? query.from.length : 0;
        Eif (fromCount > 0) {
          assert(
            fromCount === 1,
            'StructuredQuery.from with more than one collection is not supported.'
          );
          const from = query.from![0];
          path = path.child(from.collectionId!);
        }

        let filterBy: Filter[] = [];
        if (query.where) {
          filterBy = this.fromFilter(query.where);
        }

        let orderBy: OrderBy[] = [];
        Eif (query.orderBy) {
          orderBy = this.fromOrder(query.orderBy);
        }

        let limit: number | null = null;
        if (query.limit) {
          limit = this.fromInt32Value(query.limit);
        }

        let startAt: Bound | null = null;
        if (query.startAt) {
          startAt = this.fromCursor(query.startAt);
        }

        let endAt: Bound | null = null;
        if (query.endAt) {
          endAt = this.fromCursor(query.endAt);
        }

        return new Query(path, orderBy, filterBy, limit, startAt, endAt);
      }

      toListenRequestLabels(
        queryData: QueryData
      ): ApiClientObjectMap<string> | null {
        const value = this.toLabel(queryData.purpose);
        if (value == null) {
          return null;
        } else {
          return {
            'goog-listen-tags': value
          };
        }
      }

      private toLabel(purpose: QueryPurpose): string | null {
        switch (purpose) {
          case QueryPurpose.Listen:
            return null;
          case QueryPurpose.ExistenceFilterMismatch:
            return 'existence-filter-mismatch';
          case QueryPurpose.LimboResolution:
            return 'limbo-document';
          default:
            return fail('Unrecognized query purpose: ' + purpose);
        }
      }

      toTarget(queryData: QueryData): api.Target {
        let result: api.Target;
        const query = queryData.query;

        if (query.isDocumentQuery()) {
          result = { documents: this.toDocumentsTarget(query) };
        } else {
          result = { query: this.toQueryTarget(query) };
        }

        result.targetId = queryData.targetId;

        if (queryData.resumeToken.length > 0) {
          result.resumeToken = this.unsafeCastProtoByteString(
            queryData.resumeToken
          );
        }

        return result;
      }

      private toFilter(filters: Filter[]): api.Filter | undefined {
        if (filters.length === 0) return;
        const protos = filters.map(
          filter =>
            filter instanceof RelationFilter
              ? this.toRelationFilter(filter)
              : this.toUnaryFilter(filter)
        );
        if (protos.length === 1) {
          return protos[0];
        }
        return { compositeFilter: { op: 'AND', filters: protos } };
      }

      private fromFilter(filter: api.Filter | undefined): Filter[] {
        Iif (!filter) {
          return [];
        } else if (filter.unaryFilter !== undefined) {
          return [this.fromUnaryFilter(filter)];
        } else if (filter.fieldFilter !== undefined) {
          return [this.fromRelationFilter(filter)];
        } else Eif (filter.compositeFilter !== undefined) {
          return filter.compositeFilter.filters!
            .map(f => this.fromFilter(f))
            .reduce((accum, current) => accum.concat(current));
        } else {
          return fail('Unknown filter: ' + JSON.stringify(filter));
        }
      }

      private toOrder(orderBys: OrderBy[]): api.Order[] | undefined {
        Iif (orderBys.length === 0) return;
        return orderBys.map(order => this.toPropertyOrder(order));
      }

      private fromOrder(orderBys: api.Order[]): OrderBy[] {
        return orderBys.map(order => this.fromPropertyOrder(order));
      }

      private toCursor(cursor: Bound): api.Cursor {
        return {
          before: cursor.before,
          values: cursor.position.map(component => this.toValue(component))
        };
      }

      private fromCursor(cursor: api.Cursor): Bound {
        const before = !!cursor.before;
        const position = cursor.values!.map(component => this.fromValue(component));
        return new Bound(position, before);
      }

      // visible for testing
      toDirection(dir: Direction): api.OrderDirection {
        return DIRECTIONS[dir.name];
      }

      // visible for testing
      fromDirection(dir: api.OrderDirection | undefined): Direction | undefined {
        switch (dir) {
          case 'ASCENDING':
            return Direction.ASCENDING;
          case 'DESCENDING':
            return Direction.DESCENDING;
          default:
            return undefined;
        }
      }

      // visible for testing
      toOperatorName(op: RelationOp): api.FieldFilterOp {
        return OPERATORS[op.name];
      }

      fromOperatorName(op: api.FieldFilterOp): RelationOp {
        switch (op) {
          case 'EQUAL':
            return RelationOp.EQUAL;
          case 'GREATER_THAN':
            return RelationOp.GREATER_THAN;
          case 'GREATER_THAN_OR_EQUAL':
            return RelationOp.GREATER_THAN_OR_EQUAL;
          case 'LESS_THAN':
            return RelationOp.LESS_THAN;
          case 'LESS_THAN_OR_EQUAL':
            return RelationOp.LESS_THAN_OR_EQUAL;
          case 'OPERATOR_UNSPECIFIED':
            return fail('Unspecified relation');
          default:
            return fail('Unknown relation');
        }
      }

      toFieldPathReference(path: FieldPath): api.FieldReference {
        return { fieldPath: path.canonicalString() };
      }

      fromFieldPathReference(fieldReference: api.FieldReference): FieldPath {
        return FieldPath.fromServerFormat(fieldReference.fieldPath!);
      }

      // visible for testing
      toPropertyOrder(orderBy: OrderBy): api.Order {
        return {
          field: this.toFieldPathReference(orderBy.field),
          direction: this.toDirection(orderBy.dir)
        };
      }

      fromPropertyOrder(orderBy: api.Order): OrderBy {
        return new OrderBy(
          this.fromFieldPathReference(orderBy.field!),
          this.fromDirection(orderBy.direction)
        );
      }

      // visible for testing
      toRelationFilter(filter: Filter): api.Filter {
        Eif (filter instanceof RelationFilter) {
          return {
            fieldFilter: {
              field: this.toFieldPathReference(filter.field),
              op: this.toOperatorName(filter.op),
              value: this.toValue(filter.value)
            }
          };
        } else {
          return fail('Unrecognized filter: ' + JSON.stringify(filter));
        }
      }

      fromRelationFilter(filter: api.Filter): Filter {
        return new RelationFilter(
          this.fromFieldPathReference(filter.fieldFilter!.field!),
          this.fromOperatorName(filter.fieldFilter!.op!),
          this.fromValue(filter.fieldFilter!.value!)
        );
      }

      // visible for testing
      toUnaryFilter(filter: Filter): api.Filter {
        if (filter instanceof NanFilter) {
          return {
            unaryFilter: {
              field: this.toFieldPathReference(filter.field),
              op: 'IS_NAN'
            }
          };
        } else Eif (filter instanceof NullFilter) {
          return {
            unaryFilter: {
              field: this.toFieldPathReference(filter.field),
              op: 'IS_NULL'
            }
          };
        } else {
          return fail('Unrecognized filter: ' + JSON.stringify(filter));
        }
      }

      fromUnaryFilter(filter: api.Filter): Filter {
        switch (filter.unaryFilter!.op!) {
          case 'IS_NAN':
            const nanField = this.fromFieldPathReference(
              filter.unaryFilter!.field!
            );
            return new NanFilter(nanField);
          case 'IS_NULL':
            const nullField = this.fromFieldPathReference(
              filter.unaryFilter!.field!
            );
            return new NullFilter(nullField);
          case 'OPERATOR_UNSPECIFIED':
            return fail('Unspecified filter');
          default:
            return fail('Unknown filter');
        }
      }

      toDocumentMask(fieldMask: FieldMask): api.DocumentMask {
        return {
          fieldPaths: fieldMask.fields.map(field => field.canonicalString())
        };
      }

      fromDocumentMask(proto: api.DocumentMask): FieldMask {
        const paths = proto.fieldPaths || [];
        const fields = paths.map(path => FieldPath.fromServerFormat(path));
        return new FieldMask(fields);
      }
    }

    /**
     * Checks for a specific oneof tag in a protocol buffer message.
     *
     * This intentionally accommodates two distinct cases:
     *
     * 1) Messages containing a type tag: these are the format produced by GRPC in
     * return values. These may contain default-value mappings for all tags in the
     * oneof but the type tag specifies which one was actually set.
     *
     * 2) Messages that don't contain a type tag: these are the format required by
     * GRPC as inputs. If we emitted objects with type tags, ProtoBuf.js would
     * choke claiming that the tags aren't fields in the Message.
     *
     * Allowing both formats here makes the serializer able to consume the outputs
     * it produces: for all messages it supports, fromX(toX(value)) == value.
     *
     * Note that case 2 suffers from ambiguity: if multiple tags are present
     * without a type tag then the callers are structured in such a way that the
     * first invocation will win. Since we only parse in this mode when parsing
     * the output of a serialize method this works, but it's not a general
     * solution.
     *
     * Unfortunately there is no general solution here because proto3 makes it
     * impossible to distinguish unset from explicitly set fields: both have the
     * default value for the type. Without the type tag but multiple value tags
     * it's possible to have default values for each tag in the oneof and not be
     * able to know which was actually in effect.
     */
    function hasTag(obj: {}, type: string, tag: string): boolean {
      return type === tag || (!type && tag in obj);
    }