Skip to content

armgit / sie

Public Imported from GitHub
0

Open-source inference server and production cluster for all the models your agent needs.

feat(sdk): default to SIE Serverless when an API key is set and no base URL is given (#691)

svonavad680237f02c2
diff --git a/packages/sie_sdk/README.md b/packages/sie_sdk/README.md
index aacbf2f1a..0898dc068 100644
--- a/packages/sie_sdk/README.md
+++ b/packages/sie_sdk/README.md
@@ -250,30 +250,44 @@ Private reasoning is hidden on both input surfaces. If it consumes the entire
generation budget without usable output, the request fails with
`empty_model_output`.
-## Connecting to a managed SIE platform
+## Connecting to SIE Serverless or a managed gateway
-The examples above target a local server. For a managed SIE gateway,
-pass the gateway URL as `base_url` and your API key (sent as a Bearer
-token):
+The examples above target a local server. Given an API key and no base URL,
+the client connects to SIE Serverless at `https://api.superlinked.com`:
```python
from sie_sdk import SIEClient
+client = SIEClient() # reads SIE_API_KEY
+```
+
+`SIEClient(api_key="sk-sie-...")` does the same with an explicit key. Keys
+issued for the EU region use `https://eu.api.superlinked.com`; set
+`SIE_BASE_URL` to it. Set `SIE_BASE_URL` alongside a key for your own gateway
+too, or `SIEClient()` sends that key to SIE Serverless. For another SIE
+gateway, pass its URL as `base_url` and your API key (sent as a Bearer token):
+
+```python
client = SIEClient(
"https://your-gateway.example.com",
api_key="YOUR_API_KEY",
)
```
-When `base_url` is omitted, the client reads `SIE_BASE_URL`. When `api_key` is
-omitted, it selects `SIE_API_KEY` only for a base URL with the same origin as
-`SIE_BASE_URL`; a client for any other URL does not pick it up. Set both
-variables to let code and integrations that construct a client without
-credentials use a gateway with token auth. An explicit argument always wins;
-`api_key=""` sends no credential. The `connections` namespace reuses the
-client's key on requests to an explicitly configured `control_plane_url`, so a
-client whose `control_plane_url` is on another origin must pass `api_key`
-explicitly rather than rely on `SIE_API_KEY`.
+The client takes its base URL from `base_url`, then `SIE_BASE_URL`, then SIE
+Serverless when an API key is available (`api_key`, or `SIE_API_KEY` when
+`api_key` is omitted). With none of these it raises `ValueError`; it does not
+assume a local server, so pass `"http://localhost:8080"` or set `SIE_BASE_URL`
+for one. When `api_key` is omitted, the client selects `SIE_API_KEY` only for a
+base URL with the same origin as `SIE_BASE_URL`, or as SIE Serverless while
+`SIE_BASE_URL` is unset; a client for any other URL, such as
+`http://localhost:8080`, does not pick it up. Set both variables to let code
+and integrations that construct a client without credentials use a gateway
+with token auth. An explicit argument always wins; `api_key=""` sends no
+credential and does not select SIE Serverless. The `connections` namespace
+reuses the client's key on requests to an explicitly configured
+`control_plane_url`, so a client whose `control_plane_url` is on another
+origin must pass `api_key` explicitly rather than rely on `SIE_API_KEY`.
## Generation execution evidence
diff --git a/packages/sie_sdk/src/sie_sdk/client/_shared.py b/packages/sie_sdk/src/sie_sdk/client/_shared.py
index 10ad74a67..4e599623e 100644
--- a/packages/sie_sdk/src/sie_sdk/client/_shared.py
+++ b/packages/sie_sdk/src/sie_sdk/client/_shared.py
@@ -146,17 +146,33 @@ def validate_base_url(base_url: str) -> None:
SIE_BASE_URL_ENV = "SIE_BASE_URL"
SIE_API_KEY_ENV = "SIE_API_KEY"
+# SIE Serverless: the base URL of a client given an API key but no base URL,
+# and the origin ``SIE_API_KEY`` is scoped to while ``SIE_BASE_URL`` is unset.
+SIE_SERVERLESS_BASE_URL = "https://api.superlinked.com"
-def resolve_base_url(base_url: str | None) -> str:
- """Return ``base_url``, or the ``SIE_BASE_URL`` environment variable when it is omitted."""
+def resolve_base_url(base_url: str | None, api_key: str | None = None) -> str:
+ """Return the base URL a client connects to.
+
+ Precedence: ``base_url``, then the ``SIE_BASE_URL`` environment variable,
+ then SIE Serverless when an API key is available: a non-empty ``api_key``,
+ or ``SIE_API_KEY`` when ``api_key`` is omitted. Without any of these,
+ construction fails instead of guessing a local server, so a deployment
+ missing its key reports that at once rather than retrying connections.
+ """
if base_url is not None:
return base_url
env_base_url = os.environ.get(SIE_BASE_URL_ENV, "").strip()
- if not env_base_url:
- msg = f"base_url is required: pass it explicitly or set {SIE_BASE_URL_ENV}"
- raise ValueError(msg)
- return env_base_url
+ if env_base_url:
+ return env_base_url
+ has_api_key = bool(api_key) if api_key is not None else bool(os.environ.get(SIE_API_KEY_ENV, "").strip())
+ if has_api_key:
+ return SIE_SERVERLESS_BASE_URL
+ msg = (
+ f"base_url is required: pass it explicitly, set {SIE_BASE_URL_ENV}, "
+ f"or set {SIE_API_KEY_ENV} to use SIE Serverless ({SIE_SERVERLESS_BASE_URL})"
+ )
+ raise ValueError(msg)
def _url_origin(url: str) -> tuple[str, str, int] | None:
@@ -176,21 +192,22 @@ def resolve_api_key(api_key: str | None, base_url: str, control_plane_url: str |
An explicit value, including an empty string, always wins, so a caller can
opt out of the environment credential. The environment key is scoped to
- the origin named by ``SIE_BASE_URL``: a client built for any other URL
- does not select it, and a client whose ``control_plane_url`` names another
- origin must pass its key explicitly, because connection requests reuse the
+ the origin named by ``SIE_BASE_URL``, or to SIE Serverless while
+ ``SIE_BASE_URL`` is unset: a client built for any other URL does not
+ select it, and a client whose ``control_plane_url`` names another origin
+ must pass its key explicitly, because connection requests reuse the
client's key.
"""
if api_key is not None:
return api_key
env_api_key = os.environ.get(SIE_API_KEY_ENV, "").strip()
- env_origin = _url_origin(os.environ.get(SIE_BASE_URL_ENV, "").strip())
+ env_origin = _url_origin(os.environ.get(SIE_BASE_URL_ENV, "").strip() or SIE_SERVERLESS_BASE_URL)
if not env_api_key or env_origin is None or _url_origin(base_url) != env_origin:
return None
if control_plane_url and _url_origin(control_plane_url) != env_origin:
msg = (
- f"{SIE_API_KEY_ENV} is scoped to the {SIE_BASE_URL_ENV} origin and is not sent to "
- "control_plane_url on another origin; pass api_key explicitly"
+ f"{SIE_API_KEY_ENV} is scoped to the {SIE_BASE_URL_ENV} origin (SIE Serverless when unset) "
+ "and is not sent to control_plane_url on another origin; pass api_key explicitly"
)
raise ValueError(msg)
return env_api_key
diff --git a/packages/sie_sdk/src/sie_sdk/client/async_.py b/packages/sie_sdk/src/sie_sdk/client/async_.py
index 4ceb43c3f..8ae83ed15 100644
--- a/packages/sie_sdk/src/sie_sdk/client/async_.py
+++ b/packages/sie_sdk/src/sie_sdk/client/async_.py
@@ -426,14 +426,18 @@ class SIEAsyncClient:
Args:
base_url: Base URL of the SIE server (e.g., "http://localhost:8080").
- Defaults to the ``SIE_BASE_URL`` environment variable when omitted.
+ When omitted, the ``SIE_BASE_URL`` environment variable is used;
+ without it, SIE Serverless (``https://api.superlinked.com``) is
+ used when an API key is available (``api_key`` or ``SIE_API_KEY``).
+ With neither a base URL nor a key, construction raises ``ValueError``.
timeout_s: One per-attempt limit in seconds for both connecting and
waiting for response data. Sets ``connect_timeout_s`` and
``read_timeout_s`` together; either of those overrides it.
api_key: Optional API key for authentication (sent as Bearer token).
When omitted, the ``SIE_API_KEY`` environment variable is used only if
``base_url`` has the same origin as ``SIE_BASE_URL`` (including when
- ``base_url`` itself comes from ``SIE_BASE_URL``); with a
+ ``base_url`` itself comes from ``SIE_BASE_URL``), or the SIE
+ Serverless origin while ``SIE_BASE_URL`` is unset; with a
``control_plane_url`` on another origin the key must be passed
explicitly. Pass ``""`` to send no credential.
gpu: GPU type for requests (e.g., "l4", "a100-80gb"). Can be overridden per-call.
@@ -500,7 +504,7 @@ class SIEAsyncClient:
read_timeout_s: float | None = None,
remote: Literal["forbid"] | None = None,
) -> None:
- base_url = resolve_base_url(base_url)
+ base_url = resolve_base_url(base_url, api_key)
api_key = resolve_api_key(api_key, base_url, control_plane_url)
# Normalize base_url (remove trailing slash)
validate_base_url(base_url)
diff --git a/packages/sie_sdk/src/sie_sdk/client/sync.py b/packages/sie_sdk/src/sie_sdk/client/sync.py
index f31e36827..4d4c8c4eb 100644
--- a/packages/sie_sdk/src/sie_sdk/client/sync.py
+++ b/packages/sie_sdk/src/sie_sdk/client/sync.py
@@ -401,14 +401,18 @@ class SIEClient:
Args:
base_url: Base URL of the SIE server (e.g., "http://localhost:8080").
- Defaults to the ``SIE_BASE_URL`` environment variable when omitted.
+ When omitted, the ``SIE_BASE_URL`` environment variable is used;
+ without it, SIE Serverless (``https://api.superlinked.com``) is
+ used when an API key is available (``api_key`` or ``SIE_API_KEY``).
+ With neither a base URL nor a key, construction raises ``ValueError``.
timeout_s: One per-attempt limit in seconds for both connecting and
waiting for response data. Sets ``connect_timeout_s`` and
``read_timeout_s`` together; either of those overrides it.
api_key: Optional API key for authentication (sent as Bearer token).
When omitted, the ``SIE_API_KEY`` environment variable is used only if
``base_url`` has the same origin as ``SIE_BASE_URL`` (including when
- ``base_url`` itself comes from ``SIE_BASE_URL``); with a
+ ``base_url`` itself comes from ``SIE_BASE_URL``), or the SIE
+ Serverless origin while ``SIE_BASE_URL`` is unset; with a
``control_plane_url`` on another origin the key must be passed
explicitly. Pass ``""`` to send no credential.
gpu: Default GPU/machine profile for requests (e.g., "l4", "l4-spot").
@@ -487,7 +491,7 @@ class SIEClient:
remote: Literal["forbid"] | None = None,
http_client: httpx.Client | None = None,
) -> None:
- base_url = resolve_base_url(base_url)
+ base_url = resolve_base_url(base_url, api_key)
api_key = resolve_api_key(api_key, base_url, control_plane_url)
# Normalize base_url (remove trailing slash)
validate_base_url(base_url)
diff --git a/packages/sie_sdk/tests/client/test_env_credentials.py b/packages/sie_sdk/tests/client/test_env_credentials.py
index 4a411d0fb..cee873b0c 100644
--- a/packages/sie_sdk/tests/client/test_env_credentials.py
+++ b/packages/sie_sdk/tests/client/test_env_credentials.py
@@ -1,4 +1,4 @@
-"""``SIE_BASE_URL`` and ``SIE_API_KEY`` fallbacks for both client constructors."""
+"""``SIE_BASE_URL`` and ``SIE_API_KEY`` fallbacks, and the SIE Serverless default, for both client constructors."""
from __future__ import annotations
@@ -84,6 +84,9 @@ def test_sync_client_sends_env_key_to_the_env_base_url_origin(
("https://gateway.example.com", "http://gateway.example.com"),
("https://gateway.example.com", "https://gateway.example.com:8443"),
("not a url", "https://gateway.example.com"),
+ (None, "http://api.superlinked.com"),
+ (None, "https://api.superlinked.com:8443"),
+ (None, "https://api.superlinked.com.example.com"),
],
)
def test_sync_client_withholds_env_key_from_other_origins(
@@ -174,6 +177,100 @@ def test_clients_require_a_base_url(monkeypatch: pytest.MonkeyPatch, env_value:
SIEAsyncClient()
+SERVERLESS = "https://api.superlinked.com"
+
+
+def test_sync_client_defaults_to_serverless_with_env_key(
+ monkeypatch: pytest.MonkeyPatch, sync_headers: dict[str, Any]
+) -> None:
+ monkeypatch.setenv("SIE_API_KEY", "env-key")
+
+ client = SIEClient()
+
+ assert client.base_url == SERVERLESS
+ assert sync_headers["base_url"] == SERVERLESS
+ assert sync_headers["headers"]["Authorization"] == "Bearer env-key"
+
+
+def test_sync_client_defaults_to_serverless_with_explicit_key(sync_headers: dict[str, Any]) -> None:
+ client = SIEClient(api_key="explicit-key")
+
+ assert client.base_url == SERVERLESS
+ assert sync_headers["headers"]["Authorization"] == "Bearer explicit-key"
+
+
+def test_sync_client_prefers_env_base_url_over_serverless(
+ monkeypatch: pytest.MonkeyPatch, sync_headers: dict[str, Any]
+) -> None:
+ monkeypatch.setenv("SIE_BASE_URL", "http://localhost:8080")
+ monkeypatch.setenv("SIE_API_KEY", "env-key")
+
+ client = SIEClient()
+
+ assert client.base_url == "http://localhost:8080"
+ assert sync_headers["headers"]["Authorization"] == "Bearer env-key"
+
+
+def test_sync_client_explicit_local_base_url_keeps_env_key_for_serverless(
+ monkeypatch: pytest.MonkeyPatch, sync_headers: dict[str, Any]
+) -> None:
+ monkeypatch.setenv("SIE_API_KEY", "env-key")
+
+ client = SIEClient("http://localhost:8080")
+
+ assert client.base_url == "http://localhost:8080"
+ assert "Authorization" not in sync_headers["headers"]
+
+
[email protected]("base_url", [SERVERLESS, f"{SERVERLESS}/", "https://API.superlinked.com:443"])
+def test_sync_client_sends_env_key_to_serverless_while_env_base_url_is_unset(
+ monkeypatch: pytest.MonkeyPatch, sync_headers: dict[str, Any], base_url: str
+) -> None:
+ monkeypatch.setenv("SIE_API_KEY", "env-key")
+
+ SIEClient(base_url)
+
+ assert sync_headers["headers"]["Authorization"] == "Bearer env-key"
+
+
+def test_sync_client_scopes_env_key_to_env_base_url_not_serverless(
+ monkeypatch: pytest.MonkeyPatch, sync_headers: dict[str, Any]
+) -> None:
+ monkeypatch.setenv("SIE_BASE_URL", "https://gateway.example.com")
+ monkeypatch.setenv("SIE_API_KEY", "env-key")
+
+ SIEClient(SERVERLESS)
+
+ assert "Authorization" not in sync_headers["headers"]
+
+
+def test_clients_without_a_key_name_serverless_in_the_error(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_API_KEY", " ")
+ with pytest.raises(ValueError, match=r"SIE_API_KEY to use SIE Serverless \(https://api\.superlinked\.com\)"):
+ SIEClient()
+ with pytest.raises(ValueError, match="SIE_API_KEY"):
+ SIEAsyncClient()
+
+
+def test_clients_with_an_empty_api_key_do_not_default_to_serverless(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_API_KEY", "env-key")
+ with pytest.raises(ValueError, match="base_url is required"):
+ SIEClient(api_key="")
+ with pytest.raises(ValueError, match="base_url is required"):
+ SIEAsyncClient(api_key="")
+
+
+def test_clients_scope_the_serverless_env_key_away_from_a_cross_origin_control_plane(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("SIE_API_KEY", "env-key")
+
+ with pytest.raises(ValueError, match="control_plane_url"):
+ SIEClient(control_plane_url="https://control.example.com")
+ with pytest.raises(ValueError, match="control_plane_url"):
+ SIEAsyncClient(control_plane_url="https://control.example.com")
+
+
def test_clients_validate_the_env_base_url(monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setenv("SIE_BASE_URL", "localhost:8080")
with pytest.raises(ValueError, match="http:// or https://"):
@@ -227,3 +324,37 @@ async def test_async_client_empty_api_key_opts_out_of_env_key(monkeypatch: pytes
kwargs = await _async_session_kwargs(SIEAsyncClient("http://localhost:8080", api_key=""))
assert "Authorization" not in kwargs["headers"]
+
+
+async def test_async_client_defaults_to_serverless_with_env_key(monkeypatch: pytest.MonkeyPatch) -> None:
+ monkeypatch.setenv("SIE_API_KEY", "env-key")
+
+ client = SIEAsyncClient()
+ kwargs = await _async_session_kwargs(client)
+
+ assert client.base_url == SERVERLESS
+ assert kwargs["base_url"] == SERVERLESS
+ assert kwargs["headers"]["Authorization"] == "Bearer env-key"
+
+
+async def test_async_client_defaults_to_serverless_with_explicit_key() -> None:
+ client = SIEAsyncClient(api_key="explicit-key")
+ kwargs = await _async_session_kwargs(client)
+
+ assert client.base_url == SERVERLESS
+ assert kwargs["headers"]["Authorization"] == "Bearer explicit-key"
+
+
+async def test_async_client_explicit_local_base_url_keeps_env_key_for_serverless(
+ monkeypatch: pytest.MonkeyPatch,
+) -> None:
+ monkeypatch.setenv("SIE_API_KEY", "env-key")
+
+ client = SIEAsyncClient("http://localhost:8080")
+ kwargs = await _async_session_kwargs(client)
+
+ assert client.base_url == "http://localhost:8080"
+ assert "Authorization" not in kwargs["headers"]
diff --git a/packages/sie_ts_sdk/README.md b/packages/sie_ts_sdk/README.md
index 34b814778..2a40abfea 100644
--- a/packages/sie_ts_sdk/README.md
+++ b/packages/sie_ts_sdk/README.md
@@ -14,23 +14,36 @@ npm install @superlinked/sie-sdk
```typescript
import { SIEClient } from "@superlinked/sie-sdk";
+// SIE Serverless (https://api.superlinked.com). Server-side only, see below.
+const client = new SIEClient(); // reads SIE_API_KEY
+
// Local server
-const client = new SIEClient("http://localhost:8080");
+const local = new SIEClient("http://localhost:8080");
-// Managed SIE gateway: pass the gateway URL and your API key
+// Another SIE gateway: pass its URL and your API key
// (sent as a Bearer token). Server-side code only — see below.
const managed = new SIEClient("https://your-gateway.example.com", {
apiKey: "YOUR_API_KEY",
});
```
-In Node.js, an omitted `baseUrl` falls back to `SIE_BASE_URL`. An omitted
-`apiKey` selects `SIE_API_KEY` only for a base URL with the same origin as
-`SIE_BASE_URL`; a client for any other URL does not pick it up. An explicit
-value always wins; `apiKey: ""` sends no credential. The `connections`
-namespace reuses the client's key on requests to an explicitly configured
-`controlPlaneUrl`, so a client whose `controlPlaneUrl` is on another origin
-must pass `apiKey` explicitly rather than rely on `SIE_API_KEY`.
+The client takes its base URL from `baseUrl`, then `SIE_BASE_URL` (in
+Node.js), then SIE Serverless when an API key is available (`apiKey`, or
+`SIE_API_KEY` when `apiKey` is omitted), so
+`new SIEClient(undefined, { apiKey })` also targets SIE Serverless. With none
+of these it throws a `TypeError`; it does not assume a local server. Keys
+issued for the EU region use `https://eu.api.superlinked.com`; set
+`SIE_BASE_URL` to it. Set `SIE_BASE_URL` alongside a key for your own gateway
+too, or `new SIEClient()` sends that key to SIE Serverless.
+
+An omitted `apiKey` selects `SIE_API_KEY` only for a base URL with the same
+origin as `SIE_BASE_URL`, or as SIE Serverless while `SIE_BASE_URL` is unset;
+a client for any other URL, such as `http://localhost:8080`, does not pick it
+up. An explicit value always wins; `apiKey: ""` sends no credential and does
+not select SIE Serverless. The `connections` namespace reuses the client's key
+on requests to an explicitly configured `controlPlaneUrl`, so a client whose
+`controlPlaneUrl` is on another origin must pass `apiKey` explicitly rather
+than rely on `SIE_API_KEY`.
> **Warning:** only pass `apiKey` in server-side code. Shipping it in a
> browser bundle exposes the bearer key to anyone who loads the page.
diff --git a/packages/sie_ts_sdk/src/client.ts b/packages/sie_ts_sdk/src/client.ts
index 06ea082e8..e0934d645 100644
--- a/packages/sie_ts_sdk/src/client.ts
+++ b/packages/sie_ts_sdk/src/client.ts
@@ -342,6 +342,11 @@ function sleep(ms: number): Promise<void> {
const SIE_BASE_URL_ENV = "SIE_BASE_URL";
const SIE_API_KEY_ENV = "SIE_API_KEY";
+/**
+ * SIE Serverless: the base URL of a client given an API key but no base URL,
+ * and the origin `SIE_API_KEY` is scoped to while `SIE_BASE_URL` is unset.
+ */
+const SIE_SERVERLESS_BASE_URL = "https://api.superlinked.com";
/**
* Read a non-blank environment variable. Undefined outside Node-like runtimes
@@ -367,19 +372,44 @@ function urlOrigin(url: string): string | undefined {
}
/**
- * `SIE_API_KEY`, scoped to the origin named by `SIE_BASE_URL`. Connection
- * requests reuse the client's key, so a control-plane URL on another origin
- * requires an explicit key.
+ * The base URL a client connects to: `baseUrl`, then `SIE_BASE_URL`, then SIE
+ * Serverless when an API key is available (a non-empty `apiKey`, or
+ * `SIE_API_KEY` when `apiKey` is omitted). Without any of these, construction
+ * fails instead of guessing a local server, so a deployment missing its key
+ * reports that at once rather than retrying connections.
+ */
+function resolveBaseUrl(baseUrl: string | undefined, apiKey: string | undefined): string {
+ if (baseUrl !== undefined) {
+ return baseUrl;
+ }
+ const envBaseUrl = readEnv(SIE_BASE_URL_ENV);
+ if (envBaseUrl !== undefined) {
+ return envBaseUrl;
+ }
+ const hasApiKey = apiKey !== undefined ? apiKey !== "" : readEnv(SIE_API_KEY_ENV) !== undefined;
+ if (hasApiKey) {
+ return SIE_SERVERLESS_BASE_URL;
+ }
+ throw new TypeError(
+ `baseUrl is required: pass it explicitly, set ${SIE_BASE_URL_ENV}, or set ${SIE_API_KEY_ENV} to use SIE Serverless (${SIE_SERVERLESS_BASE_URL}).`,
+ );
+}
+
+/**
+ * `SIE_API_KEY`, scoped to the origin named by `SIE_BASE_URL`, or to SIE
+ * Serverless while `SIE_BASE_URL` is unset. Connection requests reuse the
+ * client's key, so a control-plane URL on another origin requires an explicit
+ * key.
*/
function envApiKeyFor(baseUrl: string, controlPlaneUrl: string | undefined): string | undefined {
const apiKey = readEnv(SIE_API_KEY_ENV);
- const envOrigin = urlOrigin(readEnv(SIE_BASE_URL_ENV) ?? "");
+ const envOrigin = urlOrigin(readEnv(SIE_BASE_URL_ENV) ?? SIE_SERVERLESS_BASE_URL);
if (!apiKey || envOrigin === undefined || urlOrigin(baseUrl) !== envOrigin) {
return undefined;
}
if (controlPlaneUrl && urlOrigin(controlPlaneUrl) !== envOrigin) {
throw new TypeError(
- `${SIE_API_KEY_ENV} is scoped to the ${SIE_BASE_URL_ENV} origin and is not sent to controlPlaneUrl on another origin; pass apiKey explicitly.`,
+ `${SIE_API_KEY_ENV} is scoped to the ${SIE_BASE_URL_ENV} origin (SIE Serverless when unset) and is not sent to controlPlaneUrl on another origin; pass apiKey explicitly.`,
);
}
return apiKey;
@@ -911,14 +941,14 @@ export class SIEClient {
* Create a new SIE client.
*
* @param baseUrl - Base URL of the SIE server (e.g., "http://localhost:8080").
- * Defaults to the `SIE_BASE_URL` environment variable when omitted.
+ * When omitted, the `SIE_BASE_URL` environment variable is used; without
+ * it, SIE Serverless (`https://api.superlinked.com`) is used when an API
+ * key is available (`options.apiKey` or `SIE_API_KEY`). With neither a
+ * base URL nor a key, construction throws a `TypeError`.
* @param options - Client options
*/
constructor(baseUrl?: string, options: SIEClientOptions = {}) {
- const url = baseUrl ?? readEnv(SIE_BASE_URL_ENV);
- if (url === undefined) {
- throw new TypeError(`baseUrl is required: pass it explicitly or set ${SIE_BASE_URL_ENV}.`);
- }
+ const url = resolveBaseUrl(baseUrl, options.apiKey);
// Validate eagerly: a scheme-less baseUrl ("localhost:8080") would
// otherwise only surface at request time as a fetch `TypeError`.
let parsed: URL | undefined;
diff --git a/packages/sie_ts_sdk/src/types.ts b/packages/sie_ts_sdk/src/types.ts
index 45c45dbbd..e9b84cc22 100644
--- a/packages/sie_ts_sdk/src/types.ts
+++ b/packages/sie_ts_sdk/src/types.ts
@@ -875,8 +875,10 @@ export interface SIEClientOptions {
* API key for authentication (sent as Bearer token). When omitted, the
* `SIE_API_KEY` environment variable is used only if the base URL has the
* same origin as `SIE_BASE_URL` (including when the base URL itself comes
- * from `SIE_BASE_URL`); with a `controlPlaneUrl` on another origin the key
- * must be passed explicitly. Pass `""` to send no credential.
+ * from `SIE_BASE_URL`), or the SIE Serverless origin
+ * (`https://api.superlinked.com`) while `SIE_BASE_URL` is unset; with a
+ * `controlPlaneUrl` on another origin the key must be passed explicitly.
+ * Pass `""` to send no credential.
*/
apiKey?: string;
/**
diff --git a/packages/sie_ts_sdk/tests/envCredentials.test.ts b/packages/sie_ts_sdk/tests/envCredentials.test.ts
index 5fc4002a1..34a0cdcec 100644
--- a/packages/sie_ts_sdk/tests/envCredentials.test.ts
+++ b/packages/sie_ts_sdk/tests/envCredentials.test.ts
@@ -1,5 +1,6 @@
/**
- * `SIE_BASE_URL` and `SIE_API_KEY` fallbacks for the client constructor.
+ * `SIE_BASE_URL` and `SIE_API_KEY` fallbacks, and the SIE Serverless default,
+ * for the client constructor.
*/
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -70,6 +71,9 @@ describe("SIEClient environment fallbacks", () => {
["https://gateway.example.test", "http://gateway.example.test"],
["https://gateway.example.test", "https://gateway.example.test:8443"],
["not a url", "https://gateway.example.test"],
+ ["", "http://api.superlinked.com"],
+ ["", "https://api.superlinked.com:8443"],
+ ["", "https://api.superlinked.com.example.test"],
])(
"withholds SIE_API_KEY when SIE_BASE_URL is %j and the base URL is %s",
async (envBaseUrl, baseUrl) => {
@@ -158,3 +162,90 @@ describe("SIEClient environment fallbacks", () => {
expect(() => new SIEClient()).toThrow(/must be an absolute http\(s\) URL/);
});
});
+
+describe("SIEClient SIE Serverless default", () => {
+ const SERVERLESS = "https://api.superlinked.com";
+
+ beforeEach(() => {
+ mockFetch.mockReset();
+ vi.stubEnv("SIE_BASE_URL", "");
+ vi.stubEnv("SIE_API_KEY", "");
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it("targets SIE Serverless with SIE_API_KEY and no base URL", async () => {
+ vi.stubEnv("SIE_API_KEY", "env-key");
+
+ const client = new SIEClient();
+
+ expect(client.getBaseUrl()).toBe(SERVERLESS);
+ expect(await encodeAuthorization(client)).toBe("Bearer env-key");
+ });
+
+ it("targets SIE Serverless with an explicit apiKey and no base URL", async () => {
+ const client = new SIEClient(undefined, { apiKey: "explicit-key" });
+
+ expect(client.getBaseUrl()).toBe(SERVERLESS);
+ expect(await encodeAuthorization(client)).toBe("Bearer explicit-key");
+ });
+
+ it("prefers SIE_BASE_URL over SIE Serverless", async () => {
+ vi.stubEnv("SIE_BASE_URL", "http://localhost:8080");
+ vi.stubEnv("SIE_API_KEY", "env-key");
+
+ const client = new SIEClient();
+
+ expect(client.getBaseUrl()).toBe("http://localhost:8080");
+ expect(await encodeAuthorization(client)).toBe("Bearer env-key");
+ });
+
+ it("keeps SIE_API_KEY away from an explicit local base URL", async () => {
+ vi.stubEnv("SIE_API_KEY", "env-key");
+
+ const client = new SIEClient("http://localhost:8080");
+
+ expect(client.getBaseUrl()).toBe("http://localhost:8080");
+ expect(await encodeAuthorization(client)).toBeUndefined();
+ });
+
+ it.each([SERVERLESS, `${SERVERLESS}/`, "https://API.superlinked.com:443"])(
+ "sends SIE_API_KEY to SIE Serverless while SIE_BASE_URL is unset (%s)",
+ async (baseUrl) => {
+ vi.stubEnv("SIE_API_KEY", "env-key");
+
+ expect(await encodeAuthorization(new SIEClient(baseUrl))).toBe("Bearer env-key");
+ },
+ );
+
+ it("scopes SIE_API_KEY to SIE_BASE_URL, not SIE Serverless, when both are set", async () => {
+ vi.stubEnv("SIE_BASE_URL", "https://gateway.example.test");
+ vi.stubEnv("SIE_API_KEY", "env-key");
+
+ expect(await encodeAuthorization(new SIEClient(SERVERLESS))).toBeUndefined();
+ });
+
+ it("names SIE Serverless in the error when no key is available", () => {
+ vi.stubEnv("SIE_API_KEY", " ");
+
+ expect(() => new SIEClient()).toThrow(
+ /SIE_API_KEY to use SIE Serverless \(https:\/\/api\.superlinked\.com\)/,
+ );
+ });
+
+ it("does not default to SIE Serverless for an explicit empty apiKey", () => {
+ vi.stubEnv("SIE_API_KEY", "env-key");
+
+ expect(() => new SIEClient(undefined, { apiKey: "" })).toThrow(/baseUrl is required/);
+ });
+
+ it("requires an explicit key for a controlPlaneUrl off the SIE Serverless origin", () => {
+ vi.stubEnv("SIE_API_KEY", "env-key");
+
+ expect(
+ () => new SIEClient(undefined, { controlPlaneUrl: "https://control.example.test" }),
+ ).toThrow(/controlPlaneUrl/);
+ });
+});