Repository navigation
StripeKit 27: Generated SDK from Stripe OpenAPI - #302
Open
grahamburgsma wants to merge 53 commits into
Open
grahamburgsma wants to merge 53 commits into
grahamburgsma wants to merge 53 commits into
Conversation
- Full OpenAPI spec-driven code generation pipeline - Generated 1552 types, 136 routes, 102 param structs - Closure-based route architecture with .live(handler:) factories - Idempotency API: StripeClient.idempotent(_:) for safe retries - Scoped clients: onBehalfOf(_:) for Connect accounts - Segment-aligned path prefix matching for correct action derivation - Swift keyword escaping (return, do, etc.) in generated identifiers - Cross-schema collision detection for filename disambiguation - Removed old domain-organized source folders (replaced by Generated/)
… form encoder - Replace scoring-based basePath with shortest-prefix approach in both RouteGenerator and ParamGenerator (no more non-deterministic tie-breaking) - Dedup prefers operations from resource's own basePath over cross-resource aliases (fixes PaymentMethod retrieve using customer-scoped path) - toFormBody() now properly encodes [String: String] as metadata[key]=value, arrays as expand[]=val, nested StripeParams recursively, and enum rawValues - Verified end-to-end: CreatePaymentAccount → AddPaymentMethod → CreatePayment → ProcessPayment, confirmed on Stripe (pi succeeded, charge created)
Generated from spec3.sdk.json (API version 2026-01-28.clover): - 1552 types (models + inline schemas) - 136 routes with live factory implementations - 102 param structs with form-encoded body generation Removed 'generated/' from .gitignore — the generated output is the library's public API and should be version-controlled.
- Data(buffer:) → Data(readableBytesView) (no Foundation overlay on Linux) - ByteBuffer(data:) → ByteBuffer(bytes:) (correct label on Linux)
- CommandLine.arguments → swift-argument-parser AsyncParsableCommand - replacingOccurrences(of:with:) → String.replacing(_:with:) - Regex strings → Swift regex literals (/<pattern>/) - hasPrefix(_:) → starts(with:) (Sequence stdlib) - URL(fileURLWithPath:) → URL(filePath:) - appendingPathComponent → .appending(path:) - Added swift-argument-parser dependency for codegen target hasSuffix kept as-is — String.ends(with:) not yet in stdlib. Incorporates review feedback from @0xTim (Gwynne).
Only 3 dot-named schemas collide after normalization: - issuing_authorization.request vs issuing_authorization_request - payment_intent.processing vs payment_intent_processing - source.mandate_notification vs source_mandate_notification Preserves 315 legitimate dot-named inline types.
- Add generateEventType() to InfraGenerator: reads event.type enum from spec, generates StripeEventType with ~250 cases + unknown fallback - Add generateStripeEvent() to InfraGenerator: derives struct properties from spec's event schema, templates custom infrastructure on top - Update CodegenCLI to write StripeEventType.swift and StripeEvent.swift to Generated/ - Delete hand-written Infrastructure/StripeEvent.swift (now generated) - type property is now StripeEventType instead of String
StripeEvent has explicit CodingKeys with snake_case raw values (e.g. pendingWebhooks = "pending_webhooks"). Using .convertFromSnakeCase in the decoder double-converts the keys, causing keyNotFound errors. CodingKeys already handle the mapping correctly on their own.
This reverts commit 0fc0caf.
The generated StripeEvent has explicit CodingKeys with snake_case raw values. Using .convertFromSnakeCase in verify() double-converts the keys, causing keyNotFound errors during decode. CodingKeys already handle the snake_case → camelCase mapping directly. The .convertFromSnakeCase remains in object(as:) and previousAttributes(as:) where it's needed for inner model decoding without explicit CodingKeys.
All generated models have explicit CodingKeys with snake_case raw values. Using .convertFromSnakeCase double-converts keys, causing keyNotFound errors. Removed from verify(), object(as:), and previousAttributes(as:).
Add tests that decode every object in Stripe's published fixtures3.json
(from the same stripe/openapi commit as spec3.sdk.json, a402765) into the
generated types, plus an encode/decode round trip. The codegen now also
writes Tests/StripeKitTests/Generated/FixtureTypes.swift, mapping schema
names to Swift types, so the tests follow the spec on regeneration.
The tests found two generator bugs, fixed here:
- Delete routes returned the full model (e.g. Customer), but Stripe
returns a stub ({id, object, deleted: true}), so every delete call
failed to decode. The spec's deleted_* schemas are now generated as
Deleted* types and routes return the type the spec declares:
- delete endpoints return DeletedX
- endpoints that can return either (customer retrieve, terminal
location/reader/configuration retrieve and update, payment source
delete) return the new ObjectOrDeleted<X, DeletedX>, chosen by the
`deleted` flag
This matches the async-stripe Rust SDK. Expandable fields still expand
to the live object only, like async-stripe and the official SDKs.
- Free-form objects (no declared fields) were typed [String: String], so
numbers, bools and nulls failed to decode. This broke Event.data.object,
next_action.use_stripe_sdk and webhook payload types. They are now
[String: AnyCodableValue].
Terminal locations, readers and configurations were missing their
retrieve/update/delete routes, because path mapping ignored responses
that are a deleted object or "X | deleted_X". ReaderRoutes.update was
also the test-helper present_payment_method endpoint under the wrong
name; it now calls /v1/terminal/readers/{reader}.
Breaking: delete and the routes above return new types. README updated.
Brings in the CI upgrade, dependabot config, and dependency updates from main (async-http-client 1.33.1, swift-crypto 3.0.0..<6.0.0, explicit swift-nio dependency for Swift 6.3). Package.swift conflict: kept main's dependency versions and added the branch's swift-argument-parser and codegen target. Main depended on NIOFoundationCompat, which the generated code doesn't import; it imports NIO and NIOHTTP1 directly, so those are the products listed instead.
Regenerate from the latest stripe/openapi spec3.sdk.json and fixtures3.json (1,844 schemas / 398 paths, up from 1,578 / 381). - Codegen: param enums whose only value is "" (clear-only fields such as invoice item update `invoicing_rules`) now fall back to their base type instead of referencing an enum that is never emitted. - Bump the Stripe-Version header to 2026-10-28.endive. - Allowlist the new `terminal.refund` fixture, which has no spec schema. - Update README API version and generated-file counts.
StripeParams.toFormBody() walked params with Mirror, which only sees Swift names, so it had to reconstruct the wire format and got it wrong: - enums sent their case name instead of their raw value (setup_future_usage=offSession instead of off_session); - arrays of enums and arrays of nested params were mis-encoded (only [String] was handled); - field names were guessed with camelToSnake instead of read from CodingKeys, so e.g. ssnLast4 went out as ssn_last4, not ssn_last_4. Encode with JSONEncoder instead (so CodingKeys and enum raw values apply), decode into a small JSON value enum, and flatten it with Stripe's conventions: parent[child]=v, scalar arrays key[]=v, object arrays key[0][field]=v. Public API is unchanged. Also: - Helpers.queryParameters: encode RawRepresentable values by rawValue. - StripeAPIHandler.sendMultipart: fix escaped interpolations (\\(apiKey) etc.) so the Authorization header carries the real key.
…ypes
The codegen never read operation `parameters`, so every GET route only took
`expand`, and search routes were typed as returning the resource itself.
Codegen:
- GET operations with query params beyond `expand` get a generated
`{Resource}{Action}Params` struct built from the spec's `in: query`
parameters (e.g. CustomerListParams, PaymentMethodListParams,
CustomerSearchParams), including generated enums. Routes take it as
`_ params:` (non-optional when a param is required, like search `query`)
and send `toFormBody()` as the query string.
- Route return types come from the 200 response's `object`: `list` ->
`{Resource}List`, `search_result` -> `StripeSearchResult<Resource>`,
otherwise the referenced object. This also fixes single-object GETs
(e.g. /v1/balance) that were typed as lists.
- `integer | range_query_specs` (created, amount, ...) maps to the new
`StripeRangeQuery` instead of falling back to String.
Hand-written:
- Infrastructure/StripeSearchResult.swift
- Infrastructure/StripeRangeQuery.swift (.equals(Int) / .range(gt:gte:lt:lte:))
Breaking: list/search routes take a params struct instead of `[String]?`
(expand moves into the struct); search returns StripeSearchResult.
Route names were derived from the URL path, which mislabeled singleton and action endpoints (balance.list returned a Balance, subscriptions.delete is Stripe's cancel, taxIds.update created a customer tax ID) and made distinct endpoints collide on one name, so the generator silently dropped all but one of them. The spec lists every SDK method per resource in `x-stripeOperations` (`method_name`), which is what Stripe's official SDKs are generated from. Use it for route names (camelCased), preferring `service` entries over `collection` ones, and fall back to the path-derived name only when the spec has none. 557 of 565 routes now carry the spec's exact name. Renames (37), e.g.: balance.list -> retrieve, mandates.list -> retrieve, tax settings list/create -> retrieve/update, subscriptions.delete -> cancel, invoices.finalize/send/void -> finalizeInvoice/sendInvoice/voidInvoice, creditNotes.void -> voidCreditNote, quotes.finalize -> finalizeQuote, bankAccounts.create -> verify, creditNotes.listPreview -> preview Params structs follow the route names (e.g. InvoiceVoidInvoiceParams). Where the spec reuses a name for the same resource under different parents, the endpoint in the resource's own namespace keeps it and the others get a parent suffix (taxIds.createForCustomer, refunds.listForCharge, ...) instead of being dropped. Net: 39 endpoints that were missing are now generated (mostly test helpers, plus customer tax IDs, charge refunds, paymentMethods.listPaymentMethods/retrievePaymentMethod), none lost. ParamGenerator now takes POST and GET operations from RouteGenerator so params struct names can't drift from the routes that use them.
CodegenCLI checked `fileExists(atPath: generatedURL.path())`, but `path()` percent-encodes, so in a checkout whose path contains a space the check was always false and the Generated/ folder was never cleared. Files from earlier codegen runs survived every regeneration and were committed: 15 stale files, including duplicate LocationRoutes (alongside TerminalLocationRoutes) and Issuing AuthorizationRoutes, plus types the current spec no longer produces. Use path(percentEncoded: false), and remove the 15 stale files. FixtureDecodingTests referenced the stale LocationRoutes; point it at TerminalLocationRoutes, which is what the current generator emits.
Routes were grouped by the type an endpoint returns, so methods Stripe
defines on a parent resource landed on the child type's routes
(paymentMethods.listPaymentMethods, lineItems.listLineItems for quotes,
fundingInstructions.createFundingInstructions, ...).
The spec says which resource owns each method: every schema's
`x-stripeOperations` lists its SDK methods. When an operation has exactly
one owner and the owner isn't what it returns, group it under the owner.
Operations with several or no owners keep the response-type grouping.
Return types now come from the response schema, since a moved route can
return another type (customers.listPaymentMethods -> PaymentMethodList).
Moved (17):
customers: listPaymentMethods, retrievePaymentMethod,
createFundingInstructions, fundCashBalance
quotes: listLineItems, listComputedUpfrontLineItems
checkoutSessions / paymentLinks: listLineItems
creditNotes: previewLines
sources: sourceTransactions
financialConnectionsAccounts: listOwners
tax calculations / transactions: listLineItems
treasury financialAccounts: retrieveFeatures, updateFeatures
New: customers.deleteDiscount, subscriptions.deleteDiscount (were never
generated). No endpoint lost; no other route's return type changed.
Removed client properties whose routes all moved to their owner:
items, fundingInstructions, sourceTransactions, accountOwners,
calculationLineItems, transactionLineItems, financialAccountFeatures.
ParamGenerator: emit a nested params struct once when two operations
reach the same one under the same name (FinancialAccountUpdateFeatures…),
and fail generation if a name is reused for a different shape.
Most bugs found so far were silent deviations from the spec: endpoints
dropped on name collisions, names and return types guessed instead of read,
params loosened to String. Make every deviation explicit.
Generator (Sources/Codegen/CoverageCheck.swift): after generating, compare
the emitted routes and params with the spec and report
missing - a spec operation that isn't generated
duplicate - an operation generated on more than one route
name - a route not named as x-stripeOperations names it
return - a return type not read from the response schema
param - a param typed looser than the spec (anyOf -> String,
map of objects -> [String: String], ...)
Generation fails on any deviation not listed with a reason in
CoverageExceptions.swift, and on any listed exception that no longer
matches, so the list can't go stale. Today: 557 operations generated,
2 skipped (GET /v1/account, the quote PDF), 50 accepted deviations, of
which 46 are param typing gaps still to close (e.g. off_session,
trial_end, currency_options, mandate_data).
ParamGenerator records each type fallback it takes (ParamFallbacks). It
now resolves a property's type only when it's used, so anyOf properties
don't record a fallback that doesn't happen; `properties: {}` objects and
`string | ""` array items are exact, not fallbacks. Generated output is
unchanged.
Test (SpecCoverageTests): the generator also writes
Tests/StripeKitTests/Generated/GeneratedOperations.swift, every generated
and skipped operation. The test checks it against spec3.sdk.json: every
spec operation generated or skipped, nothing stale, no duplicates. This
catches a spec updated without regenerating.
The coverage check listed 46 params typed looser than the spec. All are
now typed from it, and their exceptions are gone (4 operation-level ones
remain).
anyOf with several forms -> a generated enum per field:
- keywords become cases, a scalar becomes `value(T)` and the enum takes
that literal:
trialEnd: .now / trialEnd: 1_700_000_000 (SubscriptionCreateTrialEnd)
offSession: true / offSession: .oneOff (PaymentIntentCreateOffSession)
cancelAt, up_to, delay_days, effective_date, expires_at, ... (25 fields)
- object forms become cases carrying a generated struct, named from the
spec's variant title:
mandateData: .secretKey(...) / .clientKey(...)
card: .cardDetails(...) / .token(...)
product: .inlineProduct(...) / product: "prod_123"
Maps type their values: currency_options is [String: {Parent}CurrencyOptions]
(13 fields), minimum_balance_by_currency is [String: Int],
automatic_transfer_rules_by_currency is [String: [rule]].
Previously these were String or [String: String], so currency_options and
mandate_data couldn't be sent at all and card/product only in ID form.
ParamGenerator: one recursive resolveType replaces paramTypeString and
resolveAnyOfParam, which named types in one place and generated them in
another. Every other generated property type is unchanged. Enum collection
follows union variants and map values so nested enum names match.
Breaking: these 46 properties change type. E.g. callers passing
`offSession: "true"` now pass `offSession: true`.
All 559 spec operations are now generated, with 0 skipped and 0 accepted
deviations; CoverageExceptions is empty.
- GET /v1/account (the API key's own account) is generated as
accounts.retrieveCurrent. The spec names it `retrieve`, like
GET /v1/accounts/{account}; a name collision with no path param to
suffix by now gets `Current` instead of being dropped.
- GET /v1/quotes/{quote}/pdf is generated as
quotes.pdf(_ quote: String, _ expand: [String]?) async throws -> Data
It returns application/pdf from files.stripe.com (the operation's
`servers` in the spec). New StripeAPIHandler.sendForData(method:path:
baseURL:) returns the response bytes; error responses are still decoded
as StripeError. Codegen decodes operation `servers`, groups a
file-response operation under its x-stripeOperations owner, and returns
`Data` from the operation's host.
- DELETE /v1/customers/{customer}/sources/{id}: its owners name it
`delete` (bank_account, card) and `detach` (source). When owners
disagree, use the most common name; the route was already
paymentSources.delete, now it's derived from the spec.
- POST /v1/customers/{customer}/sources/{id} returns
`card | bank_account | source`. A response that's a union of object
types now maps to the smallest polymorphic schema covering all of them
(payment_source); the route already returned PaymentSource, now it's
derived from the spec.
No existing route changes. SpecCoverageTests also checks the signatures of
quotes.pdf and accounts.retrieveCurrent.
- Remove unused SchemaClassifier, DynamicExpandable, Dictionary.queryParameters, path-based route naming (every operation is named by x-stripeOperations), and unused property-type/domain cases - Share ref, doc-comment and enum emitters across generators; resolve param types once; compute each resource's operations once in the CLI - Fail generation if an expandable field can expand to several live types - Update headers, README and onBehalfOf docs to match the code Generated output is unchanged.
x-expandableFields also lists plain nested objects (so their own fields can be expanded through them), which made ~1,970 fields like account.businessProfile a String? that was always nil. Use the field's x-expansionResources instead, as async-stripe does: 315 @expandable and 17 @ExpandableCollection fields, which now also covers arrays whose items can be deleted objects (Invoice.discounts was [[String: AnyCodableValue]]). Without the wrapper boxing them, models embedding whole resources grew to 11-15 KB (ApiErrors, Invoice, TerminalReader) and decoding them overflowed a 512 KB task stack in debug builds. Add an @indirect property wrapper and store every embedded resource out of line, which also breaks the PaymentIntent -> ApiErrors -> PaymentIntent cycle; a depth-first cycle check backs it up.
…leted
Expanding e.g. charge.customer after the customer was deleted returns
{id, object, deleted}, which failed to decode as a Customer. Where the
spec's x-expansionResources include a deleted variant (47 fields), expand
to ObjectOrDeleted<Object, Deleted>, the type retrieve routes already use.
Also update the README's expandable examples (deleted objects, and the
stale defaultTaxRates / discounts collection example).
The API version was hard-coded in the hand-written StripeAPIHandler and had to be kept in sync with spec3.sdk.json by hand. Generate it as StripeClient.apiVersion from the spec's info.version and send that instead, with a test that it matches the spec.
Fields the spec marks `format: unix-time` were generated as Int. Generate them as Date instead, as the hand-written models on main did: 317 model fields (decoded with .secondsSince1970, as every decoder already was) and the request-body and query params. Timestamp unions such as trial_end become `now | value(Date)` and still take an integer literal of seconds. Form encoding now sends dates as whole Unix seconds; .secondsSince1970 would send fractional seconds, which Stripe rejects. Range filters (StripeRangeQuery) stay Int: the spec doesn't mark them as timestamps.
Decode failures printed [StripeKit DEBUG] lines to stdout before rethrowing. The DecodingError already names the type and coding path, so just rethrow.
- Compare signatures in constant time; `==` returned at the first differing character, leaking how much of a forged signature was right - Sign the payload's exact bytes rather than a String conversion of it, which signed non-UTF-8 payloads as "" - Reject a timestamp that doesn't parse; the tolerance check was skipped
InfraGenerator built ~250 lines of Swift that don't depend on the spec (EventData, EventRequest, signature verification, AnyCodableValue) as string literals. Move them to hand-written Infrastructure files; the generated StripeEvent.swift is now just the event struct from the spec. Replace AnyCodableValue (Any + @unchecked Sendable) with a JSONValue enum that is Sendable and Hashable, has subscripts and typed accessors, and also replaces the form encoder's private FormValue. Free-form model fields are [String: JSONValue], and EventData exposes object / previousAttributes as JSONValue (previously _object / _previousAttributes). Fix the README webhook example, which switched on strings instead of StripeEventType cases and decoded previousAttributes into a full model.
generateParamEnums / collectNestedEnums re-walked every params schema to emit the String enums resolveType had already named, and had to mirror its naming exactly (including the union-variant suffix). resolveType now emits each enum as it returns its name, alongside the nested structs and unions, and the second walk is gone. Param enums now live in each resource's +Params.swift instead of a separate +ParamEnums.swift. The 1,775 enums are unchanged, and so is everything else in the params files.
Every generated route closure built its own query string, expand[] list and ByteBuffer body before calling the handler. Move that into StripeAPIHandler: send(_:_:params:expand:) form-encodes params as the body of a POST or the query string otherwise, and each route is now a single call (~3,000 fewer generated lines). send, sendForData and sendMultipart now share one request builder and one execute/error path instead of three copies. The upload route takes its path and files.stripe.com host from the spec rather than a hard-coded URL. Behaviour changes: expand values are percent-encoded; uploads now send the Idempotency-Key from idempotent(_:); GET/DELETE no longer send a form Content-Type. Adds request-encoding tests for the builder.
Path parameters were interpolated into the URL as-is, so a chosen ID (products, prices, features, ...) containing `/`, `?`, `#` or a space could change the path or spill into the query string. StripeAPIHandler now takes paths as StripePath, an ExpressibleByStringInterpolation type that uses literal parts as written and escapes every interpolated value as a single path segment (all but RFC 3986's unreserved characters), as stripe-go and stripe-node do. The escaping lives in one place and can't be skipped: generated routes keep plain "/v1/customers/\(customer)" interpolation, and so would any other caller. Stripe-generated IDs are unchanged. StripePath(unescaped:) takes an already-escaped path as is. (expand[] values were already encoded by the previous commit.)
…espace Type names only got their namespace when two resources' last segments collided, so adding a resource could rename an existing one (a new billing.reader would have turned Reader into TerminalReader). Type names are now always the full schema/resource name in PascalCase, as in stripe-go and async-stripe, and the collision detection is gone: - terminal.reader -> TerminalReader, tax.calculation -> TaxCalculation, entitlements.feature -> EntitlementsFeature (51 resources renamed, along with their params, enums and routes) - event payloads too: account.application.authorized -> AccountApplicationAuthorized (was Authorized) StripeClient now groups namespaced routes like Stripe's API paths and most of its SDKs: core resources stay top-level (stripe.customers), namespaced ones sit under a nested struct per namespace (stripe.terminal.readers, stripe.tax.calculations, stripe.billingPortal.sessions). Also fixes the client pluralisation (ephemeralKeies -> ephemeralKeys). BREAKING CHANGE: namespaced types and their client properties are renamed.
…JSONValue The polymorphic list types (ExternalAccountList, PaymentSourceList and their deleted variants) split items into one array per type and encoded none of them, so encoding dropped the list's contents and their order. They now hold the items in order in `data`, like every other list, with a read-only array per type (cards, bankAccounts, ...) computed from it. Items of an unknown type are still skipped on decode. A schema with no type now maps to JSONValue instead of String (none in today's spec).
…e clashes Since c0bf0f9 named every type by its full schema name, the billing.alert.triggered event payload and the billing.alert_triggered object both became BillingAlertTriggered. Both wrote the same file, so which one was generated depended on dictionary order and changed between runs. Event payload schemas (x-stripeEvent) now get an `Event` suffix, as in stripe-node: AccountApplicationAuthorizedEvent, BillingAlertTriggeredEvent (whose `object` is a BillingAlertTriggered). That also makes the rule skipping dotted schemas with an underscore twin unnecessary; the three it skipped were events, and now generate as e.g. PaymentIntentProcessingEvent. Generation now fails if two schemas would produce the same Swift type.
…ptions
Routes were stored closures, so every call was positional with explicit
nils: customers.retrieve("cus_1", nil), customers.create(nil). Each
operation now also gets a method with argument labels and defaults,
following Swift's API guidelines and Stripe's SDKs:
stripe.customers.retrieve("cus_1", expand: ["default_source"])
stripe.customers.create()
stripe.customers.retrievePaymentMethod("cus_1", paymentMethod: "pm_1")
stripe.customers.create(params, options: .init(idempotencyKey: key))
The first path parameter is unlabeled and later ones are labeled; a params
struct is unlabeled and defaults to .init() unless it has required fields;
otherwise expand: defaults to nil; options: comes last. The methods call
the route's stored closure, which tests can still replace. Stripe's
deprecation warning moves to the method.
Adds RequestOptions (stripeAccount, idempotencyKey) per request, taking
precedence over the client's. idempotent(_:) is deprecated, since one key
for a whole client is only safe for a single request, and
StripeClient.live no longer takes an idempotencyKey.
BREAKING CHANGE: route closures take a RequestOptions argument and a
non-optional params struct, so positional calls like retrieve("cus_1", nil)
and existing stubs need updating.
idempotent(_:) sent one idempotency key with every request a client made, so a second request silently got the first one's response. It was deprecated in favour of per-request RequestOptions; since this branch is a major version, remove it, along with StripeAPIHandler's stored idempotencyKey and its init parameter. Idempotency keys are now only ever set per request: options: .init(idempotencyKey:). BREAKING CHANGE: StripeClient.idempotent(_:) and the idempotencyKey parameter of StripeAPIHandler.init are removed.
…l decoding
Stripe adds enum values (new payment method types, error codes, event
types, ...) without a new API version; its changelog labels such
additions non-breaking. Generated enums were closed, so one value
StripeKit didn't list failed the whole response, and for error responses
turned the error into a generic "HTTP 4xx" without its message.
Spec enums are now extensible structs, like the extensible enums Apple's
Objective-C headers import as and Soto's open-ended types: a stored
rawValue plus a static member per documented value. Any value decodes and
can be sent in params (.init(rawValue:)), and call sites read like enums:
`type == .card`, `switch type { case .card: ... default: ... }`. Value
descriptions from the SDK spec's x-stripeEnum annotation become the
members' doc comments.
- Polymorphic enums (ExternalAccount, PaymentSource, ...) decode an
object of an unknown type as .undocumented(JSONValue) instead of
throwing, so their lists keep such items.
- StripeErrorCode and StripeErrorType are now the generated ApiErrorsCode
and ApiErrorsType, adding the 26 codes the hand-written list lacked;
existing case names are unchanged.
- StripeEventType's .unknown is gone; an unlisted event type keeps its
rawValue.
BREAKING CHANGE: spec enums are structs: switches need a default, and
init(rawValue:) is non-failable.
Requests weren't retried. Following stripe-go and stripe-node, the handler now retries up to 2 times (StripeClient.live(maxNetworkRetries:); 0 turns it off) after a network error, or a response Stripe marks retryable: its Stripe-Should-Retry header when present, otherwise a 409 or a 5xx. Backoff starts at 0.5s and doubles up to 5s, with jitter, and honours a Retry-After of up to 60s. POSTs get a generated idempotency key unless the request has its own, and retries resend it, so a retry after a lost response can't perform a request twice. onBehalfOf clients keep the retry setting; StripeClient.test has retries off so unstubbed routes fail at once. Tests cover the retry policy, the generated keys, and the retry loop against a local stub server.
Stripe clears a field sent empty (`field=`) wherever its spec allows ""
(anyOf [X, enum [""]], or an enum including ""), e.g. metadata, shipping
or discounts. Param unions dropped the "" variant, so objects, arrays and
numbers - 718 of the 1,290 such fields - couldn't be cleared at all.
Params structs with clearable fields (506) now conform to ClearableParams
and get a nested ClearableField enum listing exactly those fields:
var params = CustomerUpdateParams(name: "Jane")
params.clear(.shipping) // shipping=
The fields to clear are encoded under a reserved key that toFormBody()
turns into `field=` pairs at any nesting level (invoice_settings[...]=),
taking precedence over a value set on the field. Params JSON without the
key still decodes. stripe-go offers the same as unsetting a field.
…er type
Every generated type had its own identical `{Type}List` struct (1,841 of
them), though only ~120 were ever used. Replace them with a hand-written
StripeList<Item>, like StripeSearchResult. Routes and list fields use it
directly (customers.list() -> StripeList<Customer>), and each resource
keeps its list name as an alias (CustomerList = StripeList<Customer>).
Polymorphic lists keep their per-type views (cards, bankAccounts, ...) in
a constrained extension. Generated source shrinks by ~6% (9.7 -> 9.1 MB).
BREAKING CHANGE: a list's data, hasMore and url are no longer optional,
as every list in the spec requires them (charges.data, not
charges.data ?? []); inline types no longer have a {Type}List.
… actions The spec writes request bodies out inline, so a nested shape such as payment_method_data is a separate copy under each endpoint, and each was generated as its own type: PaymentIntentCreatePaymentMethodData, PaymentIntentConfirmPaymentMethodData, ... (4,930 params types, ~1,356 distinct shapes). Following stripe-go and stripe-dotnet, a nested params type that every action of a resource defines identically is now generated once, named by resource and field path without the action: PaymentIntentPaymentMethodData, CustomerInvoiceSettings. Doc comments are ignored when comparing. Where actions define a field differently, the type keeps its action (CustomerCreateTax / CustomerUpdateTax), and a parent is only shared if everything nested in it is. Shared names that would clash with another type keep the action too. Params types drop to 3,591, and generated source shrinks ~17% (9.1 -> 7.5 MB). Also fixes the README params example, which used a type name that never existed. BREAKING CHANGE: nested params types lose the action in their name when shared (e.g. CustomerUpdateInvoiceSettings -> CustomerInvoiceSettings).
Generators built source with ~310 lines.append(" ...") calls, indenting
and closing every block by hand, and copied the file header into 7 places.
Add a small CodeWriter (line, block(opener, closer:), indented, doc,
append) and a shared fileHeader(), and move every generator onto them.
Swift-style switches keep their cases at the switch's indentation.
The generated output is byte-for-byte unchanged.
Sharing identical nested params across a resource's actions worked by generating every type with its action in the name, then renaming identifiers in the generated text with a regex, comparing copies by their normalised text. Params generation now runs twice: a probing pass collects each nested type's spec shape (everything but descriptions) and the nested types inside it; sharedNames decides the final names from those, using the same rules; and the real pass generates with the final names threaded through. An enum's shape ignores "" as the generated enum does, while a parent's keeps it, since it decides the parent's clearable fields. The generated output is byte-for-byte unchanged, and generation takes ~3.8s instead of ~9.8s without the regex pass over every params line.
Restore the original README's shape - short, focused examples, numbered expand examples, a Vapor webhook handler and integration extensions, and the License section - updated to this branch's API, and keep the sections on open enums, clearing fields, retries, testing and codegen. - Point installation at vapor-community/stripe-kit from 27.0.0, with a version support table (27.x: 2026-10-28.endive, 26.x: 2022-11-15) - Fix the badges: Swift 6.0, the test workflow's current badge URL, and the Stripe API version - Use Stripe's field names in expand examples (payment_method, not paymentMethod), per-request options instead of addHeaders, and drop the removed @DynamicExpandable - Fix examples that didn't compile or misled (required params, an undefined variable, decoding test fixtures without Unix-seconds dates) - Drop the overview, file listings and old calendar versioning scheme Every non-Vapor Swift example was compiled against the library.
Both come from the same stripe/openapi commit, but the fixtures lived in the test target's resources, and the README's update steps only refreshed the spec. Move fixtures3.json next to spec3.sdk.json, load it by path the way the spec tests already do (so the test target no longer declares a resource), and download both when updating the API version.
- Fix doc comments that had drifted: ObjectOrDeleted's example used the old retrieve(_:_:) call, ClearableParams' example cleared a field that isn't clearable, StripeError claimed typed throws, and the generator's headers described scoping, routes and params from before this branch's changes - Remove dead code: StripeResource.requiredFields and StripeProperty.enumCases (never read), PathItem.put/patch (Stripe only uses GET/POST/DELETE), and the unreachable path that guessed a list's item type from a plural field name - Delete unused async XCTest helpers (the build's only warnings), and replace an Expandable test that no longer exercised @expandable with one covering missing, ID and expanded values
… needed On Linux and Windows, FoundationEssentials is a separate module, so an app that never links full Foundation can leave out its internationalization data. StripeKit's dependencies (AsyncHTTPClient, NIO, swift-crypto) already import it this way. - The codegen imports Foundation only in files whose code uses Date, Data or TimeInterval (245 of 2,113 generated files), behind #if canImport(FoundationEssentials). The rest import nothing from it. - Hand-written infrastructure does the same: five files use the guarded import and nine drop an import they didn't use. - Replace the two APIs outside FoundationEssentials: webhook verification hex-encodes the signature itself instead of String(format: "%02x"), and the retry backoff computes 2^n without pow. - Enable MemberImportVisibility on StripeKit, so each file must import the modules whose members it uses and the imports stay accurate. Only imports and blank lines change in the generated files. Built on macOS; the FoundationEssentials branch hasn't been compiled on Linux yet.
Enable the ExistentialAny upcoming feature on every target through a shared swiftSettings list (StripeKit keeps MemberImportVisibility as well), as swift-nio, swift-log and Vapor's packages do. - The codegen writes custom Codable conformances with `any Decoder` and `any Encoder`; regenerating changes only those lines, in 19 files. - Hand-written infrastructure, the codegen and the tests use `any` for their Decoder, Encoder, SingleValueDecodingContainer and Channel existentials, with optionals as `(any P)?`. All targets build with no warnings.
grahamburgsma
force-pushed
the
feature/autogen
branch
from
November 18, 2026 13:49
aa00bb6 to
22e6143
Compare
FoundationEssentials has no CharacterSet or addingPercentEncoding, so StripePath and StripeParams didn't compile on Linux. Replace them with a small encoder that escapes everything but RFC 3986 unreserved characters, as Stripe's own SDKs do, for paths, form bodies and expand[] values alike. Query and form values now also escape !$'()*,/:;?@, which decode to the same values.
Params are only ever sent to Stripe, so StripeParams is now Encodable rather than Codable, and the codegen no longer emits a decoder for param unions. This drops the synthesized init(from:) from every generated params type, along with the fieldsToClear decoding helper and the tests that round-tripped params through JSONDecoder.
…roperties Release builds of apps depending on StripeKit ran out of memory: a release build optimizes each module as a whole in one compiler process, and the single StripeKit module needed more than 8 GB. Split the library into four modules. StripeKit re-exports the others, so callers still only import StripeKit: - StripeKitCore: the hand-written building blocks (JSONValue, Expandable, Indirect, StripeList, StripeParams, percent-encoding, StripePath, ...) - StripeKitModels: generated models, types and events, with the hand-written errors and webhook verification - StripeKitParams: generated request params - StripeKit: generated routes and StripeClient, with the HTTP handler Models and params never refer to each other, so each builds in its own compiler process. The codegen writes into each module's Generated/ directory. Generated model properties are now `let`, except those backed by a property wrapper, like Soto's shapes. Models are decoded from Stripe's responses, so they don't need setters, and dropping them cut the models' release build peak from 4.1 GB to about 2.8 GB on macOS.
grahamburgsma
marked this pull request as ready for review
November 18, 2026 18:12
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #302 +/- ##
========================================
+ Coverage 2.16% 8.30% +6.14%
========================================
Files 194 950 +756
Lines 8888 35036 +26148
========================================
+ Hits 192 2910 +2718
- Misses 8696 32126 +23430
🚀 New features to boost your workflow:
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
I've built on the work @Andrewangeta started earlier this year to complete a fully typed SDK from Stripe's OpenAPI spec. It targets Stripe API
2026-10-28.endiveand is a breaking release. Please take a look and give feedback.Key changes
TerminalReader, notReader), so a resource Stripe adds later can't rename an existing one. Routes are named from Stripe'sx-stripeOperations, as its SDKs are.stripe.terminal.readers).(id, params, options)with per-request options.case unknown(String)really increases the amount of generated code and would need Swift 6.2.3 (@nonexhaustive) to stay non-breaking. ARawRepresentablestruct withstatic var carddecodes any value, needs no extra code, and still readstype == .card.ObjectOrDeletedis used where Stripe can return or expand to a deleted object, and@Expandableonly wraps fields the spec marks expandable.Tests
The generator fails on any spec operation it doesn't generate, name or type as the spec says. Tests decode all of Stripe's published fixtures and cover requests, retries and webhooks.