Skip to content

feat: Isomorphic SDKs#1511

Closed
ChiragAgg5k wants to merge 41 commits intomasterfrom
feat/apple-client-auth-factories
Closed

feat: Isomorphic SDKs#1511
ChiragAgg5k wants to merge 41 commits intomasterfrom
feat/apple-client-auth-factories

Conversation

@ChiragAgg5k
Copy link
Copy Markdown
Member

@ChiragAgg5k ChiragAgg5k commented May 6, 2026

Summary

Implements the isomorphic SDK client pattern across the generated Web, Flutter, and Apple SDKs. Each SDK now exposes explicit auth factory methods for the recommended setup path while preserving the existing Client() constructor and setter style for backwards compatibility.

This consolidates the work from #1481, #1510, and #1511 into one PR.

Web SDK

The generated Web SDK now uses one typed generic Client across browser, server, and console output. Static factories describe both runtime and auth capability, and generated services narrow their available methods from the client auth type.

import { Client, Account, TablesDB } from 'appwrite';

const browserClient = Client.fromBrowser({
  endpoint: 'https://<REGION>.cloud.appwrite.io/v1',
  projectId: '<PROJECT_ID>',
});

const serverClient = Client.fromAPIKey({
  endpoint: 'https://<REGION>.cloud.appwrite.io/v1',
  projectId: '<PROJECT_ID>',
  apiKey: '<API_KEY>',
});

new Account(browserClient);              // OK
new TablesDB(browserClient).createRow;   // OK
new TablesDB(browserClient).createTable; // Type error for browser auth
new TablesDB(serverClient).createTable;  // OK

Available Web factories include fromBrowser, fromSession, fromDevKey, fromImpersonation, fromAPIKey, fromJWT, and fromCookie, with server-only factories omitted from client-platform output.

Flutter SDK

The generated Flutter client SDK now exposes a ClientAuth interface returned by factory-created clients. Services and Realtime accept ClientAuth, so the construction syntax stays the same while legacy setters are hidden from factory-created clients.

import 'package:appwrite/appwrite.dart';

final client = Client.fromBrowser(
  endPoint: 'https://<REGION>.cloud.appwrite.io/v1',
  projectId: '<PROJECT_ID>',
);

Account(client);      // OK
Realtime(client);     // OK
client.setProject('other'); // Analyzer error

Available Flutter factories are fromBrowser, fromSession, fromDevKey, and fromImpersonation. This is intentionally scoped to Flutter client output and does not add server auth factories to Flutter.

Apple SDK

The generated Apple SDK now exposes a ClientAuth protocol returned by factory-created clients. Generated services and Realtime accept ClientAuth, and services read auth values through getConfig(key:) instead of exposing the raw config dictionary.

let client = Client.fromBrowser(
    projectId: "<PROJECT_ID>"
)

let sessionClient = Client.fromSession(
    projectId: "<PROJECT_ID>",
    session: "<SESSION>"
)

let tables = TablesDB(client)
let realtime = Realtime(client)

Available Apple factories are fromBrowser, fromSession, fromDevKey, and throwing fromImpersonation. All factories accept optional endpoint, realtime endpoint, locale, self-signed, and compression values. fromImpersonation throws an AppwriteError when callers pass zero or multiple impersonation targets.

Backwards Compatibility

Existing constructor/setter setup remains supported in all three SDKs:

const webClient = new Client()
  .setEndpoint('https://<REGION>.cloud.appwrite.io/v1')
  .setProject('<PROJECT_ID>');
final flutterClient = Client()
  ..setEndpoint('https://<REGION>.cloud.appwrite.io/v1')
  ..setProject('<PROJECT_ID>');
let appleClient = Client()
    .setEndpoint("https://cloud.appwrite.io/v1")
    .setProject("<PROJECT_ID>")

Those legacy setters are marked deprecated and remain available from direct Client() instances. Factory-created clients intentionally expose the narrower auth surface.

Implementation Notes

  • Adds auth capability typing and static factories to Web, Flutter, and Apple client templates.
  • Keeps service construction syntax unchanged across all three SDKs.
  • Hides service .client internals from the public generated service surface.
  • Updates Realtime templates to accept factory-created clients.
  • Marks legacy setters as deprecated without removing them.
  • Generates Web factory base params from spec-backed global headers instead of hardcoded template branches.
  • Adds SDK build validation coverage for the combined generated surfaces.

Validation

Ran on the consolidated branch:

php example.php web server
php example.php web client
php example.php web console
php example.php flutter client
php example.php apple client
composer lint-twig
php -l src/SDK/Language/Web.php
php -l src/SDK/Language/Flutter.php
php -l src/SDK/Language/Apple.php
git diff --check origin/master...HEAD

Adds a ServerClient sibling class to the web SDK alongside the existing
Client. Service classes are generic over `Client | ServerClient` when
they have any client-tier methods, with TypeScript `this`-types gating
admin methods (e.g. `Databases.createCollection` requires
`Databases<ServerClient>`). Services with no client-tier methods
(Health, Tokens, Sites, Users) are non-generic and require a
ServerClient at construction.

Tier detection is driven entirely off existing `x-appwrite.platforms`
spec tags. The existing Client surface is unchanged — purely additive
for current `appwrite` web users; sets up the path to consolidate
`appwrite` + `node-appwrite` into a single isomorphic package.

- Filter `Key` out of Client header iterations so Client cannot setKey
- Add server-client.ts.twig (setKey/setJWT/setLocale + HTTP plumbing,
  no realtime, no session/devkey/impersonate)
- Type-gate service methods via `this: Service<ServerClient>` (or
  `<Client>` for the few client-only methods like webAuth/location)
- Re-export ServerClient from index.ts
- Register the new template in Web.php getFiles()

Verified on regenerated examples/web/: tsc --noEmit passes; negative
tests confirm `new Health(browserClient)` and admin calls on a
Client-bound service fail to type-check; djlint passes.
- Rename fromApiKey -> fromAPIKey for naming consistency
- Make all setters private; expose only static factory methods
- Guard window access with typeof window !== 'undefined' in realtime
- Gate fromAPIKey behind server/console platform builds only
- Normalize ClientRuntime to 'client' | 'server'; remove 'browser'
- Add withJWT and withForwardedUserAgent builder methods
- Fix clearTimeout misuse on interval handles
Moves the service-level auth tier detection and per-method this-gate
construction from template.ts.twig set blocks into PHP helpers exposed
as Twig filters (webServiceAuth, webMethodThisGate). This makes the
template easier to read while keeping generated output identical.
- Rename ClientRuntime -> SDKPlatform and field runtime -> sdkPlatform
- Remove ConsoleAuth type; merge cookie auth into ServerAuth (covers
  both console and SSR cookie-forwarding use cases)
- Emit fromCookie on all platforms instead of console-only
- Default mode: 'admin' in fromCookie on console builds so the wire
  request authenticates as admin without requiring callers to remember
  the X-Appwrite-Mode header
- Add Prettify utility type and wrap factory params so IDE hover shows
  the full parameter shape instead of an opaque alias name
- Simplify Web.php helpers (webServiceAuth, webMethodThisGate) by
  removing the platform argument now that ServerAuth covers all
  server-tier cases
- Wrap fromJWT in a platform guard mirroring fromAPIKey. JWT auth lives
  in ServerAuth, so emitting fromJWT on client builds produced a dead
  factory: the returned Client<'jwt'> could not satisfy any service
  generated from the client spec (which only carry ClientAuth).
- Add selfSigned?: boolean to BaseClientParams and apply it inside
  applyBase so every factory gets a public migration path. Previously
  setSelfSigned was the only way to set the flag and was made private
  by the factory refactor, leaving callers without a public hook.
Replaces the hardcoded config block and ten manually-written auth
setters with a single spec.global.headers loop, matching the pattern
every other SDK template uses (Python, Dart, Kotlin, etc.).

Setters become primitive: header write + config write + return this.
The redundant sdkPlatform / x-sdk-platform writes are removed because
applyBase already sets both before the setter runs, and the setters
are private — only callable from inside factories. Dropping the
duplication also lets the typed Client<'apiKey'> etc. flow through
chained calls without `as unknown as Client<...>` casts.

Each platform spec carries a different subset of securityDefinitions,
so a Web.php Twig filter (webClientHeaders) augments the parsed list
with auth headers the unified client needs but the loaded spec omits
(e.g. Session/DevKey on console, Cookie on client). The filter has a
TODO pointing at appwrite/appwrite#12211, which moves the union into
each platform spec's securityDefinitions directly. Once that ships
and specs regenerate, the filter and its registration can be deleted
in a follow-up.

Verified against console, client, and server builds plus an end-to-end
smoke test calling Account.get() through fromCookie on Appwrite Cloud.
The server platform spec includes ForwardedUserAgent in
securityDefinitions, so the new spec.global.headers loop generates a
config field and setForwardedUserAgent setter for it on server builds.
That collided with the manual versions left over in the template,
producing TS2300/TS1117/TS2393 duplicate-identifier errors when running
tsc --declaration in the web (server) CI job.

Add ForwardedUserAgent to webClientHeaders so it is universally present
across all platform builds (the unified web client always exposes
withForwardedUserAgent for chained user-agent forwarding) and remove
the manual config field and setter from the template. The loop now
owns it on every build target.

Verified npm run build:types passes for web (server), web (console),
and web (client) on a clean examples/web tree.
…-server-client

# Conflicts:
#	templates/web/src/client.ts.twig
@greptile-apps
Copy link
Copy Markdown

greptile-apps Bot commented May 6, 2026

Greptile Summary

This PR introduces a typed factory pattern (ClientAuth protocol / abstract class / branded type) across Apple, Flutter, and Web SDK generator templates, replacing the imperative Client().setX().setY() chain with explicit Client.fromBrowser, Client.fromSession, Client.fromDevKey, and Client.fromImpersonation constructors. Legacy setters are preserved but deprecated.

  • Apple: Adds ClientAuth protocol, four static factories on Client, private configure/setHeader helpers, a new apple/base/params.twig that reads auth values via getConfig(key:), and updates generated services and Realtime to accept and store ClientAuth.
  • Flutter: Splits the existing Client abstract into ClientAuth (minimal protocol) and Client (legacy setters + factory statics), mirrors the four factory methods using createClient() internally, and guards RealtimeBrowser/RealtimeIO with runtime type checks.
  • Web: Introduces a ClientRuntime<TAuth> class with a phantom TAuth brand, a ClientConstructor type that exposes only factory statics, and per-service Omit-based types that hide internal methods from consumers.

Confidence Score: 5/5

The change is additive and backwards-compatible — existing Client() setter chains continue to compile alongside the new factory methods.

No regressions were found in the core factory logic, auth header propagation, or service construction. The design notes around endpoint fatalError and the Flutter Realtime runtime type check are pre-existing patterns or intentional guards rather than new defects introduced by this PR.

templates/apple/Sources/Client.swift.twig — endpoint and realtime URL validation still uses fatalError even though fromImpersonation was updated to throw; worth aligning them if the factory surface is meant to be fully throwable for invalid inputs.

Important Files Changed

Filename Overview
templates/apple/Sources/Client.swift.twig Adds ClientAuth protocol and four factory methods; endpoint validation still uses fatalError instead of throwing, inconsistent with the fromImpersonation fix.
templates/apple/Sources/Service.swift.twig New base Service class whose init accepts but does not store ClientAuth; relies entirely on subclass overrides to retain the client reference.
templates/apple/Sources/Services/Service.swift.twig Generated services now store _client: ClientAuth themselves and include apple/base/params.twig which reads auth values through getConfig(key:).
templates/apple/Sources/Services/Realtime.swift.twig Realtime now stores ClientAuth directly and accesses project via getConfig(key:) instead of direct config dict access.
templates/flutter/lib/src/client.dart.twig Splits the single Client abstract class into ClientAuth (protocol surface) and Client (legacy setters); adds four factory constructors mirroring the Apple/Web pattern.
templates/flutter/lib/src/realtime_browser.dart.twig Accepts ClientAuth but immediately throws ArgumentError for non-ClientBrowser instances, creating a mismatch between declared and required type.
templates/flutter/lib/src/realtime_io.dart.twig Same pattern as realtime_browser.dart.twig: accepts ClientAuth but throws for non-ClientIO instances at runtime.
templates/web/src/client.ts.twig Introduces ClientRuntime class with branded TAuth type parameter, static factory methods, and a TypeScript ImpersonationTarget discriminated union that enforces single-target constraint at compile time.
templates/web/src/services/template.ts.twig Generated services now use Client<TAuth> for mixed-tier, server-only, or client-only auth shapes, hiding internal client from the public type surface.

Reviews (3): Last reviewed commit: "Merge Flutter isomorphic SDK changes" | Re-trigger Greptile

Comment thread templates/apple/Sources/Client.swift.twig Outdated
Comment thread templates/apple/Sources/Client.swift.twig
@ChiragAgg5k ChiragAgg5k changed the title Add Apple client auth factories feat: Isomorphic SDKs May 7, 2026
@ChiragAgg5k
Copy link
Copy Markdown
Member Author

Superseded by #1512, which uses the clearer branch for the consolidated isomorphic SDK changes.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant