-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
nativoBidAdapter.js
775 lines (663 loc) · 22.4 KB
/
nativoBidAdapter.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
import { deepAccess, isEmpty } from '../src/utils.js'
import { registerBidder } from '../src/adapters/bidderFactory.js'
import { BANNER } from '../src/mediaTypes.js'
import { getGlobal } from '../src/prebidGlobal.js'
import { ortbConverter } from '../libraries/ortbConverter/converter.js'
const converter = ortbConverter({
context: {
// `netRevenue` and `ttl` are required properties of bid responses - provide a default for them
netRevenue: true, // or false if your adapter should set bidResponse.netRevenue = false
ttl: 30 // default bidResponse.ttl (when not specified in ORTB response.seatbid[].bid[].exp)
},
imp(buildImp, bidRequest, context) {
const imp = buildImp(bidRequest, context);
imp.tagid = bidRequest.adUnitCode
return imp;
}
});
const BIDDER_CODE = 'nativo'
const BIDDER_ENDPOINT = 'https://exchange.postrelease.com/prebid'
const GVLID = 263
const TIME_TO_LIVE = 360
const SUPPORTED_AD_TYPES = [BANNER]
const FLOOR_PRICE_CURRENCY = 'USD'
const PRICE_FLOOR_WILDCARD = '*'
const localPbjsRef = getGlobal()
/**
* Keep track of bid data by keys
* @returns {Object} - Map of bid data that can be referenced by multiple keys
*/
export function BidDataMap() {
const referenceMap = {}
const bids = []
/**
* Add a refence to the index by key value
* @param {String} key - The key to store the index reference
* @param {Integer} index - The index value of the bidData
*/
function addKeyReference(key, index) {
if (!referenceMap.hasOwnProperty(key)) {
referenceMap[key] = index
}
}
/**
* Adds a bid to the map
* @param {Object} bid - Bid data
* @param {Array/String} keys - Keys to reference the index value
*/
function addBidData(bid, keys) {
const index = bids.length
bids.push(bid)
if (Array.isArray(keys)) {
keys.forEach((key) => {
addKeyReference(String(key), index)
})
return
}
addKeyReference(String(keys), index)
}
/**
* Get's the bid data refrerenced by the key
* @param {String} key - The key value to find the bid data by
* @returns {Object} - The bid data
*/
function getBidData(key) {
const stringKey = String(key)
if (referenceMap.hasOwnProperty(stringKey)) {
return bids[referenceMap[stringKey]]
}
}
// Return API
return {
addBidData,
getBidData,
}
}
const bidRequestMap = {}
const adUnitsRequested = {}
const extData = {}
// Filtering
const adsToFilter = new Set()
const advertisersToFilter = new Set()
const campaignsToFilter = new Set()
// Prebid adapter referrence doc: https://docs.prebid.org/dev-docs/bidder-adaptor.html
// Validity checks for optionsl paramters
const validParameter = {
url: (value) => typeof value === 'string',
placementId: (value) => {
const isString = typeof value === 'string'
const isNumber = typeof value === 'number'
return isString || isNumber
},
}
export const spec = {
code: BIDDER_CODE,
gvlid: GVLID,
aliases: ['ntv'], // short code
supportedMediaTypes: SUPPORTED_AD_TYPES,
/**
* Determines whether or not the given bid request is valid.
*
* @param {BidRequest} bid The bid params to validate.
* @return boolean True if this is a valid bid, and false otherwise.
*/
isBidRequestValid: function (bid) {
// We don't need any specific parameters to make a bid request
// If not parameters are supplied just verify it's the correct bidder code
if (!bid.params) return bid.bidder === BIDDER_CODE
// Check if any supplied parameters are invalid
const hasInvalidParameters = Object.keys(bid.params).some((key) => {
const value = bid.params[key]
const validityCheck = validParameter[key]
// We don't have a test for this so it's not a paramter we care about
if (!validityCheck) return false
// Return if the check is not passed
return !validityCheck(value)
})
return !hasInvalidParameters
},
/**
* Called when the page asks Prebid.js for bids
* Make a server request from the list of BidRequests
*
* @param {Array} validBidRequests - An array of bidRequest objects, one for each AdUnit that your module is involved in. This array has been processed for special features like sizeConfig, so it’s the list that you should be looping through
* @param {Object} bidderRequest - The master bidRequest object. This object is useful because it carries a couple of bid parameters that are global to all the bids.
* @return ServerRequest Info describing the request to the server.
*/
buildRequests: function (validBidRequests, bidderRequest) {
// Get OpenRTB Data
const openRTBData = converter.toORTB({bidRequests: validBidRequests, bidderRequest})
const openRTBDataString = JSON.stringify(openRTBData)
const requestData = new RequestData()
requestData.addBidRequestDataSource(new UserEIDs())
// Parse values from bid requests
const placementIds = new Set()
const bidDataMap = BidDataMap()
const placementSizes = { length: 0 }
const floorPriceData = {}
let placementId, pageUrl
validBidRequests.forEach((bidRequest) => {
pageUrl =
getPageUrlFromBidRequest(bidRequest) ||
bidderRequest.refererInfo.location
placementId = deepAccess(bidRequest, 'params.placementId')
const bidDataKeys = [bidRequest.adUnitCode]
if (placementId && !placementIds.has(placementId)) {
placementIds.add(placementId)
bidDataKeys.push(placementId)
placementSizes[placementId] = bidRequest.sizes
placementSizes.length++
}
const bidData = {
bidId: bidRequest.bidId,
size: getLargestSize(bidRequest.sizes),
}
bidDataMap.addBidData(bidData, bidDataKeys)
const bidRequestFloorPriceData = parseFloorPriceData(bidRequest)
if (bidRequestFloorPriceData) {
floorPriceData[bidRequest.adUnitCode] = bidRequestFloorPriceData
}
requestData.processBidRequestData(bidRequest, bidderRequest)
})
bidRequestMap[bidderRequest.bidderRequestId] = bidDataMap
// Build adUnit data
const adUnitData = buildAdUnitData(validBidRequests)
// Build basic required QS Params
let params = [
// Prebid version
{
key: 'ntv_pbv', value: localPbjsRef.version
},
// Prebid request id
{ key: 'ntv_pb_rid', value: bidderRequest.bidderRequestId },
// Ad unit data
{
key: 'ntv_ppc',
value: btoa(JSON.stringify(adUnitData)), // Convert to Base 64
},
// Number count of requests per ad unit
{
key: 'ntv_dbr',
value: btoa(JSON.stringify(adUnitsRequested)), // Convert to Base 64
},
// Page url
{
key: 'ntv_url',
value: encodeURIComponent(pageUrl),
},
]
// Floor pricing
if (Object.keys(floorPriceData).length) {
params.unshift({
key: 'ntv_ppf',
value: btoa(JSON.stringify(floorPriceData)),
})
}
// Add filtering
if (adsToFilter.size > 0) {
params.unshift({
key: 'ntv_atf',
value: Array.from(adsToFilter).join(','),
})
}
if (advertisersToFilter.size > 0) {
params.unshift({
key: 'ntv_avtf',
value: Array.from(advertisersToFilter).join(','),
})
}
if (campaignsToFilter.size > 0) {
params.unshift({
key: 'ntv_ctf',
value: Array.from(campaignsToFilter).join(','),
})
}
// Placement Sizes
if (placementSizes.length) {
params.unshift({
key: 'ntv_pas',
value: btoa(JSON.stringify(placementSizes)),
})
}
// Add placement IDs
if (placementIds.size > 0) {
// Convert Set to Array (IE 11 Safe)
const placements = []
placementIds.forEach((value) => placements.push(value))
// Append to query string paramters
params.unshift({ key: 'ntv_ptd', value: placements.join(',') })
}
// Add GDPR params
if (bidderRequest.gdprConsent) {
// Put on the beginning of the qs param array
params.unshift({
key: 'ntv_gdpr_consent',
value: bidderRequest.gdprConsent.consentString,
})
}
// Add USP params
if (bidderRequest.uspConsent) {
// Put on the beginning of the qs param array
params.unshift({ key: 'us_privacy', value: bidderRequest.uspConsent })
}
const qsParamStrings = [requestData.getRequestDataQueryString(), arrayToQS(params)]
const requestUrl = buildRequestUrl(BIDDER_ENDPOINT, qsParamStrings)
let serverRequest = {
method: 'POST',
url: requestUrl,
data: openRTBDataString,
}
return serverRequest
},
/**
* Will be called when the browser has received the response from your server.
* The function will parse the response and create a bidResponse object containing one or more bids.
* The adapter should indicate no valid bids by returning an empty array.
*
* @param {Object} response - Data returned from the bidding server request endpoint
* @param {Object} request - The request object used to call the server request endpoint
* @return {Array} An array of bids which were nested inside the server.
*/
interpretResponse: function (response, request) {
// If the bid response was empty, return []
if (!response || !response.body || isEmpty(response.body)) return []
try {
const body =
typeof response.body === 'string'
? JSON.parse(response.body)
: response.body
const bidResponses = []
const seatbids = body.seatbid
// Step through and grab pertinent data
let bidResponse, adUnit
seatbids.forEach((seatbid) => {
seatbid.bid.forEach((bid) => {
adUnit = this.getAdUnitData(body.id, bid)
bidResponse = {
requestId: adUnit.bidId,
cpm: bid.price,
currency: body.cur,
width: bid.w || adUnit.size[0],
height: bid.h || adUnit.size[1],
creativeId: bid.crid,
dealId: bid.id,
netRevenue: true,
ttl: bid.ttl || TIME_TO_LIVE,
ad: bid.adm,
meta: {
advertiserDomains: bid.adomain,
},
}
if (bid.ext) extData[bid.id] = bid.ext
bidResponses.push(bidResponse)
})
})
// Don't need the map anymore as it was unique for one request/response
delete bidRequestMap[body.id]
return bidResponses
} catch (error) {
// If there is an error, return []
return []
}
},
/**
* All user ID sync activity should be done using the getUserSyncs callback of the BaseAdapter model.
* Given an array of all the responses from the server, getUserSyncs is used to determine which user syncs should occur.
* The order of syncs in the serverResponses array matters. The most important ones should come first, since publishers may limit how many are dropped on their page.
* @param {Object} syncOptions - Which user syncs are allowed?
* @param {Array} serverResponses - Array of server's responses
* @param {Object} gdprConsent - GDPR consent data
* @param {Object} uspConsent - USP consent data
* @return {Array} The user syncs which should be dropped.
*/
getUserSyncs: function (
syncOptions,
serverResponses,
gdprConsent,
uspConsent
) {
// Generate consent qs string
let params = ''
// GDPR
if (gdprConsent) {
params = appendQSParamString(
params,
'gdpr',
gdprConsent.gdprApplies ? 1 : 0
)
params = appendQSParamString(
params,
'gdpr_consent',
encodeURIComponent(gdprConsent.consentString || '')
)
}
// CCPA
if (uspConsent) {
params = appendQSParamString(
params,
'us_privacy',
encodeURIComponent(uspConsent.uspConsent)
)
}
// Get sync urls from the respnse and inject cinbsent params
const types = {
iframe: syncOptions.iframeEnabled,
image: syncOptions.pixelEnabled,
}
const syncs = []
let body
serverResponses.forEach((response) => {
// If the bid response was empty, return []
if (!response || !response.body || isEmpty(response.body)) {
return syncs
}
try {
body =
typeof response.body === 'string'
? JSON.parse(response.body)
: response.body
} catch (err) { return }
// Make sure we have valid content
if (!body || !body.seatbid || body.seatbid.length === 0) return
body.seatbid.forEach((seatbid) => {
// Grab the syncs for each seatbid
seatbid.syncUrls.forEach((sync) => {
if (types[sync.type]) {
if (sync.url.trim() !== '') {
syncs.push({
type: sync.type,
url: sync.url.replace('{GDPR_params}', params),
})
}
}
})
})
})
return syncs
},
/**
* Will be called when a bid from the adapter won the auction.
* @param {Object} bid - The bid that won the auction
*/
onBidWon: function (bid) {
const ext = extData[bid.dealId]
if (!ext) return
appendFilterData(adsToFilter, ext.adsToFilter)
appendFilterData(advertisersToFilter, ext.advertisersToFilter)
appendFilterData(campaignsToFilter, ext.campaignsToFilter)
},
/**
* Maps Prebid's bidId to Nativo's placementId values per unique bidderRequestId
* @param {String} bidderRequestId - The unique ID value associated with the bidderRequest
* @param {Object} bid - The placement ID value from Nativo
* @returns {String} - The bidId value associated with the corresponding placementId
*/
getAdUnitData: function (bidderRequestId, bid) {
const bidDataMap = bidRequestMap[bidderRequestId]
const placementId = bid.impid
const adUnitCode = deepAccess(bid, 'ext.ad_unit_id')
return (
bidDataMap.getBidData(adUnitCode) || bidDataMap.getBidData(placementId)
)
},
}
registerBidder(spec)
// Utils
export class RequestData {
constructor() {
this.bidRequestDataSources = []
}
addBidRequestDataSource(bidRequestDataSource) {
if (!(bidRequestDataSource instanceof BidRequestDataSource)) return
this.bidRequestDataSources.push(bidRequestDataSource)
}
processBidRequestData(bidRequest, bidderRequest) {
for (let bidRequestDataSource of this.bidRequestDataSources) {
bidRequestDataSource.processBidRequestData(bidRequest, bidderRequest)
}
}
getRequestDataQueryString() {
if (this.bidRequestDataSources.length == 0) return
const queryParams = this.bidRequestDataSources.map(dataSource => dataSource.getRequestQueryString()).filter(queryString => queryString !== '')
return queryParams.join('&')
}
}
export class BidRequestDataSource {
constructor() {
this.type = 'BidRequestDataSource'
}
processBidRequestData(bidRequest, bidderRequest) { }
getRequestQueryString() { return '' }
}
export class UserEIDs extends BidRequestDataSource {
constructor() {
super()
this.type = 'UserEIDs'
this.qsParam = new QueryStringParam('ntv_pb_eid')
this.eids = []
}
processBidRequestData(bidRequest, bidderRequest) {
if (bidRequest.userIdAsEids === undefined || this.eids.length > 0) return
this.eids = bidRequest.userIdAsEids
}
getRequestQueryString() {
if (this.eids.length === 0) return ''
const encodedValueArray = encodeToBase64(this.eids)
this.qsParam.value = encodedValueArray
return this.qsParam.toString()
}
}
export class QueryStringParam {
constructor(key, value) {
this.key = key
this.value = value
}
}
QueryStringParam.prototype.toString = function () {
return `${this.key}=${this.value}`
}
export function encodeToBase64(value) {
try {
return btoa(JSON.stringify(value))
} catch (err) { }
}
export function parseFloorPriceData(bidRequest) {
if (typeof bidRequest.getFloor !== 'function') return
// Setup price floor data per bid request
let bidRequestFloorPriceData = {}
let bidMediaTypes = bidRequest.mediaTypes
let sizeOptions = new Set()
// Step through meach media type so we can get floor data for each media type per bid request
Object.keys(bidMediaTypes).forEach((mediaType) => {
// Setup price floor data per media type
let mediaTypeData = bidMediaTypes[mediaType]
let mediaTypeFloorPriceData = {}
let mediaTypeSizes = mediaTypeData.sizes || mediaTypeData.playerSize || []
// Step through each size of the media type so we can get floor data for each size per media type
mediaTypeSizes.forEach((size) => {
// Get floor price data per the getFloor method and respective media type / size combination
const priceFloorData = bidRequest.getFloor({
currency: FLOOR_PRICE_CURRENCY,
mediaType,
size,
})
// Save the data and track the sizes
mediaTypeFloorPriceData[sizeToString(size)] = priceFloorData.floor
sizeOptions.add(size)
})
bidRequestFloorPriceData[mediaType] = mediaTypeFloorPriceData
// Get floor price of current media type with a wildcard size
const sizeWildcardFloor = getSizeWildcardPrice(bidRequest, mediaType)
// Save the wildcard floor price if it was retrieved successfully
if (sizeWildcardFloor.floor > 0) {
mediaTypeFloorPriceData['*'] = sizeWildcardFloor.floor
}
})
// Get floor price for wildcard media type using all of the sizes present in the previous media types
const mediaWildCardPrices = getMediaWildcardPrices(bidRequest, [
PRICE_FLOOR_WILDCARD,
...Array.from(sizeOptions),
])
bidRequestFloorPriceData['*'] = mediaWildCardPrices
return bidRequestFloorPriceData
}
/**
* Get price floor data by always setting the size value to the wildcard for a specific size
* @param {Object} bidRequest - The bid request
* @param {String} mediaType - The media type
* @returns {Object} - Bid floor data
*/
export function getSizeWildcardPrice(bidRequest, mediaType) {
return bidRequest.getFloor({
currency: FLOOR_PRICE_CURRENCY,
mediaType,
size: PRICE_FLOOR_WILDCARD,
})
}
/**
* Get price data for a range of sizes and always setting the media type to the wildcard value
* @param {*} bidRequest - The bid request
* @param {*} sizes - The sizes to get the floor price data for
* @returns {Object} - Bid floor data
*/
export function getMediaWildcardPrices(
bidRequest,
sizes = [PRICE_FLOOR_WILDCARD]
) {
const sizePrices = {}
sizes.forEach((size) => {
// MODIFY the bid request's mediaTypes property (so we can get the wildcard media type value)
const temp = bidRequest.mediaTypes
bidRequest.mediaTypes = { PRICE_FLOOR_WILDCARD: temp.sizes }
// Get price floor data
const priceFloorData = bidRequest.getFloor({
currency: FLOOR_PRICE_CURRENCY,
mediaType: PRICE_FLOOR_WILDCARD,
size,
})
// RESTORE initial property value
bidRequest.mediaTypes = temp
// Only save valid floor price data
const key =
size !== PRICE_FLOOR_WILDCARD ? sizeToString(size) : PRICE_FLOOR_WILDCARD
sizePrices[key] = priceFloorData.floor
})
return sizePrices
}
/**
* Format size array to a string
* @param {Array} size - Size data [width, height]
* @returns {String} - Formated size string
*/
export function sizeToString(size) {
if (!Array.isArray(size) || size.length < 2) return ''
return `${size[0]}x${size[1]}`
}
/**
* Build the ad unit data to send back to the request endpoint
* @param {Array<Object>} requests - Bid requests
* @returns {Array<Object>} - Array of ad unit data
*/
function buildAdUnitData(requests) {
return requests.map((request) => {
// Track if we've already requested for this ad unit code
adUnitsRequested[request.adUnitCode] =
adUnitsRequested[request.adUnitCode] !== undefined
? adUnitsRequested[request.adUnitCode] + 1
: 0
// Return a new object with only the data we need
return {
adUnitCode: request.adUnitCode,
mediaTypes: request.mediaTypes,
}
})
}
/**
* Append QS param to existing string
* @param {String} str - String to append to
* @param {String} key - Key to append
* @param {String} value - Value to append
* @returns
*/
function appendQSParamString(str, key, value) {
return str + `${str.length ? '&' : ''}${key}=${value}`
}
/**
* Convert an object to query string parameters
* @param {Object} obj - Object to convert
* @returns
*/
function arrayToQS(arr) {
return arr.reduce((value, obj) => {
return appendQSParamString(value, obj.key, obj.value)
}, '')
}
/**
* Get the largest size array
* @param {Array} sizes - Array of size arrays
* @returns Size array with the largest area
*/
function getLargestSize(sizes, method = area) {
if (!sizes || sizes.length === 0) return []
if (sizes.length === 1) return sizes[0]
return sizes.reduce((prev, current) => {
if (method(current) > method(prev)) {
return current
} else {
return prev
}
})
}
/**
* Build the final request url
*/
export function buildRequestUrl(baseUrl, qsParamStringArray = []) {
if (qsParamStringArray.length === 0 || !Array.isArray(qsParamStringArray)) return baseUrl
const nonEmptyQSParamStrings = qsParamStringArray.filter(qsParamString => qsParamString.trim() !== '')
if (nonEmptyQSParamStrings.length === 0) return baseUrl
let requestUrl = `${baseUrl}?${nonEmptyQSParamStrings[0]}`
for (let i = 1; i < nonEmptyQSParamStrings.length; i++) {
requestUrl += `&${nonEmptyQSParamStrings[i]}`
}
return requestUrl
}
/**
* Calculate the area
* @param {Array} size - [width, height]
* @returns The calculated area
*/
const area = (size) => size[0] * size[1]
/**
* Save any filter data from winning bid requests for subsequent requests
* @param {Array} filter - The filter data bucket currently stored
* @param {Array} filterData - The filter data to add
*/
function appendFilterData(filter, filterData) {
if (filterData && Array.isArray(filterData) && filterData.length) {
filterData.forEach((ad) => filter.add(ad))
}
}
export function getPageUrlFromBidRequest(bidRequest) {
let paramPageUrl = deepAccess(bidRequest, 'params.url')
if (paramPageUrl == undefined) return
if (hasProtocol(paramPageUrl)) return paramPageUrl
paramPageUrl = addProtocol(paramPageUrl)
try {
const url = new URL(paramPageUrl)
return url.href
} catch (err) { }
}
export function hasProtocol(url) {
const protocolRegexp = /^http[s]?\:/
return protocolRegexp.test(url)
}
export function addProtocol(url) {
if (hasProtocol(url)) {
return url
}
let protocolPrefix = 'https:'
if (url.indexOf('//') !== 0) {
protocolPrefix += '//'
}
return `${protocolPrefix}${url}`
}