1- import { describe , it , expect , beforeEach , vi , afterEach } from "vitest" ;
1+ import { describe , it , expect , beforeEach , afterEach } from "vitest" ;
22import {
33 readSavedSettings ,
44 writeSavedSettings ,
55 getRuntimeApiBase ,
66 inferHostedApiBase ,
7+ inferLocalApiBase ,
78} from "./settings" ;
89
910describe ( "readSavedSettings" , ( ) => {
@@ -68,16 +69,27 @@ describe("getRuntimeApiBase", () => {
6869 expect ( getRuntimeApiBase ( ) ) . toBe ( "http://custom:9999" ) ;
6970 } ) ;
7071
72+ it ( "does not preserve a saved local frontend origin as the API URL" , ( ) => {
73+ localStorage . setItem (
74+ "settings" ,
75+ JSON . stringify ( { apiUrl : window . location . origin } )
76+ ) ;
77+ expect ( getRuntimeApiBase ( ) ) . toBe ( "http://localhost:3000" ) ;
78+ } ) ;
79+
7180 it ( "returns env var when no saved setting" , ( ) => {
7281 process . env . NEXT_PUBLIC_API_URL = "http://env-host:8080" ;
7382 expect ( getRuntimeApiBase ( ) ) . toBe ( "http://env-host:8080" ) ;
7483 } ) ;
7584
76- it ( "falls back to window.location.origin when no saved setting or env var" , ( ) => {
77- // The key behavior: uses window.location.origin instead of hardcoding :3000.
78- // In jsdom the origin is 'http://localhost' by default.
79- const result = getRuntimeApiBase ( ) ;
80- expect ( result ) . toBe ( window . location . origin ) ;
85+ it ( "maps a local browser origin to the default backend port" , ( ) => {
86+ window . history . replaceState ( { } , "" , "/control" ) ;
87+ expect ( getRuntimeApiBase ( ) ) . toBe ( "http://localhost:3000" ) ;
88+ } ) ;
89+
90+ it ( "keeps same-origin when the local page already runs on the backend port" , ( ) => {
91+ window . history . replaceState ( { } , "" , "http://localhost:3000/control" ) ;
92+ expect ( getRuntimeApiBase ( ) ) . toBe ( "http://localhost:3000" ) ;
8193 } ) ;
8294
8395 it ( "strips trailing slash from returned URL" , ( ) => {
@@ -98,3 +110,15 @@ describe("inferHostedApiBase", () => {
98110 expect ( inferHostedApiBase ( "example.com" ) ) . toBeNull ( ) ;
99111 } ) ;
100112} ) ;
113+
114+ describe ( "inferLocalApiBase" , ( ) => {
115+ it ( "maps localhost frontend ports to :3000" , ( ) => {
116+ expect ( inferLocalApiBase ( new URL ( "http://localhost:3001/control" ) as unknown as Location ) ) . toBe (
117+ "http://localhost:3000"
118+ ) ;
119+ } ) ;
120+
121+ it ( "does not override non-local hosts" , ( ) => {
122+ expect ( inferLocalApiBase ( new URL ( "https://example.com/control" ) as unknown as Location ) ) . toBeNull ( ) ;
123+ } ) ;
124+ } ) ;
0 commit comments