@routr/processor 2.34.2 → 3.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -41,20 +41,6 @@ export declare const isAnonymous: (uri: CommonTypes.SipURI) => boolean;
41
41
  * @return {Function} the alteration
42
42
  */
43
43
  export declare const rewriteFromWithNumber: (route: Route) => (request: MessageRequest) => MessageRequest;
44
- /**
45
- * Writes the numbers of a request the way the Trunk it leaves through asks
46
- * (Route.numberFormat). The called format writes the To and Request-URI users,
47
- * read from the request as routed (original, before normalizeToE164), so
48
- * normalizeToE164 has no effect on them. The caller format writes the From
49
- * user only when rewriteFromWithNumber rewrote it to the Number; an anonymous
50
- * From stays anonymous, and a From Routr doesn't rewrite is left to
51
- * normalizeToE164. A user that is not a phone number is sent as it is.
52
- *
53
- * @param {Route} route - the route; does nothing unless route.numberFormat is set
54
- * @param {MessageRequest} original - the request before normalizeToE164
55
- * @return {Function} the alteration
56
- */
57
- export declare const formatNumbers: (route: Route, original: MessageRequest) => (request: MessageRequest) => MessageRequest;
58
44
  /**
59
45
  * The identity mapping that remembers how the identity alterations changed a
60
46
  * request's From and To; addSelfRecordRoute writes it in its Record-Route URI. Both ends of the dialog copy Record-Route into the
@@ -81,3 +67,68 @@ export declare const identityRewriteParameters: (original: MessageRequest, alter
81
67
  * @return {MessageRequest} the request with From and To swapped where they match
82
68
  */
83
69
  export declare const swapIdentityFromRouteSet: (request: MessageRequest) => MessageRequest;
70
+ /**
71
+ * Adds this EdgePort's Via, with the rport flag, for an in-dialog request.
72
+ * When the top Route is a peer EdgePort's own address (in one of this
73
+ * EdgePort's localnets, on the port it listens on for the entry's transport,
74
+ * and not this EdgePort), the Via faces that peer, on that transport.
75
+ * Otherwise it faces the Request-URI as addSelfViaUsingExternalAddrs does,
76
+ * except that a Request-URI with no transport goes on the transport the
77
+ * request came on when fromPeer is set or this EdgePort doesn't listen on UDP.
78
+ *
79
+ * @param {boolean} fromPeer - the request came from a peer EdgePort the
80
+ * processor trusts
81
+ * @return {Function} the alteration; it throws getEdgeInterface's errors
82
+ */
83
+ export declare const addSelfViaTowardNextHop: (fromPeer: boolean) => (request: MessageRequest) => MessageRequest;
84
+ /**
85
+ * Puts the peer EdgePort the route lives on on top of the route set, as a
86
+ * loose route: at the peer's own address, on its listening port for the
87
+ * route's transport, when the peer is on one of this EdgePort's localnets
88
+ * (loopback and network-form localnets never count); else on its interface
89
+ * facing the endpoint, as addRouteToPeerEdgePort does but never at a
90
+ * network-form localnet's address.
91
+ *
92
+ * @param {Route} route - the route on the peer EdgePort
93
+ * @return {Function} the alteration; it throws getEdgeInterface's errors, or
94
+ * NoListeningPointError for a transport the peer doesn't listen on
95
+ */
96
+ export declare const addRouteToPeerEdgePortOwnAddress: (route: Route) => (request: MessageRequest) => MessageRequest;
97
+ /**
98
+ * addSelfRecordRoute for a request a trusted peer EdgePort forwarded:
99
+ * peerSource is the address it came from (its sourceAddress, taken before any
100
+ * Via is added), and the origin entry is the interface facing it instead of
101
+ * the sender, whose host is the peer's interface facing the endpoint. An
102
+ * empty peerSource gives addSelfRecordRoute's result.
103
+ *
104
+ * @param {Route} route - the route
105
+ * @param {Record<string, string>} parameters - the identity mapping
106
+ * @param {string} peerSource - the peer EdgePort's address, or ""
107
+ * @return {Function} the alteration; it throws getEdgeInterface's errors
108
+ */
109
+ export declare const addSelfRecordRouteFromPeer: (route: Route, parameters?: Record<string, string>, peerSource?: string) => (request: MessageRequest) => MessageRequest;
110
+ /**
111
+ * addSelfRecordRoute for a request forwarded to the peer EdgePort the route
112
+ * lives on: the target entry is this EdgePort's own localnet address facing
113
+ * the peer, so the dialog's route set names both EdgePorts by their own
114
+ * addresses (RFC 5658, double Record-Route). When the peer is in none of this
115
+ * EdgePort's localnets, or this EdgePort doesn't listen on the route's
116
+ * transport, it is addSelfRecordRoute.
117
+ *
118
+ * @param {Route} route - the route on the peer EdgePort
119
+ * @param {Record<string, string>} parameters - the identity mapping
120
+ * @return {Function} the alteration; it throws getEdgeInterface's errors
121
+ */
122
+ export declare const addSelfRecordRouteToPeer: (route: Route, parameters?: Record<string, string>) => (request: MessageRequest) => MessageRequest;
123
+ /**
124
+ * Consumes, in a dialog that crossed EdgePorts, every Route entry up to the
125
+ * last one that names this EdgePort by its own address (a localnet address,
126
+ * never a network-form localnet): the ones before it are this EdgePort's and
127
+ * its peers' toward the sender, where the request has already been. Without
128
+ * such an entry, the request is returned as it is. Run it before
129
+ * removeSelfRoutes and addSelfViaTowardNextHop.
130
+ *
131
+ * @param {MessageRequest} request - an in-dialog request
132
+ * @return {MessageRequest} the request without those entries
133
+ */
134
+ export declare const removeRoutesUpToOwn: (request: MessageRequest) => MessageRequest;
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.swapIdentityFromRouteSet = exports.identityRewriteParameters = exports.formatNumbers = exports.rewriteFromWithNumber = exports.isAnonymous = exports.normalizeToE164 = exports.overwriteContactWithSenderInfo = exports.fixInvalidContact = exports.decreaseMaxForwards = exports.removeTopVia = exports.removeSelfRoutes = exports.removeAuthorization = exports.removeHeaders = exports.removeXEdgePortRef = exports.addXEdgePortRef = exports.addSelfRecordRoute = exports.applyXHeaders = exports.addRouteToPeerEdgePort = exports.addRouteToNextHop = exports.addSelfViaUsingExternalAddrs = exports.addSelfViaUsingTheRouteHeaders = exports.addSelfVia = exports.fixRequestURI = void 0;
3
+ exports.removeRoutesUpToOwn = exports.addSelfRecordRouteToPeer = exports.addSelfRecordRouteFromPeer = exports.addRouteToPeerEdgePortOwnAddress = exports.addSelfViaTowardNextHop = exports.swapIdentityFromRouteSet = exports.identityRewriteParameters = exports.rewriteFromWithNumber = exports.isAnonymous = exports.normalizeToE164 = exports.overwriteContactWithSenderInfo = exports.fixInvalidContact = exports.decreaseMaxForwards = exports.removeTopVia = exports.removeSelfRoutes = exports.removeAuthorization = exports.removeHeaders = exports.removeXEdgePortRef = exports.addXEdgePortRef = exports.addSelfRecordRoute = exports.applyXHeaders = exports.addRouteToPeerEdgePort = exports.addRouteToNextHop = exports.addSelfViaUsingExternalAddrs = exports.addSelfViaUsingTheRouteHeaders = exports.addSelfVia = exports.fixRequestURI = void 0;
4
4
  /*
5
5
  * Copyright (C) 2026 by Fonoster Inc (https://fonoster.com)
6
6
  * http://github.com/fonoster/routr
@@ -20,9 +20,9 @@ exports.swapIdentityFromRouteSet = exports.identityRewriteParameters = exports.f
20
20
  * limitations under the License.
21
21
  */
22
22
  const common_1 = require("@routr/common");
23
+ const net_1 = require("net");
23
24
  const phone_1 = require("phone");
24
25
  const helper_1 = require("./helper");
25
- const format_number_1 = require("./format_number");
26
26
  const { IDENTITY_PARAMETERS, encodeIdentity, encodeIdentityUser, decodeIdentity, decodeIdentityUser, portOf } = common_1.Identity;
27
27
  // Forces the requestURI to be the same as the trunk uri.
28
28
  // This is a workaround for Twilio.
@@ -242,14 +242,19 @@ exports.removeAuthorization = removeAuthorization;
242
242
  const isSelfRoute = (request) => (r) => {
243
243
  var _a, _b;
244
244
  const localIps = request.localnets.map((ln) => ln.split("/")[0]);
245
- const lp = common_1.Helper.getListeningPoint(request.listeningPoints, ((_a = r.address.uri.transportParam) === null || _a === void 0 ? void 0 : _a.toUpperCase()) ||
246
- common_1.Transport.UDP);
245
+ // A Route on a transport this EdgePort does not listen on is not this
246
+ // EdgePort's: it stays for the next hop (RFC 3261 section 16.4), as in
247
+ // Connect and the Go SDK
248
+ const transport = ((_a = r.address.uri.transportParam) === null || _a === void 0 ? void 0 : _a.toUpperCase()) || common_1.Transport.UDP;
249
+ const lp = request.listeningPoints.find((lp) => lp.transport.toUpperCase() === transport);
250
+ if (!lp)
251
+ return false;
247
252
  const routeUri = r.address.uri;
248
253
  const aliases = (request.aliases || []).map((a) => a.toLowerCase());
249
254
  return ((localIps.includes(routeUri.host) ||
250
255
  request.externalAddrs.includes(routeUri.host) ||
251
256
  aliases.includes((_b = routeUri.host) === null || _b === void 0 ? void 0 : _b.toLowerCase())) &&
252
- routeUri.port === (lp === null || lp === void 0 ? void 0 : lp.port));
257
+ routeUri.port === lp.port);
253
258
  };
254
259
  const removeSelfRoutes = (request) => {
255
260
  const req = common_1.Helper.deepCopy(request);
@@ -379,44 +384,6 @@ const rewriteFromWithNumber = (route) => (request) => {
379
384
  return req;
380
385
  };
381
386
  exports.rewriteFromWithNumber = rewriteFromWithNumber;
382
- // Writes a URI's user; ";user=phone" stays only when the user sent starts
383
- // with + (or was left as it was), and a format never adds it
384
- const writeUser = (uri, { user, keepsUserPhone }) => {
385
- uri.user = user;
386
- if (!keepsUserPhone && uri.userParam === "phone")
387
- uri.userParam = "";
388
- };
389
- /**
390
- * Writes the numbers of a request the way the Trunk it leaves through asks
391
- * (Route.numberFormat). The called format writes the To and Request-URI users,
392
- * read from the request as routed (original, before normalizeToE164), so
393
- * normalizeToE164 has no effect on them. The caller format writes the From
394
- * user only when rewriteFromWithNumber rewrote it to the Number; an anonymous
395
- * From stays anonymous, and a From Routr doesn't rewrite is left to
396
- * normalizeToE164. A user that is not a phone number is sent as it is.
397
- *
398
- * @param {Route} route - the route; does nothing unless route.numberFormat is set
399
- * @param {MessageRequest} original - the request before normalizeToE164
400
- * @return {Function} the alteration
401
- */
402
- const formatNumbers = (route, original) => (request) => {
403
- var _a;
404
- const { called, caller, countryIsoCode } = (_a = route.numberFormat) !== null && _a !== void 0 ? _a : {};
405
- if (!called && !caller)
406
- return request;
407
- const req = common_1.Helper.deepCopy(request);
408
- if (called) {
409
- const options = Object.assign(Object.assign({}, called), { countryIsoCode });
410
- writeUser(req.message.to.address.uri, (0, format_number_1.formatNumber)(original.message.to.address.uri.user, options));
411
- writeUser(req.message.requestUri, (0, format_number_1.formatNumber)(original.message.requestUri.user, options));
412
- }
413
- const from = req.message.from.address.uri;
414
- if (caller && route.rewriteFrom && !(0, exports.isAnonymous)(from)) {
415
- writeUser(from, (0, format_number_1.formatNumber)(from.user, Object.assign(Object.assign({}, caller), { countryIsoCode })));
416
- }
417
- return req;
418
- };
419
- exports.formatNumbers = formatNumbers;
420
387
  const sameIdentity = (uri, identity) => {
421
388
  var _a, _b, _c;
422
389
  return !!identity &&
@@ -535,3 +502,333 @@ const swapIdentityFromRouteSet = (request) => {
535
502
  return req;
536
503
  };
537
504
  exports.swapIdentityFromRouteSet = swapIdentityFromRouteSet;
505
+ // Dialogs that cross EdgePorts. The alterations below are Connect's own
506
+ // (internal/connect/alterations.go), for a processor that forwards a request
507
+ // to the peer EdgePort holding the endpoint's connection when the EdgePorts
508
+ // share one external address (behind a load balancer): addRouteToPeerEdgePort
509
+ // and addSelfRecordRoute name that shared address, so the request, or the
510
+ // dialog's later ones, can land on an EdgePort that doesn't hold the
511
+ // connection. These name each EdgePort by its own localnet address where it
512
+ // faces the other. The functions above are unchanged.
513
+ //
514
+ // fromPeer and peerSource are what the processor's own trust check decides:
515
+ // set them only for a request whose sourceAddress is a peer EdgePort the
516
+ // processor trusts. The SDK doesn't decide who is a peer.
517
+ const IPV4_BITS = 32;
518
+ const IPV6_BITS = 128;
519
+ // The bits of an IP address, most significant first; undefined when it is
520
+ // not one.
521
+ const addressBits = (address) => {
522
+ if ((0, net_1.isIPv4)(address)) {
523
+ return address
524
+ .split(".")
525
+ .flatMap((octet) => Array.from({ length: 8 }, (_, i) => (Number(octet) >> (7 - i)) & 1));
526
+ }
527
+ if (!(0, net_1.isIPv6)(address))
528
+ return undefined;
529
+ const [head, tail] = address.includes("::")
530
+ ? address.split("::")
531
+ : [address, undefined];
532
+ const headGroups = head ? head.split(":") : [];
533
+ const tailGroups = tail ? tail.split(":") : [];
534
+ const groups = tail === undefined
535
+ ? headGroups
536
+ : [
537
+ ...headGroups,
538
+ ...Array(8 - headGroups.length - tailGroups.length).fill("0"),
539
+ ...tailGroups
540
+ ];
541
+ return groups.flatMap((group) => Array.from({ length: 16 }, (_, i) => (parseInt(group, 16) >> (15 - i)) & 1));
542
+ };
543
+ // The prefix length of a localnet: a CIDR, a dotted IPv4 mask, or none (a
544
+ // single address); undefined when it doesn't parse.
545
+ const prefixOf = (address, mask) => {
546
+ var _a;
547
+ const bits = (0, net_1.isIPv4)(address) ? IPV4_BITS : IPV6_BITS;
548
+ if (mask === undefined)
549
+ return bits;
550
+ if ((0, net_1.isIPv4)(mask)) {
551
+ return ((_a = addressBits(mask)) !== null && _a !== void 0 ? _a : []).filter((bit) => bit === 1).length;
552
+ }
553
+ const n = Number(mask);
554
+ return Number.isInteger(n) && n >= 0 && n <= bits ? n : undefined;
555
+ };
556
+ // The address part of a localnet, the EdgePort's address on it; undefined
557
+ // when the localnet is written as a network address (host bits zero with a
558
+ // shorter prefix than the address, such as 10.244.0.0/16), which names no
559
+ // interface and would be the same on every EdgePort.
560
+ const localnetHost = (network) => {
561
+ const [address, mask] = network.split("/");
562
+ const bits = addressBits(address);
563
+ const prefix = bits ? prefixOf(address, mask) : undefined;
564
+ if (!bits || prefix === undefined)
565
+ return undefined;
566
+ const hostBits = bits.slice(prefix);
567
+ if (hostBits.length > 0 && hostBits.every((bit) => bit === 0)) {
568
+ return undefined;
569
+ }
570
+ return address;
571
+ };
572
+ const hasIpSafe = (network, host) => {
573
+ try {
574
+ return common_1.IpUtils.hasIp(network, host);
575
+ }
576
+ catch (_a) {
577
+ return false;
578
+ }
579
+ };
580
+ // The EdgePort's address on the first localnet the host belongs to, passing
581
+ // over the network-form ones.
582
+ const localnetIp = (localnets, host) => localnets === null || localnets === void 0 ? void 0 : localnets.filter((network) => localnetHost(network) && hasIpSafe(network, host)).map(localnetHost)[0];
583
+ // getEdgeInterface on localnetIp, as the Go SDK's edgeInterface and Connect
584
+ // are: a localnet written as a network (10.244.0.0/16) names no interface, so
585
+ // it is never written in a Via or a Record-Route. getEdgeInterface itself is
586
+ // left as it is for the functions above.
587
+ const edgeInterface = (nets) => {
588
+ const { listeningPoints, endpointIntf, localnets, externalAddrs } = nets;
589
+ const ip = localnetIp(localnets, endpointIntf.host);
590
+ const lp = common_1.Helper.getListeningPoint(listeningPoints, endpointIntf.transport);
591
+ if (!ip && externalAddrs.length === 0) {
592
+ throw new Error(`unable to find a valid interface for host ${endpointIntf.host} and transport ${lp.transport}`);
593
+ }
594
+ const host = ip !== null && ip !== void 0 ? ip : externalAddrs[0];
595
+ if (ip && lp.host !== "0.0.0.0" && lp.host !== host) {
596
+ throw new Error(`listening point host ${lp.host} does not match interface host ${host}`);
597
+ }
598
+ return { host, port: lp.port, transport: lp.transport };
599
+ };
600
+ const isLoopback = (host) => ((0, net_1.isIPv4)(host) && host.startsWith("127.")) || host === "::1";
601
+ const findListeningPoint = (listeningPoints, transport) => {
602
+ try {
603
+ return common_1.Helper.getListeningPoint(listeningPoints, transport);
604
+ }
605
+ catch (_a) {
606
+ return undefined;
607
+ }
608
+ };
609
+ const prependVia = (req, intf) => {
610
+ req.message.via = [Object.assign(Object.assign({}, intf), { rPortFlag: true }), ...req.message.via];
611
+ };
612
+ const prependRoute = (req, host, port, transport) => {
613
+ const r = {
614
+ address: { uri: { host, port, transportParam: transport, lrParam: true } }
615
+ };
616
+ req.message.route = [r, ...req.message.route];
617
+ };
618
+ // Whether a Route entry looks like a peer EdgePort's own address: not this
619
+ // EdgePort, inside its localnets, on the port it listens on for that transport
620
+ const isPeerRoute = (request, r) => {
621
+ const uri = r.address.uri;
622
+ const lp = findListeningPoint(request.listeningPoints, uri.transportParam);
623
+ if (!lp || lp.port !== uri.port || isSelfRoute(request)(r))
624
+ return false;
625
+ return localnetIp(request.localnets, uri.host) !== undefined;
626
+ };
627
+ const addSelfViaUsingExternalAddrsFromPeer = (request, fromPeer) => {
628
+ const req = common_1.Helper.deepCopy(request);
629
+ const uri = request.message.requestUri;
630
+ // No transport means UDP. A peer EdgePort sends the Request-URI with no
631
+ // parameters, so a request from one goes on the transport it came on; so
632
+ // does one on an EdgePort without UDP
633
+ const transport = !uri.transportParam &&
634
+ (fromPeer || !findListeningPoint(request.listeningPoints, common_1.Transport.UDP))
635
+ ? request.sender.transport
636
+ : uri.transportParam;
637
+ prependVia(req, edgeInterface(Object.assign(Object.assign({}, request), { endpointIntf: { host: uri.host, port: uri.port, transport } })));
638
+ return req;
639
+ };
640
+ /**
641
+ * Adds this EdgePort's Via, with the rport flag, for an in-dialog request.
642
+ * When the top Route is a peer EdgePort's own address (in one of this
643
+ * EdgePort's localnets, on the port it listens on for the entry's transport,
644
+ * and not this EdgePort), the Via faces that peer, on that transport.
645
+ * Otherwise it faces the Request-URI as addSelfViaUsingExternalAddrs does,
646
+ * except that a Request-URI with no transport goes on the transport the
647
+ * request came on when fromPeer is set or this EdgePort doesn't listen on UDP.
648
+ *
649
+ * @param {boolean} fromPeer - the request came from a peer EdgePort the
650
+ * processor trusts
651
+ * @return {Function} the alteration; it throws getEdgeInterface's errors
652
+ */
653
+ const addSelfViaTowardNextHop = (fromPeer) => (request) => {
654
+ var _a;
655
+ const top = (_a = request.message.route) === null || _a === void 0 ? void 0 : _a[0];
656
+ if (!top || !isPeerRoute(request, top)) {
657
+ return addSelfViaUsingExternalAddrsFromPeer(request, fromPeer);
658
+ }
659
+ const req = common_1.Helper.deepCopy(request);
660
+ prependVia(req, edgeInterface(Object.assign(Object.assign({}, request), { endpointIntf: {
661
+ host: top.address.uri.host,
662
+ port: top.address.uri.port,
663
+ transport: top.address.uri.transportParam
664
+ } })));
665
+ return req;
666
+ };
667
+ exports.addSelfViaTowardNextHop = addSelfViaTowardNextHop;
668
+ // The address of the peer EdgePort the route lives on, on the first of its
669
+ // localnets that is in one of this EdgePort's localnets
670
+ const peerOwnAddress = (request, route) => {
671
+ var _a;
672
+ return ((_a = route.localnets) !== null && _a !== void 0 ? _a : [])
673
+ .map(localnetHost)
674
+ .find((host) => host &&
675
+ !isLoopback(host) &&
676
+ localnetIp(request.localnets, host) !== undefined);
677
+ };
678
+ /**
679
+ * Puts the peer EdgePort the route lives on on top of the route set, as a
680
+ * loose route: at the peer's own address, on its listening port for the
681
+ * route's transport, when the peer is on one of this EdgePort's localnets
682
+ * (loopback and network-form localnets never count); else on its interface
683
+ * facing the endpoint, as addRouteToPeerEdgePort does but never at a
684
+ * network-form localnet's address.
685
+ *
686
+ * @param {Route} route - the route on the peer EdgePort
687
+ * @return {Function} the alteration; it throws getEdgeInterface's errors, or
688
+ * NoListeningPointError for a transport the peer doesn't listen on
689
+ */
690
+ const addRouteToPeerEdgePortOwnAddress = (route) => (request) => {
691
+ const host = peerOwnAddress(request, route);
692
+ const intf = host
693
+ ? Object.assign(Object.assign({}, common_1.Helper.getListeningPoint(route.listeningPoints, route.transport)), { host }) : edgeInterface({
694
+ listeningPoints: route.listeningPoints,
695
+ localnets: route.localnets,
696
+ externalAddrs: route.externalAddrs,
697
+ endpointIntf: route
698
+ });
699
+ const req = common_1.Helper.deepCopy(request);
700
+ prependRoute(req, intf.host, intf.port, intf.transport);
701
+ return req;
702
+ };
703
+ exports.addRouteToPeerEdgePortOwnAddress = addRouteToPeerEdgePortOwnAddress;
704
+ // Puts this EdgePort on top of the Record-Route set: the origin interface
705
+ // and, when the target interface differs, that one too, both marked r2=on
706
+ const recordRouteBetween = (req, origin, target, parameters) => {
707
+ const user = encodeIdentityUser(parameters);
708
+ const entry = (intf, params) => (Object.assign({ address: {
709
+ uri: Object.assign(Object.assign({}, (user ? { user } : {})), { host: intf.host, port: intf.port, transportParam: intf.transport, lrParam: true })
710
+ } }, (params ? { parameters: params } : {})));
711
+ const differs = origin.host !== target.host ||
712
+ origin.port !== target.port ||
713
+ origin.transport !== target.transport;
714
+ req.message.recordRoute = differs
715
+ ? [
716
+ entry(target, { r2: "on" }),
717
+ entry(origin, { r2: "on" }),
718
+ ...req.message.recordRoute
719
+ ]
720
+ : [entry(origin), ...req.message.recordRoute];
721
+ };
722
+ /**
723
+ * addSelfRecordRoute for a request a trusted peer EdgePort forwarded:
724
+ * peerSource is the address it came from (its sourceAddress, taken before any
725
+ * Via is added), and the origin entry is the interface facing it instead of
726
+ * the sender, whose host is the peer's interface facing the endpoint. An
727
+ * empty peerSource gives addSelfRecordRoute's result.
728
+ *
729
+ * @param {Route} route - the route
730
+ * @param {Record<string, string>} parameters - the identity mapping
731
+ * @param {string} peerSource - the peer EdgePort's address, or ""
732
+ * @return {Function} the alteration; it throws getEdgeInterface's errors
733
+ */
734
+ const addSelfRecordRouteFromPeer = (route, parameters = {}, peerSource = "") => (request) => {
735
+ const nets = {
736
+ listeningPoints: request.listeningPoints,
737
+ localnets: request.localnets,
738
+ externalAddrs: request.externalAddrs
739
+ };
740
+ const origin = edgeInterface(Object.assign(Object.assign({}, nets), { endpointIntf: Object.assign(Object.assign({}, request.sender), { host: peerSource || request.sender.host }) }));
741
+ const target = edgeInterface(Object.assign(Object.assign({}, nets), { endpointIntf: {
742
+ host: route.advertisedHost,
743
+ port: route.advertisedPort,
744
+ transport: route.transport
745
+ } }));
746
+ const req = common_1.Helper.deepCopy(request);
747
+ recordRouteBetween(req, origin, target, parameters);
748
+ return req;
749
+ };
750
+ exports.addSelfRecordRouteFromPeer = addSelfRecordRouteFromPeer;
751
+ // This EdgePort's address on the localnet the peer EdgePort the route lives
752
+ // on is in, on the listening point of the route's transport: the peer is
753
+ // looked for at the interface the request goes to and at its own localnet
754
+ // addresses
755
+ const peerFacingInterface = (request, route) => {
756
+ var _a;
757
+ const lp = findListeningPoint(request.listeningPoints, route.transport);
758
+ if (!lp)
759
+ return undefined;
760
+ const toward = (() => {
761
+ try {
762
+ return [
763
+ edgeInterface({
764
+ listeningPoints: route.listeningPoints,
765
+ localnets: route.localnets,
766
+ externalAddrs: route.externalAddrs,
767
+ endpointIntf: route
768
+ }).host
769
+ ];
770
+ }
771
+ catch (_a) {
772
+ return [];
773
+ }
774
+ })();
775
+ const ip = [...toward, ...((_a = route.localnets) !== null && _a !== void 0 ? _a : []).map(localnetHost)]
776
+ .filter((host) => host && !isLoopback(host))
777
+ .map((host) => localnetIp(request.localnets, host))
778
+ .find((found) => found && !isLoopback(found));
779
+ return ip ? { host: ip, port: lp.port, transport: lp.transport } : undefined;
780
+ };
781
+ /**
782
+ * addSelfRecordRoute for a request forwarded to the peer EdgePort the route
783
+ * lives on: the target entry is this EdgePort's own localnet address facing
784
+ * the peer, so the dialog's route set names both EdgePorts by their own
785
+ * addresses (RFC 5658, double Record-Route). When the peer is in none of this
786
+ * EdgePort's localnets, or this EdgePort doesn't listen on the route's
787
+ * transport, it is addSelfRecordRoute.
788
+ *
789
+ * @param {Route} route - the route on the peer EdgePort
790
+ * @param {Record<string, string>} parameters - the identity mapping
791
+ * @return {Function} the alteration; it throws getEdgeInterface's errors
792
+ */
793
+ const addSelfRecordRouteToPeer = (route, parameters = {}) => (request) => {
794
+ const target = peerFacingInterface(request, route);
795
+ if (!target)
796
+ return (0, exports.addSelfRecordRouteFromPeer)(route, parameters)(request);
797
+ const origin = edgeInterface({
798
+ listeningPoints: request.listeningPoints,
799
+ localnets: request.localnets,
800
+ externalAddrs: request.externalAddrs,
801
+ endpointIntf: request.sender
802
+ });
803
+ const req = common_1.Helper.deepCopy(request);
804
+ recordRouteBetween(req, origin, target, parameters);
805
+ return req;
806
+ };
807
+ exports.addSelfRecordRouteToPeer = addSelfRecordRouteToPeer;
808
+ // Whether a Route entry points at this EdgePort by its own address, one of
809
+ // its localnet addresses, which no peer EdgePort has
810
+ const isOwnAddressRoute = (request, r) => request.localnets.some((network) => localnetHost(network) === r.address.uri.host) && isSelfRoute(request)(r);
811
+ /**
812
+ * Consumes, in a dialog that crossed EdgePorts, every Route entry up to the
813
+ * last one that names this EdgePort by its own address (a localnet address,
814
+ * never a network-form localnet): the ones before it are this EdgePort's and
815
+ * its peers' toward the sender, where the request has already been. Without
816
+ * such an entry, the request is returned as it is. Run it before
817
+ * removeSelfRoutes and addSelfViaTowardNextHop.
818
+ *
819
+ * @param {MessageRequest} request - an in-dialog request
820
+ * @return {MessageRequest} the request without those entries
821
+ */
822
+ const removeRoutesUpToOwn = (request) => {
823
+ var _a;
824
+ const routes = (_a = request.message.route) !== null && _a !== void 0 ? _a : [];
825
+ const last = routes
826
+ .map((r) => isOwnAddressRoute(request, r))
827
+ .lastIndexOf(true);
828
+ if (last === -1)
829
+ return request;
830
+ const req = common_1.Helper.deepCopy(request);
831
+ req.message.route = routes.slice(last + 1);
832
+ return req;
833
+ };
834
+ exports.removeRoutesUpToOwn = removeRoutesUpToOwn;
package/dist/helper.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { MessageRequest, Transport, NetInterface } from "@routr/common";
1
+ import { MessageRequest, Transport, NetInterface, Route } from "@routr/common";
2
2
  export declare const isTypeResponse: (request: MessageRequest) => boolean;
3
3
  export declare const isTypeRequest: (request: MessageRequest) => boolean;
4
4
  export declare const getEdgeInterface: (nets: {
@@ -17,3 +17,29 @@ export declare const isInviteOrAckWithSDP: (request: MessageRequest) => boolean;
17
17
  export declare const isResponseWithSDP: (request: MessageRequest) => boolean;
18
18
  export declare const isOkOrRingingWithSDP: (request: MessageRequest) => boolean;
19
19
  export declare const isBye: (request: MessageRequest) => boolean;
20
+ /**
21
+ * The address the request came from: the top Via's received value, which the
22
+ * SIP stack sets when the packet's source differs from the Via host (RFC 3261
23
+ * section 18.2.1), or the Via host otherwise. A processor checks it against
24
+ * the peer EdgePorts it trusts to decide fromPeer, and passes it as
25
+ * addSelfRecordRouteFromPeer's peerSource. Take it before an alteration adds
26
+ * a Via: that Via becomes the top one.
27
+ *
28
+ * @param {MessageRequest} request - the request
29
+ * @return {string} the address, "" without a Via
30
+ */
31
+ export declare const sourceAddress: (request: MessageRequest) => string;
32
+ /**
33
+ * The route of a request a peer EdgePort forwarded (one carrying
34
+ * X-Edgeport-Ref from a source the processor trusts): the peer pointed the
35
+ * Request-URI at the endpoint, so the route is built from it, as seen from
36
+ * this EdgePort, with the top Via's host as the advertised host. The EdgePort
37
+ * drops the Request-URI's parameters, so with no transport there the route
38
+ * takes the sender's, the one the peer sent on. Connect's
39
+ * createRouteFromLastMessage with its transport override.
40
+ *
41
+ * @param {MessageRequest} request - the request from the peer EdgePort
42
+ * @param {number} defaultExpires - the expiry when the request names none
43
+ * @return {Route} the route
44
+ */
45
+ export declare const createRouteFromPeer: (request: MessageRequest, defaultExpires?: number) => Route;
package/dist/helper.js CHANGED
@@ -1,6 +1,6 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.isBye = exports.isOkOrRingingWithSDP = exports.isResponseWithSDP = exports.isInviteOrAckWithSDP = exports.isAckWithSDP = exports.isInviteWithSDP = exports.isWebRTC = exports.isRinging = exports.isOk = exports.hasSDP = exports.getEdgeInterface = exports.isTypeRequest = exports.isTypeResponse = void 0;
3
+ exports.createRouteFromPeer = exports.sourceAddress = exports.isBye = exports.isOkOrRingingWithSDP = exports.isResponseWithSDP = exports.isInviteOrAckWithSDP = exports.isAckWithSDP = exports.isInviteWithSDP = exports.isWebRTC = exports.isRinging = exports.isOk = exports.hasSDP = exports.getEdgeInterface = exports.isTypeRequest = exports.isTypeResponse = void 0;
4
4
  /*
5
5
  * Copyright (C) 2026 by Fonoster Inc (https://fonoster.com)
6
6
  * http://github.com/fonoster/routr
@@ -21,6 +21,7 @@ exports.isBye = exports.isOkOrRingingWithSDP = exports.isResponseWithSDP = expor
21
21
  */
22
22
  const common_1 = require("@routr/common");
23
23
  const common_2 = require("@routr/common");
24
+ const target_1 = require("./target");
24
25
  const isTypeResponse = (request) => request.message.messageType === common_1.CommonTypes.MessageType.RESPONSE;
25
26
  exports.isTypeResponse = isTypeResponse;
26
27
  const isTypeRequest = (request) => !(0, exports.isTypeResponse)(request);
@@ -65,3 +66,72 @@ const isOkOrRingingWithSDP = (request) => (0, exports.isTypeResponse)(request) &
65
66
  exports.isOkOrRingingWithSDP = isOkOrRingingWithSDP;
66
67
  const isBye = (request) => (0, exports.isTypeRequest)(request) && request.method === common_1.Method.BYE;
67
68
  exports.isBye = isBye;
69
+ /**
70
+ * The address the request came from: the top Via's received value, which the
71
+ * SIP stack sets when the packet's source differs from the Via host (RFC 3261
72
+ * section 18.2.1), or the Via host otherwise. A processor checks it against
73
+ * the peer EdgePorts it trusts to decide fromPeer, and passes it as
74
+ * addSelfRecordRouteFromPeer's peerSource. Take it before an alteration adds
75
+ * a Via: that Via becomes the top one.
76
+ *
77
+ * @param {MessageRequest} request - the request
78
+ * @return {string} the address, "" without a Via
79
+ */
80
+ const sourceAddress = (request) => {
81
+ var _a;
82
+ const via = (_a = request.message.via) === null || _a === void 0 ? void 0 : _a[0];
83
+ if (!via)
84
+ return "";
85
+ return via.received || via.host || "";
86
+ };
87
+ exports.sourceAddress = sourceAddress;
88
+ const transportOf = (name) => {
89
+ const upper = name === null || name === void 0 ? void 0 : name.toUpperCase();
90
+ return Object.values(common_1.Transport).includes(upper)
91
+ ? upper
92
+ : common_1.Transport.UDP;
93
+ };
94
+ const sessionCountOf = (request) => {
95
+ var _a, _b;
96
+ const value = (_b = (_a = request.message.extensions) === null || _a === void 0 ? void 0 : _a.find((ext) => ext.name.toLowerCase() === "x-session-count")) === null || _b === void 0 ? void 0 : _b.value;
97
+ if (value === undefined || value === null || value === "")
98
+ return -1;
99
+ const n = parseInt(value.trim(), 10);
100
+ return isNaN(n) ? 0 : n;
101
+ };
102
+ /**
103
+ * The route of a request a peer EdgePort forwarded (one carrying
104
+ * X-Edgeport-Ref from a source the processor trusts): the peer pointed the
105
+ * Request-URI at the endpoint, so the route is built from it, as seen from
106
+ * this EdgePort, with the top Via's host as the advertised host. The EdgePort
107
+ * drops the Request-URI's parameters, so with no transport there the route
108
+ * takes the sender's, the one the peer sent on. Connect's
109
+ * createRouteFromLastMessage with its transport override.
110
+ *
111
+ * @param {MessageRequest} request - the request from the peer EdgePort
112
+ * @param {number} defaultExpires - the expiry when the request names none
113
+ * @return {Route} the route
114
+ */
115
+ const createRouteFromPeer = (request, defaultExpires = target_1.DEFAULT_EXPIRES) => {
116
+ var _a;
117
+ const uri = request.message.requestUri;
118
+ const via = (_a = request.message.via) === null || _a === void 0 ? void 0 : _a[0];
119
+ return {
120
+ edgePortRef: request.edgePortRef,
121
+ user: uri.user,
122
+ host: uri.host,
123
+ port: uri.port,
124
+ advertisedHost: via === null || via === void 0 ? void 0 : via.host,
125
+ advertisedPort: via === null || via === void 0 ? void 0 : via.port,
126
+ transport: uri.transportParam
127
+ ? transportOf(uri.transportParam)
128
+ : request.sender.transport,
129
+ registeredOn: Date.now(),
130
+ sessionCount: sessionCountOf(request),
131
+ expires: (0, target_1.getTargetExpires)(request, defaultExpires),
132
+ listeningPoints: request.listeningPoints,
133
+ localnets: request.localnets,
134
+ externalAddrs: request.externalAddrs
135
+ };
136
+ };
137
+ exports.createRouteFromPeer = createRouteFromPeer;
package/dist/index.d.ts CHANGED
@@ -6,6 +6,4 @@ export * as Target from "./target";
6
6
  export * as Extensions from "./extensions";
7
7
  export * as Alterations from "./alterations";
8
8
  export * as Helper from "./helper";
9
- export { e164Candidates } from "./e164_candidates";
10
- export { formatNumber, FormatNumberOptions, FormattedNumber } from "./format_number";
11
9
  export { Processor as default, MessageRequest, Response, ProcessorConfig };
package/dist/index.js CHANGED
@@ -36,7 +36,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.Response = exports.default = exports.formatNumber = exports.e164Candidates = exports.Helper = exports.Alterations = exports.Extensions = exports.Target = void 0;
39
+ exports.Response = exports.default = exports.Helper = exports.Alterations = exports.Extensions = exports.Target = void 0;
40
40
  const processor_1 = __importDefault(require("./processor"));
41
41
  exports.default = processor_1.default;
42
42
  const response_1 = __importDefault(require("./response"));
@@ -45,7 +45,3 @@ exports.Target = __importStar(require("./target"));
45
45
  exports.Extensions = __importStar(require("./extensions"));
46
46
  exports.Alterations = __importStar(require("./alterations"));
47
47
  exports.Helper = __importStar(require("./helper"));
48
- var e164_candidates_1 = require("./e164_candidates");
49
- Object.defineProperty(exports, "e164Candidates", { enumerable: true, get: function () { return e164_candidates_1.e164Candidates; } });
50
- var format_number_1 = require("./format_number");
51
- Object.defineProperty(exports, "formatNumber", { enumerable: true, get: function () { return format_number_1.formatNumber; } });
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@routr/processor",
3
- "version": "2.34.2",
3
+ "version": "3.1.0",
4
4
  "description": "Processor server and API",
5
5
  "author": "Pedro Sanders <psanders@fonoster.com>",
6
6
  "homepage": "https://github.com/fonoster/routr#readme",
@@ -15,9 +15,8 @@
15
15
  "@fonoster/logger": "0.6.0",
16
16
  "@grpc/grpc-js": "~1.14.6",
17
17
  "@grpc/proto-loader": "~0.7.10",
18
- "@routr/common": "^2.34.2",
18
+ "@routr/common": "^3.1.0",
19
19
  "fp-ts": "^2.11.8",
20
- "libphonenumber-js": "1.11.20",
21
20
  "phone": "^3.1.68"
22
21
  },
23
22
  "directories": {
@@ -37,5 +36,5 @@
37
36
  "bugs": {
38
37
  "url": "https://github.com/fonoster/routr/issues"
39
38
  },
40
- "gitHead": "5766eb15fd60f870fc260d4ec52db232c038ab7c"
39
+ "gitHead": "e117105ae83d4078ccddd33fe9133d327171dd45"
41
40
  }
@@ -1,13 +0,0 @@
1
- /**
2
- * The E.164 numbers, as digits without the +, that a number written in national
3
- * form may stand for in a country. A carrier writes one number several ways:
4
- * behind an international prefix (00442079460018), with the trunk prefix 0
5
- * (02079460018) or bare (2079460018). Each reading is a candidate; the caller
6
- * compares them with the numbers it knows, so nothing here judges whether a
7
- * candidate is a valid number (number plans reject real landlines).
8
- *
9
- * @param {string} identifier - the number as received, digits only
10
- * @param {string} countryIsoCode - ISO 3166-1 alpha-2 code of the country, any case
11
- * @return {string[]} the candidates; empty when the country is empty or unknown
12
- */
13
- export declare const e164Candidates: (identifier: string, countryIsoCode?: string) => string[];
@@ -1,58 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.e164Candidates = void 0;
4
- /*
5
- * Copyright (C) 2026 by Fonoster Inc (https://fonoster.com)
6
- * http://github.com/fonoster/routr
7
- *
8
- * This file is part of Routr.
9
- *
10
- * Licensed under the MIT License (the "License");
11
- * you may not use this file except in compliance with
12
- * the License. You may obtain a copy of the License at
13
- *
14
- * https://opensource.org/licenses/MIT
15
- *
16
- * Unless required by applicable law or agreed to in writing, software
17
- * distributed under the License is distributed on an "AS IS" BASIS,
18
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
- * See the License for the specific language governing permissions and
20
- * limitations under the License.
21
- */
22
- const phone_1 = require("phone");
23
- // The international prefix of ITU-T E.164, as carriers forward it
24
- const INTERNATIONAL_PREFIX = "00";
25
- const callingCodeOf = (countryIsoCode) => {
26
- var _a;
27
- return (_a = phone_1.countryPhoneData.find((country) => country.alpha2 === (countryIsoCode === null || countryIsoCode === void 0 ? void 0 : countryIsoCode.toUpperCase()))) === null || _a === void 0 ? void 0 : _a.country_code;
28
- };
29
- /**
30
- * The E.164 numbers, as digits without the +, that a number written in national
31
- * form may stand for in a country. A carrier writes one number several ways:
32
- * behind an international prefix (00442079460018), with the trunk prefix 0
33
- * (02079460018) or bare (2079460018). Each reading is a candidate; the caller
34
- * compares them with the numbers it knows, so nothing here judges whether a
35
- * candidate is a valid number (number plans reject real landlines).
36
- *
37
- * @param {string} identifier - the number as received, digits only
38
- * @param {string} countryIsoCode - ISO 3166-1 alpha-2 code of the country, any case
39
- * @return {string[]} the candidates; empty when the country is empty or unknown
40
- */
41
- const e164Candidates = (identifier, countryIsoCode) => {
42
- const callingCode = callingCodeOf(countryIsoCode);
43
- if (!callingCode)
44
- return [];
45
- const afterInternationalPrefix = identifier.startsWith(INTERNATIONAL_PREFIX)
46
- ? [identifier.slice(INTERNATIONAL_PREFIX.length)]
47
- : [];
48
- // Italy keeps the 0 in its E.164 numbers and Germany drops it, so both
49
- // readings are candidates
50
- const national = identifier.startsWith("0")
51
- ? [identifier, identifier.slice(1)]
52
- : [identifier];
53
- return [
54
- ...afterInternationalPrefix,
55
- ...national.map((digits) => callingCode + digits)
56
- ];
57
- };
58
- exports.e164Candidates = e164Candidates;
@@ -1,34 +0,0 @@
1
- import { CommonTypes as CT } from "@routr/common";
2
- export interface FormatNumberOptions extends CT.NumberFormatSetting {
3
- countryIsoCode?: string;
4
- }
5
- export interface FormattedNumber {
6
- user: string;
7
- keepsUserPhone: boolean;
8
- }
9
- /**
10
- * Writes a phone number the way a Trunk's carrier asks for it.
11
- *
12
- * E164 +442079460018, with no prefix
13
- * E164_WITHOUT_PLUS 442079460018
14
- * NATIONAL 02079460018: the digits of the national format, trunk
15
- * prefix included where the country uses one, for a
16
- * number of the reference country; a number of another
17
- * calling code in international form
18
- * INTERNATIONAL 00442079460018: the international prefix of the
19
- * reference country, the country code and the national
20
- * number
21
- *
22
- * NATIONAL and INTERNATIONAL write +E.164 with no prefix when the reference
23
- * country is empty, unknown or has no single international prefix. The
24
- * prefix goes in front of the formatted number, with # escaped as %23 (RFC
25
- * 3261 section 25.1). A user that is not a phone number is returned as it is,
26
- * with no prefix.
27
- *
28
- * @param {string} user - the user part of a URI, as routed
29
- * @param {FormatNumberOptions} options - the format, the prefix and the
30
- * country of the Number the call leaves from
31
- * @return {FormattedNumber} the user to send and whether ";user=phone" still
32
- * describes it
33
- */
34
- export declare const formatNumber: (user: string, options: FormatNumberOptions) => FormattedNumber;
@@ -1,117 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.formatNumber = void 0;
4
- /*
5
- * Copyright (C) 2026 by Fonoster Inc (https://fonoster.com)
6
- * http://github.com/fonoster/routr
7
- *
8
- * This file is part of Routr.
9
- *
10
- * Licensed under the MIT License (the "License");
11
- * you may not use this file except in compliance with
12
- * the License. You may obtain a copy of the License at
13
- *
14
- * https://opensource.org/licenses/MIT
15
- *
16
- * Unless required by applicable law or agreed to in writing, software
17
- * distributed under the License is distributed on an "AS IS" BASIS,
18
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
- * See the License for the specific language governing permissions and
20
- * limitations under the License.
21
- */
22
- const common_1 = require("@routr/common");
23
- const libphonenumber_js_1 = require("libphonenumber-js");
24
- const countryOf = (countryIsoCode) => {
25
- const country = countryIsoCode === null || countryIsoCode === void 0 ? void 0 : countryIsoCode.toUpperCase();
26
- return country && (0, libphonenumber_js_1.isSupportedCountry)(country) ? country : undefined;
27
- };
28
- // A user is read as a number of the reference country first (a + makes it
29
- // international), then as an international number written without its +.
30
- // Whatever neither reading accepts is not a phone number: an Agent's
31
- // username, "anonymous", a short code such as 999
32
- const read = (user, country) => [
33
- (0, libphonenumber_js_1.parsePhoneNumberFromString)(user, country),
34
- (0, libphonenumber_js_1.parsePhoneNumberFromString)(`+${user}`)
35
- ].find((number) => number === null || number === void 0 ? void 0 : number.isPossible());
36
- // The international prefix of a country, digits only, as libphonenumber-js
37
- // writes it from there toward a number of another country code: 00 from GB,
38
- // 011 from the US, 0011 from AU. format("IDD") writes a number of the same
39
- // country in national form, so the probe is always of another country, and
40
- // its own country code and national number are dropped from the end. Empty
41
- // when the country has no single international prefix (BR, KR...).
42
- const internationalPrefix = (country) => {
43
- var _a;
44
- const probe = (0, libphonenumber_js_1.parsePhoneNumberFromString)((0, libphonenumber_js_1.getCountryCallingCode)(country) === "44" ? "+12015550123" : "+442079460000");
45
- const written = probe.format("IDD", { fromCountry: country });
46
- const tail = probe.countryCallingCode + probe.nationalNumber;
47
- const digits = (_a = written === null || written === void 0 ? void 0 : written.replace(/\D/g, "")) !== null && _a !== void 0 ? _a : "";
48
- if (!written || written.startsWith("+") || !digits.endsWith(tail))
49
- return "";
50
- return digits.slice(0, -tail.length);
51
- };
52
- /**
53
- * Writes a phone number the way a Trunk's carrier asks for it.
54
- *
55
- * E164 +442079460018, with no prefix
56
- * E164_WITHOUT_PLUS 442079460018
57
- * NATIONAL 02079460018: the digits of the national format, trunk
58
- * prefix included where the country uses one, for a
59
- * number of the reference country; a number of another
60
- * calling code in international form
61
- * INTERNATIONAL 00442079460018: the international prefix of the
62
- * reference country, the country code and the national
63
- * number
64
- *
65
- * NATIONAL and INTERNATIONAL write +E.164 with no prefix when the reference
66
- * country is empty, unknown or has no single international prefix. The
67
- * prefix goes in front of the formatted number, with # escaped as %23 (RFC
68
- * 3261 section 25.1). A user that is not a phone number is returned as it is,
69
- * with no prefix.
70
- *
71
- * @param {string} user - the user part of a URI, as routed
72
- * @param {FormatNumberOptions} options - the format, the prefix and the
73
- * country of the Number the call leaves from
74
- * @return {FormattedNumber} the user to send and whether ";user=phone" still
75
- * describes it
76
- */
77
- const formatNumber = (user, options) => {
78
- var _a;
79
- const { format } = options;
80
- const prefix = ((_a = options.prefix) !== null && _a !== void 0 ? _a : "").replace(/#/g, "%23");
81
- const country = countryOf(options.countryIsoCode);
82
- const untouched = { user, keepsUserPhone: true };
83
- if (!user || !format || format === common_1.CommonTypes.NumberFormat.UNSPECIFIED) {
84
- return untouched;
85
- }
86
- const number = read(user, country);
87
- if (!number)
88
- return untouched;
89
- const written = (user) => ({
90
- user,
91
- keepsUserPhone: user.startsWith("+")
92
- });
93
- const international = () => {
94
- const idd = country ? internationalPrefix(country) : "";
95
- if (!idd)
96
- return written(number.number);
97
- return written(prefix + idd + number.countryCallingCode + number.nationalNumber);
98
- };
99
- switch (format) {
100
- case common_1.CommonTypes.NumberFormat.E164:
101
- return written(number.number);
102
- case common_1.CommonTypes.NumberFormat.E164_WITHOUT_PLUS:
103
- return written(prefix + number.number.slice(1));
104
- case common_1.CommonTypes.NumberFormat.NATIONAL:
105
- // NATIONAL means something only inside the reference country's own plan
106
- if (!country ||
107
- (0, libphonenumber_js_1.getCountryCallingCode)(country) !== number.countryCallingCode) {
108
- return international();
109
- }
110
- return written(prefix + number.formatNational().replace(/\D/g, ""));
111
- case common_1.CommonTypes.NumberFormat.INTERNATIONAL:
112
- return international();
113
- default:
114
- return untouched;
115
- }
116
- };
117
- exports.formatNumber = formatNumber;