2
2
// This product includes software developed at Datadog (https://www.datadoghq.com/).
3
3
// Copyright 2019-Present Datadog, Inc.
4
4
5
+ import { doRequest } from '@dd/core/helpers' ;
5
6
import type { GlobalContext , GetPlugins , Logger } from '@dd/core/types' ;
6
7
7
8
import { CONFIG_KEY , PLUGIN_NAME } from './constants' ;
@@ -20,6 +21,14 @@ export type types = {
20
21
OptionsWithRum : OptionsWithRum ;
21
22
} ;
22
23
24
+ type RumAppResponse = {
25
+ data : {
26
+ attributes : {
27
+ client_token : string ;
28
+ } ;
29
+ } ;
30
+ } ;
31
+
23
32
export const getPlugins : GetPlugins < OptionsWithRum > = (
24
33
opts : OptionsWithRum ,
25
34
context : GlobalContext ,
@@ -28,9 +37,10 @@ export const getPlugins: GetPlugins<OptionsWithRum> = (
28
37
// Verify configuration.
29
38
const options = validateOptions ( opts , log ) ;
30
39
31
- if ( ! options . sdk ?. clientToken ) {
32
- // Fetch the client token from the API.
33
- }
40
+ context . inject ( {
41
+ type : 'file' ,
42
+ value : 'https://www.datadoghq-browser-agent.com/us1/v5/datadog-rum.js' ,
43
+ } ) ;
34
44
35
45
return [
36
46
{
@@ -39,6 +49,52 @@ export const getPlugins: GetPlugins<OptionsWithRum> = (
39
49
// Not supported by Rollup and ESBuild.
40
50
// https://vitejs.dev/guide/api-plugin.html#plugin-ordering
41
51
enforce : 'pre' ,
52
+ async buildStart ( ) {
53
+ if ( ! options . sdk ) {
54
+ return ;
55
+ }
56
+
57
+ if ( ! options . sdk . clientToken ) {
58
+ if ( ! context . auth ?. apiKey || ! context . auth ?. appKey ) {
59
+ throw new Error (
60
+ 'Missing auth.apiKey and/or auth.appKey to fetch clientToken.' ,
61
+ ) ;
62
+ }
63
+
64
+ const sdkOpts = options . sdk ;
65
+ let clientToken : string ;
66
+
67
+ try {
68
+ // Fetch the client token from the API.
69
+ const appResponse = await doRequest < RumAppResponse > ( {
70
+ url : `https://api.datadoghq.com/api/v2/rum/applications/${ options . sdk . applicationId } ` ,
71
+ type : 'json' ,
72
+ auth : context . auth ,
73
+ } ) ;
74
+
75
+ clientToken = appResponse . data ?. attributes ?. client_token ;
76
+ } catch ( e : any ) {
77
+ // Could not fetch the clientToken.
78
+ // Let's crash the build.
79
+ throw new Error ( `Could not fetch the clientToken: ${ e . message } ` ) ;
80
+ }
81
+
82
+ // Still no clientToken.
83
+ if ( ! clientToken ) {
84
+ throw new Error ( 'Missing clientToken in the API response.' ) ;
85
+ }
86
+
87
+ console . log ( 'INJECTING' ) ;
88
+ // Inject the initialization code.
89
+ context . inject ( {
90
+ type : 'code' ,
91
+ value : `DD_RUM.init(${ JSON . stringify ( {
92
+ clientToken,
93
+ ...sdkOpts ,
94
+ } ) } );`,
95
+ } ) ;
96
+ }
97
+ } ,
42
98
} ,
43
99
] ;
44
100
} ;
0 commit comments