Debian Codegraph @

node/@bufbuild/protobuf/dist/esm/wkt/any.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 { AnySchema } from "./gen/google/protobuf/any_pb.js";
15 import { create } from "../create.js";
16 import { toBinary } from "../to-binary.js";
17 import { fromBinary, mergeFromBinary } from "../from-binary.js";
18 export function anyPack(schema, message, into) {
19 let ret = false;
20 if (!into) {
21 into = create(AnySchema);
22 ret = true;
23 }
24 into.value = toBinary(schema, message);
25 into.typeUrl = typeNameToUrl(message.$typeName);
26 return ret ? into : undefined;
27 }
28 export function anyIs(any, descOrTypeName) {
29 if (any.typeUrl === "") {
30 return false;
31 }
32 const want = typeof descOrTypeName == "string"
33 ? descOrTypeName
34 : descOrTypeName.typeName;
35 const got = typeUrlToName(any.typeUrl);
36 return want === got;
37 }
38 export function anyUnpack(any, registryOrMessageDesc) {
39 if (any.typeUrl === "") {
40 return undefined;
41 }
42 const desc = registryOrMessageDesc.kind == "message"
43 ? registryOrMessageDesc
44 : registryOrMessageDesc.getMessage(typeUrlToName(any.typeUrl));
45 if (!desc || !anyIs(any, desc)) {
46 return undefined;
47 }
48 return fromBinary(desc, any.value);
49 }
50 /**
51 * Same as anyUnpack but unpacks into the target message.
52 */
53 export function anyUnpackTo(any, schema, message) {
54 if (!anyIs(any, schema)) {
55 return undefined;
56 }
57 return mergeFromBinary(schema, message, any.value);
58 }
59 function typeNameToUrl(name) {
60 return `type.googleapis.com/${name}`;
61 }
62 function typeUrlToName(url) {
63 const slash = url.lastIndexOf("/");
64 const name = slash >= 0 ? url.substring(slash + 1) : url;
65 if (!name.length) {
66 throw new Error(`invalid type url: ${url}`);
67 }
68 return name;
69 }