| 1 |
"use strict"; |
| 2 |
// Copyright 2021-2026 Buf Technologies, Inc. |
| 3 |
// |
| 4 |
// Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
// you may not use this file except in compliance with the License. |
| 6 |
// You may obtain a copy of the License at |
| 7 |
// |
| 8 |
// http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
// |
| 10 |
// Unless required by applicable law or agreed to in writing, software |
| 11 |
// distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
// See the License for the specific language governing permissions and |
| 14 |
// limitations under the License. |
| 15 |
Object.defineProperty(exports, "__esModule", { value: true }); |
| 16 |
exports.clone = clone; |
| 17 |
const descriptors_js_1 = require("./descriptors.js"); |
| 18 |
const reflect_js_1 = require("./reflect/reflect.js"); |
| 19 |
const guard_js_1 = require("./reflect/guard.js"); |
| 20 |
/** |
| 21 |
* Create a deep copy of a message, including extensions and unknown fields. |
| 22 |
*/ |
| 23 |
function clone(schema, message) { |
| 24 |
return cloneReflect((0, reflect_js_1.reflect)(schema, message)).message; |
| 25 |
} |
| 26 |
function cloneReflect(i) { |
| 27 |
const o = (0, reflect_js_1.reflect)(i.desc); |
| 28 |
for (const f of i.fields) { |
| 29 |
if (!i.isSet(f)) { |
| 30 |
continue; |
| 31 |
} |
| 32 |
switch (f.fieldKind) { |
| 33 |
case "list": |
| 34 |
const list = o.get(f); |
| 35 |
for (const item of i.get(f)) { |
| 36 |
list.add(cloneSingular(f, item)); |
| 37 |
} |
| 38 |
break; |
| 39 |
case "map": |
| 40 |
const map = o.get(f); |
| 41 |
for (const entry of i.get(f).entries()) { |
| 42 |
map.set(entry[0], cloneSingular(f, entry[1])); |
| 43 |
} |
| 44 |
break; |
| 45 |
default: { |
| 46 |
o.set(f, cloneSingular(f, i.get(f))); |
| 47 |
break; |
| 48 |
} |
| 49 |
} |
| 50 |
} |
| 51 |
const unknown = i.getUnknown(); |
| 52 |
if (unknown && unknown.length > 0) { |
| 53 |
o.setUnknown([...unknown]); |
| 54 |
} |
| 55 |
return o; |
| 56 |
} |
| 57 |
function cloneSingular(field, value) { |
| 58 |
if (field.message !== undefined && (0, guard_js_1.isReflectMessage)(value)) { |
| 59 |
return cloneReflect(value); |
| 60 |
} |
| 61 |
if (field.scalar == descriptors_js_1.ScalarType.BYTES && value instanceof Uint8Array) { |
| 62 |
// @ts-expect-error T cannot extend Uint8Array in practice |
| 63 |
return value.slice(); |
| 64 |
} |
| 65 |
return value; |
| 66 |
} |