@@ -110,7 +110,7 @@ export function formatBaggageHeader(entries: Set<string>): string | null {
110110 }
111111
112112 const headerValue = formattedParts . join ( ',' ) ;
113- const byteLength = Buffer . byteLength ( headerValue , 'utf8' ) ;
113+ const byteLength = utf8ByteLength ( headerValue ) ;
114114
115115 if ( byteLength > MAX_BYTES ) {
116116 InternalLog . log (
@@ -122,6 +122,40 @@ export function formatBaggageHeader(entries: Set<string>): string | null {
122122 return headerValue ;
123123}
124124
125+ /**
126+ * Returns the number of bytes needed to encode a string in UTF-8.
127+ *
128+ * Useful as a lightweight alternative to Node.js `Buffer.byteLength()`
129+ * for older environments that do not support it.
130+ *
131+ * @param text - The input string.
132+ * @returns The UTF-8 byte length of the string.
133+ */
134+ function utf8ByteLength ( text : string ) : number {
135+ let byteLength = text . length ;
136+ for ( let i = text . length - 1 ; i >= 0 ; i -- ) {
137+ const code = text . charCodeAt ( i ) ;
138+
139+ // 2-byte characters (U+0080 to U+07FF)
140+ if ( code > 0x7f && code <= 0x7ff ) {
141+ byteLength ++ ;
142+ }
143+ // 3-byte characters (U+0800 to U+FFFF)
144+ else if ( code > 0x7ff && code <= 0xffff ) {
145+ byteLength += 2 ;
146+ }
147+
148+ // Handle surrogate pairs (4-byte characters, e.g. emoji)
149+ // These characters already count as 2 in the initial length
150+ // Encountering the low surrogate already accounts for the full 4 bytes
151+ // (2 from the initial length + 2 for the 3-byte characters logic above)
152+ if ( code >= 0xdc00 && code <= 0xdfff ) {
153+ i -- ; // prevents double counting the same character by skipping high surrogate
154+ }
155+ }
156+ return byteLength ;
157+ }
158+
125159/**
126160 * Returns a set of valid baggage header characters.
127161 */
0 commit comments