@literary-universe/sdk 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Literary Universe contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,399 @@
1
- # Temporary Holding Version
1
+ # Literary Universe SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ TypeScript and JavaScript client for the [Literary Universe](https://literaryuniverse.com)
4
+ authoring API. Use it to read your writing, save versioned drafts, create and
5
+ publish chapters, manage universe translations, and prepare or upload images.
6
+ The [CLI](https://github.com/LiteraryUniverse/cli) uses this SDK; Obsidian and local
7
+ MCP integrations can use the same client.
8
+
9
+ Read the [documentation in our feedback knowledge base](https://literaryuniverse.com/feedback/help)
10
+ for Literary Universe help. This README describes the SDK's current API contract.
11
+ Report SDK bugs in [this repository](https://github.com/LiteraryUniverse/sdk-typescript/issues).
12
+
13
+ The client uses the deployment's `/graphql` endpoint. The core client has no runtime dependencies and exports ESM and CommonJS builds. Local image preparation uses the optional Sharp dependency through the `/images` entry point. Node 22 or later and Bun are targets; see CI and local verification for tested versions. `/graphql` sends no CORS headers, so code running on another origin, including an Obsidian plugin, must pass a `fetch` that is not subject to CORS, for example one built on Obsidian's `requestUrl`.
14
+
15
+ ## Install
16
+
17
+ The source is MIT licensed. The package is still marked private and has not been
18
+ released to npm. Build a tarball from this repository with Node 22 or later:
19
+
20
+ ```sh
21
+ git clone https://github.com/LiteraryUniverse/sdk-typescript.git
22
+ cd sdk-typescript
23
+ npm ci
24
+ npm pack
25
+ ```
26
+
27
+ Install that tarball in your application:
28
+
29
+ ```sh
30
+ npm install /path/to/sdk-typescript/literary-universe-sdk-0.1.0.tgz
31
+ ```
32
+
33
+ The package includes its schema, generated types and image policy. Building or
34
+ packing it does not require the Literary Universe monorepo. Git dependencies
35
+ also build through the package's `prepare` script.
36
+
37
+ ## Quickstart
38
+
39
+ Create a personal API key in your Literary Universe account and grant only the
40
+ scopes your integration needs. The read example below needs `story:read`.
41
+ Provide the raw key through `LU_TOKEN` or your host application's secret store.
42
+
43
+ ```ts
44
+ import { LiteraryUniverseClient, LiteraryUniverseApiError } from '@literary-universe/sdk'
45
+
46
+ const client = new LiteraryUniverseClient({
47
+ baseUrl: 'https://literaryuniverse.com',
48
+ token: process.env.LU_TOKEN!,
49
+ })
50
+
51
+ const identity = await client.identity()
52
+ const page = await client.stories({ first: 25 })
53
+ const story = page.nodes[0]
54
+ if (story) {
55
+ const chapters = await client.chapters({ storyId: story.id })
56
+ const chapter = chapters.nodes.find((chapter) => chapter.hasDraft)
57
+ if (chapter) {
58
+ const draft = await client.draft({ id: chapter.id })
59
+ console.log(draft)
60
+ }
61
+ }
62
+
63
+ try {
64
+ await client.story({ id: 'another-story-id' })
65
+ } catch (error) {
66
+ if (error instanceof LiteraryUniverseApiError) {
67
+ console.error(error.code, error.requestId)
68
+ }
69
+ }
70
+ ```
71
+
72
+ `baseUrl` identifies the deployment, including any mount prefix. Use the raw API token without `Bearer`. Cookies are omitted. Redirects are not followed and fail with `REDIRECTED`, so use the final URL: `https://www.literaryuniverse.com` redirects to `https://literaryuniverse.com`. HTTPS is required except on loopback addresses; a private HTTP deployment can explicitly set `allowInsecureHttp: true`. Token prefixes describe generation conditions and do not create an isolated database or sandbox.
73
+
74
+ ## Supported reads
75
+
76
+ | Method | Scope | Result |
77
+ | --- | --- | --- |
78
+ | `identity()` | Any valid credential | API version, deployment label/URL, credential identity, granted scopes/restrictions and limits |
79
+ | `profile()` | `user:read` | Your user ID and optional username |
80
+ | `universes({first, after})` | `universe:read` | Paginated author/team universe headers |
81
+ | `universe({id})` | `universe:read` | Universe metadata and its translations, each with its `revision` |
82
+ | `stories({first, after})` | `story:read` | Paginated author/team story headers |
83
+ | `story({id})` | `story:read` | Story metadata and author notes |
84
+ | `chapters({storyId, language, first, after})` | `story:read` | Chapter headers without bodies |
85
+ | `draft({id, language})` | `story:read` | Stored working draft, including JSON, HTML/text/legacy representations and notes/counters |
86
+ | `encyclopediaEntries({universeId, first, after})` | `universe:read` | Paginated entry headers of a universe, drafts included |
87
+ | `encyclopediaEntry({id, language})` | `universe:read` | An entry with its summary, links and fields as plain text, in the original or a translated edition |
88
+ | `series({universeId})` | `universe:read` | The universe's saved series, each with its `version` and its stories in reading order |
89
+
90
+ Read access requires the person's current `draft.read` capability on the work or inherited universe. Personal credentials use current organization roles, including read-only view-all; removing a role affects subsequent requests. Organization keys are described under [Organization keys](#organization-keys). Fan fiction is readable by its author and that story's own team; the team of the universe it is set in does not inherit it.
91
+
92
+ Draft language defaults to the chapter's original language. An explicit translation returns that stored edition; a missing edition or unavailable permission returns `NOT_FOUND`. Draft JSON preserves editor nodes and marks without conversion. Titles, descriptions and `html` are returned as the app displays them, with the stored entity encoding removed. `text` and `markdown` are returned as stored, where a literal `<` or `>` is `&lt;` or `&gt;`. `updatedAt` is existing metadata, not an atomic write-precondition version. Draft reads return a server version. Versioned content saves, validation, recovery, chapter creation, publication, universe translations, story and universe details, chapter structure, encyclopedia entries and series are available.
93
+
94
+ Chapter headers include `hasDraft` for the requested edition. When a translation has not been created, its header retains the source title as a label, has `hasDraft: false`, and does not inherit the original's publication timestamp.
95
+
96
+ Lists default to 25 rows and accept 1–100. Follow `pageInfo.endCursor` while `hasNextPage` is true. Cursors are bound to the catalogue, credential restrictions and filters. They are ordered by stable IDs; chapter sequence is provided separately for writing order. Start a new traversal when changing credentials or catalogue inputs. Lists are live reads, not a database snapshot.
97
+
98
+ ## Universe translations
99
+
100
+ | Method | Scope | Result |
101
+ | --- | --- | --- |
102
+ | `createUniverseTranslation({universeId, language, input?})` | `universe:translate` or `universe:write` | `{created, translation}`; an already open language returns `created: false` and the stored translation |
103
+ | `updateUniverseTranslation({universeId, language, expectedRevision, input})` | `universe:translate` or `universe:write` | The saved translation with its new `revision` |
104
+
105
+ A translation is the universe's title and description in another language. Who may write one follows the workshop: the owner, an organization admin, a team member who edits the universe, or a translator of that language. Opening a language copies the original title and description unless `input` provides them, and opens the language for the universe's encyclopedia and universe blog as the workshop does. The original language is refused with `BAD_USER_INPUT`. Send plain text: the title holds up to 100 characters and the description up to 800. A `null` or omitted field stays as it is.
106
+
107
+ `expectedRevision` is the `revision` you read from `universe({id})`. Every change advances it, including saves in the browser workshop, which overwrite without a revision. When the translation is no longer at `expectedRevision` the update changes nothing and fails with `VERSION_CONFLICT`; the error's `currentRevision` says where it is now, so read it again and decide what to write. Translations saved before revisions existed are at revision 0.
108
+
109
+ Writes are never retried, whatever `maxRetries` says: a lost response to an applied update would come back from a retry as a conflict. A resource-restricted credential can write to the universes it selects.
110
+
111
+ ## Organization keys
112
+
113
+ An organization admin creates organization keys in the organization's settings, on the API keys tab, which the organization's `api` add-on opens. With `organization:read` alone a key reads the organization's public catalogue as a guest, for display on another site. With work scopes (`story:read`, `story:write`, `story:publish`, `universe:read`, `universe:write`, `universe:translate`) it acts as the organization itself: it has an organization admin's rights over the stories and universes the organization owns, and over the stories set in those universes, and over nothing else. It keeps working when the admin who created it leaves; revoke it to stop it. `identity()` reports it as `ORGANIZATION_API_KEY` with its `organizationId` and no `userId`. What it creates is recorded under the owner of the work it writes into, and the audit log names the key.
114
+
115
+ Organization keys cannot upload covers or chapter images yet; use a personal key for those.
116
+
117
+ ## Story details and visibility
118
+
119
+ | Method | Scope | Result |
120
+ | --- | --- | --- |
121
+ | `updateStory({storyId, input})` | `story:write` | The story header after the change |
122
+ | `setStoryVisibility({storyId, visibility})` | `story:write` | The story header; `privateAt` is set while it is hidden |
123
+
124
+ `input` takes `title`, `description`, `genres`, `tags`, `rating`, `license`, `language` and `universeId`; only the fields you give change. Moving a story to another universe takes the story owner's rights (the owner or an admin of the owning organization) and edit rights on the target universe, as the workshop does; `universeId: null` makes it standalone. A rating under staff review stays as it is (`FAILED_PRECONDITION`).
125
+
126
+ `PRIVATE` hides a published story from readers and its universe's story count; `PUBLIC` shows it again. A story that was never published fails with `BAD_USER_INPUT`.
127
+
128
+ ## Chapter structure
129
+
130
+ | Method | Scope | Result |
131
+ | --- | --- | --- |
132
+ | `renameChapter({id, language?, title})` | `story:write` | The chapter header with its new title |
133
+ | `reorderChapters({storyId, chapterIds})` | `story:write` | `{storyId, chapterIds}` in the new order |
134
+ | `removeChapter({id})` | `story:write` | `{id, storyId}` of the removed unpublished chapter |
135
+
136
+ Renaming and reordering apply to published chapters too, and readers see the change at once. A `language` renames that translation's title; without it the original is renamed, together with the story's list of chapters. `chapterIds` names every chapter of the story exactly once. Only a chapter never published, in any language or to beta readers, can be removed (`FAILED_PRECONDITION` otherwise); the chapters after it are renumbered. The only chapter of a story cannot be removed. A story whose arcs or free preview chapters count chapters keeps its structure: removal and reordering fail with `FAILED_PRECONDITION`. `removeChapter` is never retried.
137
+
138
+ ## Universe details
139
+
140
+ | Method | Scope | Result |
141
+ | --- | --- | --- |
142
+ | `updateUniverse({universeId, input})` | `universe:write` | The universe header after the change |
143
+
144
+ `input` takes `title`, `slug`, `description`, `genre`, `rating`, `license` and `language`. A `slug` is lowercase letters, digits and single hyphens; one in use by another universe fails with `CONFLICT`. `genre` is a genre value such as `fantasy`. A rating under staff review does not change (`FAILED_PRECONDITION`). Translations of the title and description go through `updateUniverseTranslation`.
145
+
146
+ ## Encyclopedia
147
+
148
+ | Method | Scope | Result |
149
+ | --- | --- | --- |
150
+ | `createEncyclopediaEntry({universeId, name, categoryTitle, ...})` | `universe:write` | The new draft entry |
151
+ | `updateEncyclopediaEntry({id, changes})` | `universe:write` | The entry after the change |
152
+ | `translateEncyclopediaEntry({id, language, ...})` | `universe:translate` or `universe:write` | The entry's edition in that language |
153
+ | `setEncyclopediaEntryPublication({id, published})` | `universe:write` | The entry, published or back to draft |
154
+ | `deleteEncyclopediaEntry({id})` | `universe:write` | `{id, universeId}` of the deleted entry |
155
+
156
+ A new entry is a draft in a category the universe offers, named by its title, and starts with the category's template fields. It can carry its first text right away: `pronunciation`, `tags`, `summary`, `parentName`, `relatedAdd`, and `fields` and `timeFields` by title. Other entries are named by their names. A name the universe already has fails with `CONFLICT`, and the error's `resourceId` is the existing entry. The plan of the universe's owner caps the number of entries (`FAILED_PRECONDITION`). Creation and deletion are never retried.
157
+
158
+ `changes` sets the same values in the original language and may also change `name` and `categoryTitle`, remove links with `relatedRemove`, and clear the parent with `parentName: null`. Text is plain; the server turns it into the editor's format. A text field of a new title is added; a field that holds something other than text is refused. `translateEncyclopediaEntry` writes an edition in a language the universe is translated into (`FAILED_PRECONDITION` otherwise): `name`, `pronunciation`, `summary` and `fields`, each named by its original title with an optional `translatedTitle`. A new edition starts as a copy of the original.
159
+
160
+ Publishing shows the entry to readers; unpublishing returns it to a draft. Deletion can be undone by staff and removes the entry from the parent and related links of the universe's other entries.
161
+
162
+ ## Series
163
+
164
+ | Method | Scope | Result |
165
+ | --- | --- | --- |
166
+ | `saveSeries({universeId, seriesId?, expectedVersion, title, storyIds})` | `universe:write` | The saved series with its new `version` |
167
+
168
+ A series is the reading order of stories in a universe. `storyIds` lists stories of the universe, not fan fiction, in order; the series workshop shows them in a row. Leave out `seriesId` and pass `expectedVersion: 0` to create one; to replace one, pass the `version` read from `series({universeId})`. A series changed since then fails with `VERSION_CONFLICT` and changes nothing. Saves are never retried. A universe holds up to 50 series.
169
+
170
+ ## Resource restrictions
171
+
172
+ Restricted credentials can be issued through the existing authenticated browser method; the resource picker belongs to the later developer-settings milestone:
173
+
174
+ ```js
175
+ await Meteor.callAsync('apiKeys.create', {
176
+ name: 'Obsidian reads',
177
+ scopes: ['story:read', 'universe:read'],
178
+ resourceRestrictions: { universeIds: ['SELECTED_UNIVERSE_ID'] },
179
+ })
180
+ ```
181
+
182
+ The method returns the token once. Keep it in your local secret store; never write it into an Obsidian vault or commit it. Existing expiry choices/default remain unchanged; the method still supports omitted expiry.
183
+
184
+ A selected universe covers its current and future descendant stories/chapters for these reads. A selected story covers itself and its chapters, without granting its parent universe. Containment comes from stored data and is checked again after moves. Selections supplement scopes and current user rights. Each category accepts at most 100 IDs; empty/malformed selections and inaccessible resources are rejected during issuance.
185
+
186
+ Restricted credentials are denied on legacy GraphQL operations and HTTP text exports that do not enforce these boundaries. Supported draft and universe-translation mutations enforce their stored resource boundaries. Protected media and AI remain session-only. Named SDK operations are client conveniences; server authorization applies to the GraphQL fields themselves.
187
+
188
+ ## Errors and limits
189
+
190
+ `LiteraryUniverseApiError` provides `code`, a safe message, optional `requestId`, HTTP `status`, `retryAfterSeconds`, `currentRevision` with `VERSION_CONFLICT`, and `resourceId` with `CONFLICT`. Partial GraphQL data is rejected whenever the response contains errors. Missing and inaccessible resources both return `NOT_FOUND`. Common server codes include `UNAUTHENTICATED`, `FORBIDDEN`, `BAD_USER_INPUT`, `GRAPHQL_VALIDATION_FAILED`, `NOT_FOUND`, `CONFLICT`, `FAILED_PRECONDITION`, `VERSION_CONFLICT`, `PAYLOAD_TOO_LARGE`, and `INTERNAL_SERVER_ERROR`. Client/transport codes include `INVALID_CONFIGURATION`, `INVALID_RESPONSE`, `REDIRECTED`, `NETWORK_ERROR`, `RATE_LIMITED`, `SERVICE_UNAVAILABLE`, `TIMEOUT` and `CANCELLED`. An HTTP failure without a GraphQL error, such as a 404 from a wrong mount prefix, is `INVALID_RESPONSE`.
191
+
192
+ Requests retain the 1 MiB JSON ceiling. A draft pull is limited to 8 MiB; requests containing author operations have a 16 MiB response ceiling. The SDK also stops reading at 16 MiB. IP/batch protection remains. Deployed API-key traffic also consumes atomic per-key and owner budgets shared across instances. GraphQL development skips limits except in E2E mode; image transfers always consume shared credential quotas. Top-level aliases are charged as operations; a single query is limited to 20 roots.
193
+
194
+ Timeout defaults to 30 seconds for the entire request, including retries; valid values are 1–120,000 milliseconds. Pass `{signal, timeoutMs}` as the final method argument to cancel or override it. Retries default to zero and can be configured with `maxRetries: 1` or `2` for network failures and transparent HTTP 429/503 responses. Authentication/permission failures are never retried. Retry-After waits above ten seconds return the throttle error to the caller.
195
+
196
+ ## Development and verification
197
+
198
+ ```sh
199
+ npm ci
200
+ npm run generate
201
+ npm run check:generated
202
+ npm run typecheck
203
+ npm test
204
+ ```
205
+
206
+ `operations.graphql` is validated against the package-local `schema.graphql` artifact. LU CI checks that export against the app contract. Operation types/documents are generated from the supported server contract. When changing the server contract in the monorepo, regenerate `app/graphql.schema.json`, run `node app/scripts/exportSdkSchema.mjs`, then run `npm run generate --prefix sdk`. Commit the updated schema and generated files in this repository before advancing the monorepo submodule pointer. Generation/build/pack work without a sibling app. No generated runtime code depends on Meteor, Mongo, React or GraphQL libraries.
207
+
208
+ Live acceptance tests belong to the [Literary Universe monorepo](https://github.com/StorytellerCZ/Literary-Universe). With its `sdk` submodule initialized, start the app with tracked `settings.ci.json`, `ENABLE_E2E=1`, its own `.meteor/e2e` build and an isolated local Mongo replica-set database ending in `_test`. Draft and recovery records commit together in a transaction. Set `LU_API_TEST_MONGO_URL` and optionally `LU_API_TEST_BASE_URL`, then run `node --experimental-strip-types app/scripts/testApiReadContract.mjs` from the monorepo root. It issues credentials through real DDP methods, installs the tarball into a clean Node consumer, checks GraphQL/HTTP boundaries, and removes only its own credentials/fixtures and temporary files. The test fixture provisioner uses the app's Mongo dependency; the external consumer imports only Node built-ins and this packed SDK.
209
+
210
+ ## Versioned draft writes
211
+
212
+ Use story:read and story:write to validate, save and consume the returned draft.
213
+ validateDraft accepts the same input as saveDraft, runs current permissions,
214
+ version and content checks, and returns warnings without changing content.
215
+
216
+ ```ts
217
+ const draft = await client.draft({ id: chapterId })
218
+ const input = { id: chapterId, language: draft.language, expectedVersion: draft.version,
219
+ operationId: crypto.randomUUID(), content: changedTiptapJson }
220
+ await client.validateDraft(input)
221
+ const saved = await client.saveDraft(input)
222
+ const before = await client.draftRecovery({ id: chapterId, recoveryId: saved.recoveryId })
223
+ ```
224
+
225
+ Retry an interrupted save with the same input and operation ID. A reused ID with
226
+ changed input yields IDEMPOTENCY_CONFLICT; a changed draft yields VERSION_CONFLICT.
227
+ The mutation changes body representations/counters only. Titles, notes, financial
228
+ settings and publication state are preserved. Supported browser nodes share one
229
+ schema; unsupported nodes become readable fallback with structured warnings.
230
+ The previous draft and saved response remain in a private recovery record for
231
+ 30 days, after which MongoDB's TTL cleanup removes them. Replay saves within that
232
+ window. An expired retry may return VERSION_CONFLICT; pull the current draft and
233
+ reconcile it before starting a new operation. Creation and publication receipts
234
+ do not expire with draft recovery.
235
+
236
+ The version covers the whole chapter, including its translations. A translation
237
+ body save can therefore conflict with an original-language edit. Title-only and
238
+ settings-only edits do not advance it.
239
+
240
+ The initial write ceiling is 900,000 serialized UTF-8 bytes. In deployed builds,
241
+ set server settings authorApi.draftWritesEnabled to true. Optional
242
+ authorApi.allowedUserIds limits rollout to selected accounts. Development builds
243
+ allow it by default; setting draftWritesEnabled false disables it there too.
244
+ Production publication also requires authorApi.publicationEnabled to be true.
245
+
246
+ ## Chapter lifecycle
247
+
248
+ ```ts
249
+ const created = await client.createChapter({ storyId, operationId: crypto.randomUUID(),
250
+ title: 'New chapter', content: tiptapJson })
251
+ const released = await client.publishChapter({ id: created.id, expectedVersion: created.version,
252
+ operationId: crypto.randomUUID(), publishAt: '2027-01-01T12:00:00Z' })
253
+ ```
254
+
255
+ createChapter requires story:write, appends in LU's chapter order, and returns
256
+ its ID/version, localized title and content warnings. Omitted content creates
257
+ an empty draft. It preserves story commercial settings and uses the normal
258
+ chapter defaults; isAIGenerated can be supplied explicitly. It does not publish.
259
+
260
+ publishChapter requires story:publish, separately issued by LU. READERS is the
261
+ default audience; BETA creates a private revision without changing reader release
262
+ dates. Existing translations can be selected by language. Missing publishAt means
263
+ now; an explicit timezone-bearing timestamp schedules that revision. Account/work
264
+ publication restrictions and course rules apply. A new Tiptap document is required
265
+ for canonical publication; save legacy drafts into that format first.
266
+
267
+ The matching draft, revision, listing changes, retry result and sjobs notification
268
+ jobs commit atomically. Publishing advances the draft version. publishedAt is the
269
+ revision's release time; chapterPublishedAt retains or advances the chapter's first
270
+ release time, matching LU's existing earlier-release behavior. The first original
271
+ chapter publishes its story; moving its scheduled release earlier also moves an
272
+ existing later story opening earlier. Universe visibility remains a separate LU operation;
273
+ a selected story does not implicitly grant publication of its parent universe.
274
+
275
+ Operation IDs are scoped to the credential owner and operation target, rather
276
+ than being globally unique. Saves use the chapter and resolved language; creation
277
+ uses the story; publication uses the chapter; image uploads use the purpose and
278
+ target. Reusing an ID for another target or action starts a separate operation.
279
+ Within that scope, changed input returns IDEMPOTENCY_CONFLICT. Use a fresh random
280
+ ID for each new operation and keep it unchanged for retries. Key rotation does
281
+ not create duplicates. Replays return the committed result after
282
+ current authorization, before new-write constraints. Creation metadata remains
283
+ durable after later deletion; retrying returns the original ID and does not recreate
284
+ the chapter. Recovery bodies are removed when the corresponding chapter is erased.
285
+
286
+ Browser creation/deletion use the shared transaction boundary. Browser/offline draft
287
+ saves retain their current UX; counters are recalculated from persisted editions.
288
+ API saves record challenge progress from that same transaction's word count, so
289
+ retrying an old save cannot move newer progress into an earlier day.
290
+ The legacy browser revision adapter remains separate from this API publication path.
291
+
292
+ Credential quotas default to 300 operations/minute/key for regular/staff keys,
293
+ 600 for premium keys, and three times the respective limit across the owner.
294
+ Server settings apiRateLimits.user and apiRateLimits.premium can tune the finite
295
+ key limit; owner limits scale with it. A failed shared store returns a retryable
296
+ 503. Rate diagnostics include Retry-After, remaining and reset headers.
297
+
298
+ Use the /project entry point for managed filesystem projects, or supply a
299
+ credential provider when the host owns storage/rotation:
300
+
301
+ ```ts
302
+ const client = new LiteraryUniverseClient({ baseUrl,
303
+ credentials: async signal => ({ kind: 'api-key', token: await getCurrentKey(signal) }),
304
+ clientName: 'my-integration/0.1' })
305
+ ```
306
+
307
+ The provider is covered by the request deadline. API keys remain the only
308
+ supported credential kind; the provider interface leaves room for deliberate
309
+ OAuth support later. Client names are bounded reported metadata for server audit.
310
+ There are no automatic telemetry providers or exporters.
311
+
312
+ ## Images
313
+
314
+ Install the existing supported image engine with `npm install sharp@0.35.5` in a
315
+ consumer that uses /images. The CLI installs it automatically. Core API calls and
316
+ policy reads do not load Sharp.
317
+
318
+ ```ts
319
+ import { readFile } from 'node:fs/promises'
320
+ import { prepareImage } from '@literary-universe/sdk/images'
321
+
322
+ const policy = await client.imagePolicy()
323
+ const image = await prepareImage(await readFile('scene.png'), 'chapter-image', { policy })
324
+ const asset = await client.uploadImage({ ...image, targetId: chapterId,
325
+ operationId: crypto.randomUUID() })
326
+
327
+ const cover = await prepareImage(await readFile('cover.png'), 'story-cover', { policy })
328
+ await client.setCover({ kind: 'story', id: storyId, bytes: cover.bytes, type: cover.type })
329
+ ```
330
+
331
+ Preparation runs locally in a killable subprocess. It accepts single-frame raster
332
+ images, corrects EXIF orientation, strips metadata, preserves transparency, and
333
+ resizes/compresses to the selected purpose's finite limits. A forced JPEG output
334
+ is rejected when it would discard transparency. SVG, document and multi-frame
335
+ inputs require an explicit raster/single-frame export. Originals remain untouched;
336
+ no remote references are fetched. A crop must be explicit: `{crop: {left, top,
337
+ width, height}}` uses pixels after orientation. A wrong enforced ratio returns
338
+ CROP_REQUIRED. Recommended cover dimensions do not impose a resize.
339
+
340
+ The versioned policy is packaged for offline use and available from imagePolicy.
341
+ LU and the SDK consume exported copies of the same policy data. The initial
342
+ processing bounds are 50 MiB source bytes, 40 million source pixels, 16 million
343
+ output pixels and ten seconds, including metadata parsing. Smaller server limits
344
+ apply; larger remote limits never raise the SDK's local processing ceilings.
345
+ Story/universe covers, chapter and encyclopedia images, blog images and headers
346
+ have a 5 MiB upload ceiling; blog logos have 2 MiB. Covers enforce 2:3 and 1:1;
347
+ blog post images use 16:9 with a consistent 1200×675 recommendation.
348
+
349
+ uploadImage creates a public asset in LU's existing ImagesCollection/storage. It
350
+ returns an ID, URL, digest, size and dimensions. It does not attach, replace or
351
+ publish content. Use story:write for chapter images, universe:write for
352
+ encyclopedia illustrations, and blog:write for blog assets. It refuses cover
353
+ purposes: setCover replaces a story's (story:write) or universe's
354
+ (universe:write) cover through `PUT /api/{stories,universes}/:id/cover`, which
355
+ crops to the cover shape and stores WebP. It takes no operation ID; retrying sets
356
+ the same cover again. Prepare with the cover purposes to stay within 5 MiB.
357
+ Current target capabilities, course rules, plan restrictions and selected-resource
358
+ boundaries still apply. Chapter uploads target a chapter, encyclopedia uploads
359
+ an entry, and blog purposes target their blog. Chapter
360
+ images currently target the original edition; translation-specific asset writes
361
+ remain to add. Restricted story/universe keys cannot target blogs. Universe/blog
362
+ write scopes currently enable asset creation; broader editing contracts are later.
363
+
364
+ Binary transfers use /api/author/images, bypassing the GraphQL JSON ceiling. LU
365
+ checks the actual format, full decode, bytes, geometry and ratio. Requests cost ten
366
+ ordinary operations against shared key/owner quotas. Concurrent transfers are
367
+ bounded to one per key, three per owner and eight per deployment, with four
368
+ decoders per server process. Body transfer has a twenty-second deadline; decoding
369
+ has a killable ten-second deadline. Unavailable enforcement/storage fails closed.
370
+ Transfer and intent leases renew while work is active; renewal calls are bounded
371
+ to ten seconds and the final asset/result transaction to twenty-five seconds.
372
+ Production uses the existing authorApi.draftWritesEnabled/allowedUserIds rollout.
373
+
374
+ Keep the prepared bytes and operation ID for retry. Changed input yields
375
+ IDEMPOTENCY_CONFLICT; committed replay returns the original asset after current
376
+ authorization, including after credential rotation or a smaller current purpose
377
+ limit, within the fixed 5 MiB transport ceiling. New input using an old policy
378
+ returns POLICY_CHANGED. An ambiguous storage/commit failure may require waiting
379
+ for its 90-second lease; retry checks the deterministic storage key's digest
380
+ before creating bytes again. Safe API/client attribution uses LU's existing audit
381
+ collection. Storage remains public; protected comic/audio files use other contracts.
382
+
383
+ For live image checks, configure an isolated local S3-compatible test endpoint in
384
+ the test server's Backblaze settings, then run `node app/scripts/testApiImageContract.mjs` from the monorepo root with the same
385
+ local _test database variables as test:integration. Real Backblaze verification
386
+ remains a separate rollout check.
387
+
388
+ Platform CI runs the package checks on Windows and macOS, including both Intel
389
+ and Apple Silicon Macs. These checks cover extracted builds, packed consumers,
390
+ image preparation/cancellation and CLI credential storage. Local project and
391
+ source JSON files accept UTF-8 BOM and CRLF; chapter filenames must be distinct
392
+ ignoring case so moving a project between these filesystems cannot overwrite a
393
+ different chapter.
394
+
395
+ The monorepo provides a local storage fixture: run
396
+ `node app/scripts/serveApiImageTestStorage.mjs /tmp/lu-image-settings.json`, start
397
+ the isolated Meteor test server with that settings file, and stop both owned
398
+ processes after verification. The fixture uses synthetic credentials and checks
399
+ real S3 transport without contacting Backblaze. It is not a production server.