Skip to main content

sp_laravel_api 0.5.0 copy "sp_laravel_api: ^0.5.0" to clipboard
sp_laravel_api: ^0.5.0 copied to clipboard

Typed REST client and multi-broadcaster realtime client for the SP Laravel backend packages.

Changelog #

0.5.0 - 2026-11-30 #

  • Added: limit on TableGateway.list and serializeQuery, for reads that are not pages (a lookup by key, a top 10, a preview). list(where: [...], limit: 10) sends limit=10 and no per_page, so the host runs a plain LIMIT with no COUNT(*). limit with perPage or page throws SpApiError(unencodableValue); limit with cursor is allowed, and total stays off unless you pass total: true. Without limit nothing changes. Same behaviour as limit in @sokpheak/sp-laravel-api.

0.4.0 - 2026-11-30 #

  • Added: update and patch take expectedVersion (a number or numeric string). It is sent as expected_version, so a table with a version column in sp-laravel-api 1.1.0 refuses a stale write with a SpApiErrorCode.conflict error whose currentRecord is the stored row. The body you pass is not changed. Added SpApiError.isConflict. Same behaviour as expectedVersion and isConflict in @sokpheak/sp-laravel-api.

0.3.0 - 2026-11-29 #

  • Added: a version conflict is its own error category. An HTTP 409, or a 200 { success: false } envelope with error_code 10016 (a stale expected_version on a table with a version column in sp-laravel-api 1.1.0), is SpApiErrorCode.conflict instead of unknown, and SpApiError.currentRecord holds the row the server has now (errors.current_record), or null. The stored row is no longer flattened into fieldErrors['current_record'] as text. SpApiErrorCode gains conflict after validation, so an exhaustive switch over it needs a new case. Same behaviour as @sokpheak/sp-laravel-api.

0.2.0 - 2026-10-30 #

  • Fix: the direct-to-storage requests of uploadDirect and uploadMultipart no longer pass through the interceptors or default headers of the client's Dio. They use a bare Dio that shares only the transport (adapter and timeouts), so the bearer token that attach(dio) from sp_jwt_auth adds to every request is not sent to S3 or R2 (storage rejects a presigned request that also carries an Authorization header). A multipart upload also waits for the parts in flight before it aborts, and a failure or a stream error stops them. A cancelled upload rethrows a cancel error that does not hold the signed URL, and a transport failure on an upload call is rethrown without the underlying request (which carried the upload token and the key).

  • BREAKING: TableGateway.fetchLast and CursorPagination.lastPage need a sort and throw SpApiError(unencodableValue) before any request without one. They used to assume Sort('id', Order.asc), but the host's default sort depends on the table (created_at when it has one, else the primary key), so the old default could silently return the wrong rows. With a sort nothing changes: the sort is inverted for the request and the items are restored to canonical order. Pass the sort the list uses. Same behaviour as lastPage in @sokpheak/sp-laravel-api.

  • BREAKING (fix): the attachment ids, record ids, table names and the rpcPrefix that go into a request path are now guarded: an empty, . or .. value throws SpApiError(unencodableValue) and nothing is sent (a URL parser would normalise it into a different route, and the call carries auth headers). Affects viewBytes, link, unlink, getViewUrl and getDownloadUrl; the rpcPrefix is checked segment by segment (a prefix such as .. or a//b throws). Fix: getViewUrl and getDownloadUrl hard-coded rpc and ignored a custom rpcPrefix; they now use the client's prefix (an empty prefix drops the segment) and percent-encode the id (they inserted it raw before). With the default prefix and a plain id the URLs are unchanged.

  • Added serializeFilters: the query parameters for select, where, or, search, distinct, trashed and sort, without any paging, for hosts that run their own list layer and set per_page, cursor and the rest themselves. It quotes values exactly like serializeQuery, never returns per_page, page, cursor, direction, cursor_column or total, and does not require select. serializeQuery is unchanged.

  • Fix: AttachmentsModule.uploadMultipart could never succeed and uploaded nothing. It never read its stream, called rpc/create-multipart-upload (the route is sp_attachments/rpc/...) and completed with parts: [] while the backend requires at least one part, the upload token and its expiry. It now follows the real protocol: create-multipart-upload, per part sign-multipart-part and a PUT to the signed URL (no auth or tenant header, the ETag response header is required), then complete-multipart-upload with the ordered parts. The stream is cut into exact partSize parts (default 8 MiB, at least 5 MiB, at most 10,000 parts, concurrency parts at once, default 4); a failure aborts the upload once and rethrows the original error. totalBytes is now optional; new parameters: contentType, partSize, concurrency, onProgress, cancelToken, replaceOld, title, caption, tempTimeoutMinutes, tempTimeoutAt. Resume is not supported. Errors never contain a signed URL, the upload token or the key.

  • Fix: AttachmentsModule.uploadDirect could never succeed against the backend. It called rpc/create-upload-url (the route is sp_attachments/rpc/create-upload-url), read an attachment_id the backend does not return, and completed with { attachment_id } while complete-upload requires key, upload_token and expires_at. It now follows the real protocol: create-upload-url (filename, content_type, visibility, folder_id), a PUT of the bytes to the signed URL with the backend's headers and no auth or tenant header (or, on a local disk, the file posted to complete-upload), then complete-upload with the token, the record link (recordType, recordId, collection) and the shared fields (replaceOld, title, caption, tempTimeoutMinutes, tempTimeoutAt). New optional parameters: contentType, cancelToken and those fields; folder is now sent as folder_id. A failed upload is a typed SpApiError that never contains the signed URL, the upload token or the key.

  • AttachmentsModule.upload sends the other fields the upload route validates: recordType, recordId, collection (the link), folderId, title, caption, replaceOld (replaces what is linked in the same collection of the record, deletes old files nothing else links to; needs a record), tempTimeoutMinutes / tempTimeoutAt (a String or a DateTime; the server drops the offset, so a UTC value is only right when the host's app.timezone is UTC) and, form upload only, width, height, fit, sizeName and asTemp. When the server would silently ignore or override an option the call throws SpApiError(unencodableValue) before any request (asTemp: true with a private / public visibility, a timeout without a temporary upload, both timeouts, replaceOld without a record, sizeName with width / height / fit, a width or height below 1); only a truthy flag counts, asTemp: false never throws. visibility is now nullable: when null the form still sends private, unless asTemp is true. The server's own ranges (width and height 10 to 3000, title length, timeout cap) are not copied: its 422 reports them.

  • debug option that sends X-Debug (D3): SpApi(debug: true) adds X-Debug: 1 to every request and SpDebug.on() / SpDebug.merge(options) do it for one request (every TableGateway method and rpc), asking the SERVER for lazy-loading diagnostics and error debug details. It logs nothing on the client (see SpLog). The header is added after the auth and tenant headers and before per-request headers, so an explicit per-request X-Debug (even 0) wins. The default sends no header. New file: lib/src/debug.dart.

  • Optional redacted request logging (D1): SpApi(logger: SpLogger(sink: ...)) delivers one SpLogEntry per HTTP attempt (method, redacted URL, status, duration, request id, attempt, code, errorCode). Modes SpLogMode.perRequest (default, only requests marked with options: SpLog.on(headers:, bodies:)), all and off; SpLog.off() (or SpLog.merge(options, off: true)) keeps one request out of the log even in all mode. Headers and bodies are included only when asked for; redaction (sensitive header names, body and query keys at any depth, credentials in the URL, 2048-unit truncation, <N bytes>, <multipart>, <stream>) is built in and cannot be disabled, and request ids are sanitised. The redaction rules are shared with @sokpheak/sp-laravel-api through the same fixture: sensitive keys include pin, pwd, pass, sig, authorization, cookie and keys ending in tokens, secrets, passwd, privatekey, signature, credential, otp, otp_code, recovery_codes and similar (error_code, country_code, idempotency_key stay visible); header names containing signature, pass, otp, jwt or bearer are redacted; the URLs in Link and Refresh headers, key=value pairs in URL fragments, comma-joined Filter.anyOf keys and dotted relation keys (sessions.pin) with a sensitive part, and filter groups (or=(...), and=(...)) and select embed filters (rel(cols,col=op.value)) whose column path (sessions.token) has a sensitive segment are redacted. Only plain data is walked: any other object in a body (a model with toJson, a Set) is logged as <object>; a body nested more than 100 levels is <unavailable>; JSON text is recognised after a BOM or NBSP; a query value holding a URL is redacted as a URL (2 levels); percent-decoding is tolerant and identical to the JS client. Redaction is a denylist of key names, not a guarantee. The sink runs inline; a sink that throws or returns a failing Future never changes the request result. Nothing changes for callers that do not set logger. New files: lib/src/logging.dart; shared fixture test/vectors/log_redaction.json.

  • Fix (realtime recovery): a rejoin whose confirmation arrives late, during the retry backoff, stops instead of sending more subscribe frames and reporting a false onSubscribeFailed. On a final rejoin failure onRecovered now fires before onSubscribeFailed, and an exception thrown by onSubscribeFailed is caught, so it no longer surfaces as an uncaught error or keeps onRecovered from firing. Unsubscribing (or a timed-out subscribe abandoning) the last channel a recovery was waiting for now completes the recovery.

  • Fix: a realtime socket that dies silently is now detected and replaced. After a pong timeout the client closes the socket and handles the loss itself: onDisconnected fires once and it reconnects. Before, WebSocketTransport.close() emitted no onDone, so isConnected stayed true and nothing reconnected. onAppResumed now reconnects at once while a ping is unanswered and, after a long pause, sends a ping at once (before, it called connect(), which returned at once on a connected client), so a socket that died in the background is replaced after pongTimeout. A new connection no longer reports isHealthy == false because of a ping sent on the previous one.

  • Behaviour change: SpRealtime.onAppResumed and onNetworkChanged reconnect only a client in use: one started with connect() (or subscribe()) and not stopped with disconnect() since. Before, an online event connected a fresh client (for example at app start, before login, since connectivity_plus emits the current state when listened to), and a resume revived a client the app had disconnected and re-sent its old subscribe frames. After dispose() both do nothing instead of throwing StateError.

  • Fix: a failed SpRealtime.connect no longer sticks. Before, every later connect() returned the same failed future without trying again. A failed attempt is now retried after reconnectDelay, doubling per consecutive failure up to 5 s, unless the client is offline, disconnected or disposed; a later connect(), resume or online event tries again at once. Reconnects started by onAppResumed, onNetworkChanged or the reconnect timer no longer raise uncaught errors. A connect() still waiting for the handshake now fails with SpApiError (network) when the socket closes first or when disconnect() or dispose() is called, instead of never completing. onDisconnected fires only for a connection that was established.

  • SpApi.getBytes and AttachmentsModule.viewBytes now return Uint8List instead of List<int>. A Uint8List response is returned as the same instance (no copy); other lists are converted. Uint8List is a List<int>, so existing callers keep compiling. Code that overrides or mocks getBytes or viewBytes (for example a mocktail stub) must now return a Uint8List, not a List<int>.

  • Behaviour change: SpRealtime.subscribe now completes only after the server confirms the channel with pusher_internal:subscription_succeeded, and can throw SpApiError with code timeout after subscribeTimeout (default 10 seconds). A timed-out or authorization-failed subscribe leaves no registered intent. A second subscribe to a confirmed channel sends no new frame; concurrent subscribers on a pending channel share one confirmation. A failed re-subscribe after a reconnect is retried up to subscribeAttempts (default 3) with exponential backoff from subscribeBackoff (default 300 ms, capped at 5 s) and then reported once through the new onSubscribeFailed(channel, error) callback. New optional SpRealtime constructor parameters: subscribeTimeout, subscribeAttempts, subscribeBackoff, onSubscribeFailed. Custom RealtimeTransport implementations and test fakes must deliver pusher_internal:subscription_succeeded for each pusher:subscribe, or subscribe times out. They also must not emit onDone for a connection they close with close(), not even later (cancel the stream subscription first, as WebSocketTransport does): SpRealtime handles that loss itself and may already be reconnecting, so a late onDone would tear down the new connection. Known limitation: the Pusher protocol has no correlation id, so a very late confirmation (more than subscribeTimeout) of an abandoned subscribe frame can complete a new subscribe to the same channel early.

  • Docs: README install snippet now targets ^0.1.0; new sections for rpc, SpApiError, the success: false envelope, pagination, the select rule, upsert availability, retries, per-request options, attachments, realtime recovery and pairing with sp_jwt_auth. Samples are compile-checked in example/readme_samples.dart and guarded by test/readme_test.dart. The missing-select error names requireSelect: false.

  • AttachmentsModule.upload (multipart form POST to sp_attachments/rpc/upload, bytes or filePath, visibility default private), link / unlink for record attachments, and viewBytes (authenticated GET rpc/{id}/view). Signed-URL methods and URL builders are unchanged.

  • TableGateway.list and serializeQuery accept direction (next or prev) and cursorColumn, sent as direction= and cursor_column=.

  • Behaviour change: an empty cursor is now sent as cursor= (empty string) instead of being remapped to 0; the backend treats both as the first page. cursor: null still sends no cursor.

  • Behaviour change: CursorPage.nextCursor is now meta['next_cursor'] whenever the backend provides it, regardless of item count (previously only on full pages). It is null when absent; offset mode still yields no cursor.

  • RecordEvent now exposes eventName (the broadcast event name), raw (the full payload as broadcast) and isRecord (true only when the payload has a string table and a map record). Non-record events such as courier_location.updated are delivered to the subscribe handler with all fields in raw. A non-map record no longer yields surprises: it gives an empty record and isRecord == false.

  • Behaviour change: added RecordAction.unknown. A payload with a missing or unrecognised action now maps to unknown instead of created. Exhaustive switch statements over RecordAction need a new case.

  • TableGateway.list/get/create/update/patch/remove/restore/upsert accept optional Options? options and CancelToken? cancelToken, forwarded to SpApi.request (per-request headers win over tenant/auth headers). Existing calls are unchanged.

  • SpApi.rpc accepts optional query (query parameters), method (override; default stays POST with a body, GET otherwise) and options (Dio Options merged into the request).

  • BREAKING (behaviour change): SpApi.request now throws SpApiError (status stays the HTTP status, e.g. 200) when a response with status < 400 has a JSON map body with success: false. Error code 10002 on such a response is routed through ApiAuth.handleUnauthorized() and retried once, like a 401. Bytes responses and non-map bodies are unaffected. Opt out with SpApi(treatSuccessFalseAsError: false) to restore the 0.1.0 behaviour.

  • SpApiError.retryAfter now also reads errors.retry_after_seconds (first element, int or numeric string; zero or negative ignored) as a last fallback after the Retry-After header and body retry_after. The value remains in fieldErrors.

  • SpApiError now carries the transport cause and stackTrace (the originating DioException) for status 0 failures, plus isTransport / isHttp getters. toString() never prints the cause.

  • iterate(), fetchFirst(), fetchLast() and cursorPagination().firstPage() now send cursor= (cursor mode) so the backend returns next_cursor; fetchPrev sends direction=prev; fetchLast keeps prevCursor null on a single short page. list with a null cursor is unchanged (offset mode).

  • CursorPage.nextCursor / hasMore: the backend sends next_cursor on every non-empty page, so the real end of the data is an empty page; docs updated.

  • Behaviour change: SpApiError.isTransport is now true only for network and timeout errors with status == 0; local errors (for example a missing select) also have status 0 but are not transport failures.

  • A 200 success: false envelope now maps error_code to SpApiError.code (10002 unauthenticated, 10008 forbidden, 10009 notFound, 10004 validation, 10010 server; others unknown).

  • Retried multipart uploads (after a 401, a 10002 envelope or a RetryConfig retry) now send a fresh FormData clone instead of failing with "already finalized".

  • Release note: the release containing the breaking treatSuccessFalseAsError default should be versioned 0.2.0.

0.1.0 - 2026-10-27 #

  • First stable release of sp_laravel_api for Dart and Flutter.
  • Added configurable RetryConfig with exponential backoff, full jitter, and Retry-After header parsing for transient HTTP errors.
  • Added remote OpenAPI schema resolution (--url, --schema, --header, --token, --tenant) to typegen CLI.
  • Added Sort.reversed() and cursor pagination boundary helpers (fetchFirst, fetchLast, fetchNext, fetchPrev, cursorPagination) on TableGateway.

0.1.0-beta.2 - 2026-10-27 #

  • Verified automated GitHub Actions OIDC publishing pipeline to pub.dev.
  • Enhanced CI hygiene tooling with default fallback checks.

0.1.0-beta.1 - 2026-10-27 #

  • Initial beta release of sp_laravel_api for Dart and Flutter.
  • Typed TableGateway with cursor and offset pagination.
  • Query builder serializing filters, relationships, and sorting.
  • Multi-broadcaster realtime engine for Laravel Reverb, Pusher, Soketi, and Ably.
  • Cross-platform support for VM, web, and Wasm.
1
likes
160
points
764
downloads

Documentation

API reference

Publisher

unverified uploader

Weekly Downloads

Typed REST client and multi-broadcaster realtime client for the SP Laravel backend packages.

Repository (GitHub)
View/report issues

Topics

#api #laravel #rest #realtime #reverb

License

MIT (license)

Dependencies

dio, meta, web_socket_channel

More

Packages that depend on sp_laravel_api