Debian Codegraph @

node/@bufbuild/protobuf/dist/esm/merge.js

raw
1 // Copyright 2021-2026 Buf Technologies, Inc.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 import { reflect } from "./reflect/reflect.js";
15 /**
16 * Merge message `source` into message `target`, following Protobuf semantics.
17 *
18 * This is the same as serializing the source message, then deserializing it
19 * into the target message via `mergeFromBinary()`, with one difference:
20 * While serialization will create a copy of all values, `merge()` will copy
21 * the reference for `bytes` and messages.
22 *
23 * Also see https://protobuf.com/docs/language-spec#merging-protobuf-messages
24 */
25 export function merge(schema, target, source) {
26 reflectMerge(reflect(schema, target), reflect(schema, source));
27 }
28 function reflectMerge(target, source) {
29 var _a;
30 var _b;
31 const sourceUnknown = source.message.$unknown;
32 if (sourceUnknown !== undefined && sourceUnknown.length > 0) {
33 (_a = (_b = target.message).$unknown) !== null && _a !== void 0 ? _a : (_b.$unknown = []);
34 target.message.$unknown.push(...sourceUnknown);
35 }
36 for (const f of target.fields) {
37 if (!source.isSet(f)) {
38 continue;
39 }
40 switch (f.fieldKind) {
41 case "scalar":
42 case "enum":
43 target.set(f, source.get(f));
44 break;
45 case "message":
46 if (target.isSet(f)) {
47 reflectMerge(target.get(f), source.get(f));
48 }
49 else {
50 target.set(f, source.get(f));
51 }
52 break;
53 case "list":
54 const list = target.get(f);
55 for (const e of source.get(f)) {
56 list.add(e);
57 }
58 break;
59 case "map":
60 const map = target.get(f);
61 for (const [k, v] of source.get(f)) {
62 map.set(k, v);
63 }
64 break;
65 }
66 }
67 }