@@ -45,6 +45,9 @@ class FetchResponse {
4545 get isTurboStream ( ) {
4646 return this . contentType . match ( / ^ t e x t \/ v n d \. t u r b o - s t r e a m \. h t m l / ) ;
4747 }
48+ get isScript ( ) {
49+ return this . contentType . match ( / \b (?: j a v a | e c m a ) s c r i p t \b / ) ;
50+ }
4851 async renderTurboStream ( ) {
4952 if ( this . isTurboStream ) {
5053 if ( window . Turbo ) {
@@ -56,6 +59,20 @@ class FetchResponse {
5659 return Promise . reject ( new Error ( `Expected a Turbo Stream response but got "${ this . contentType } " instead` ) ) ;
5760 }
5861 }
62+ async activeScript ( ) {
63+ if ( this . isScript ) {
64+ const script = document . createElement ( "script" ) ;
65+ const metaTag = document . querySelector ( "meta[name=csp-nonce]" ) ;
66+ const nonce = metaTag && metaTag . content ;
67+ if ( nonce ) {
68+ script . setAttribute ( "nonce" , nonce ) ;
69+ }
70+ script . innerHTML = await this . text ;
71+ document . body . appendChild ( script ) ;
72+ } else {
73+ return Promise . reject ( new Error ( `Expected a Script response but got "${ this . contentType } " instead` ) ) ;
74+ }
75+ }
5976}
6077
6178class RequestInterceptor {
@@ -129,10 +146,14 @@ class FetchRequest {
129146 } catch ( error ) {
130147 console . error ( error ) ;
131148 }
132- const response = new FetchResponse ( await window . fetch ( this . url , this . fetchOptions ) ) ;
149+ const fetch = this . responseKind === "turbo-stream" && window . Turbo ? window . Turbo . fetch : window . fetch ;
150+ const response = new FetchResponse ( await fetch ( this . url , this . fetchOptions ) ) ;
133151 if ( response . unauthenticated && response . authenticationURL ) {
134152 return Promise . reject ( window . location . href = response . authenticationURL ) ;
135153 }
154+ if ( response . isScript ) {
155+ await response . activeScript ( ) ;
156+ }
136157 const responseStatusIsTurboStreamable = response . ok || response . unprocessableEntity ;
137158 if ( responseStatusIsTurboStreamable && response . isTurboStream ) {
138159 await response . renderTurboStream ( ) ;
@@ -199,6 +220,9 @@ class FetchRequest {
199220 case "json" :
200221 return "application/json, application/vnd.api+json" ;
201222
223+ case "script" :
224+ return "text/javascript, application/javascript" ;
225+
202226 default :
203227 return "*/*" ;
204228 }
0 commit comments