@civitai/app-sdk 0.56.1 → 0.58.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/README.md CHANGED
@@ -137,8 +137,9 @@ interface BlockInitPayload {
137
137
  | `BLOCK_SCOPES` / `BLOCK_SCOPE_PATTERN` | Every known block scope string (the authoritative enum the canonical schema validates `scopes` against) + the `domain:verb:target` format-helper regex. Read the current set from `BLOCK_SCOPES` itself — scopes are added and retired, so no count is quoted here. A scope is valid only if it's a member of `BLOCK_SCOPES`, matching the [canonical schema](https://civitai.com/schemas/app-block/v1.json). |
138
138
  | `isMessage(data, type)` | Discriminator-only message narrowing (see above). |
139
139
  | `isModelSlotContext(ctx)` / `isPageSlotContext(ctx)` | Runtime narrowing for the `slotId`-discriminated `BlockContext` union. Real checks on a value that crossed a `postMessage` boundary — they verify every field they assert, not just `slotId`. |
140
+ | `fetchNestedDocument(opts)` | Embed one of your OWN bundled documents as an iframe `srcdoc`, because a nested `<iframe src>` of your own content **cannot load** — see [Nested documents](#nested-documents) below. `NestedDocumentError` carries a `.code` of `'invalid-url' \| 'http-error' \| 'network-error'`. |
140
141
  | `isSignedIn(viewer)` | **The sign-in gate.** `isSignedIn(useBlockContext().viewer)` — do not open-code it as `viewer !== null` or `viewer?.signedIn === true`. Which of those is correct has already changed once with the host contract, and this is the one place it is decided. It reads neither `viewer.id` nor `viewer.username` (both `@deprecated`), so nothing written through it changes when those are removed. Need the identity rather than the presence? `useViewer()` — scope-gated and audited per call. |
141
- | types | `BlockManifestV1`, `ManifestSettings` (+ field types), `BlockContext`, `ModelSlotContext`, `BlockCheckpointInfo`, `ShowcaseImage`, `BlockToken`, `WrappedToken`, `BlockSettings`, `ViewerInfo`, `Theme`, `WorkflowBody`, `BlockTextToImageParams`, `WorkflowBodyCustomComfy` (+ its two arms `WorkflowBodyCustomComfyRecipe` / `WorkflowBodyCustomComfyInline`, and `InlineComfyNode`), `WorkflowBodyStep` / `WorkflowBodyPassThroughStep` (the two arms of `kind: 'step'`), `BlockWorkflowSnapshot`, `WorkflowStatus`, `BlockInitPayload`, `ParentToBlockMessage`, `BlockToParentMessage`. |
142
+ | types | `BlockManifestV1`, `ManifestSettings` (+ field types), `BlockContext`, `ModelSlotContext`, `BlockCheckpointInfo`, `ShowcaseImage`, `BlockToken`, `WrappedToken`, `BlockSettings`, `ViewerInfo`, `Theme`, `WorkflowBody`, `BlockTextToImageParams`, `WorkflowBodyCustomComfy` (+ its two arms `WorkflowBodyCustomComfyRecipe` / `WorkflowBodyCustomComfyInline`, and `InlineComfyNode`), `WorkflowBodyStep` / `WorkflowBodyPassThroughStep` (the two arms of `kind: 'step'`), `WorkflowBodyTraining` (+ `AiToolkitTrainingParams`, `BlockTrainingQuote`, `BlockTrainingDatasetItem`, `BlockTrainingDatasetResult` and the `BLOCK_TRAINING_*` bounds), `BlockWorkflowSnapshot`, `WorkflowStatus`, `BlockInitPayload`, `ParentToBlockMessage`, `BlockToParentMessage`. |
142
143
 
143
144
  `WorkflowBody`'s `customComfy` member is a discriminated union on `mode`, mirroring
144
145
  the host's `blockCustomComfyMemberSchema`. Narrow on the VALUE (`body.mode === 'inline'`),
@@ -171,8 +172,29 @@ own key:
171
172
  and the host forwards `input` unmodified. There is no registry lookup, no param schema, no
172
173
  prompt audit and no AIR scan; what bounds it is a denylist of platform-internal `$type`s
173
174
  (scanners, moderation classifiers, hashing/model ingestion, web egress), a 64-character
174
- `$type` cap, a 256 KB `input` cap, and `maxBuzz` — which, as on the inline arm, is **also the
175
- step timeout in seconds**.
175
+ `$type` cap, a 256 KB `input` cap, and the spend reservation. **Unlike the inline arm, `maxBuzz`
176
+ is not always the timeout here**: on both `estimate` and `submit` the host asks the orchestrator
177
+ for a `whatif` quote of the step. **Quoted** → it reserves `max(maxBuzz, quote)`, gated against
178
+ the token's per-call budget (`token.buzzBudget`, capped at 1000 on a production token — so the
179
+ reservation can exceed the 1–250 `maxBuzz` range), and stamps **no** step timeout.
180
+ **Unquoted** → `maxBuzz` is both the reservation and the step timeout in seconds; the timeout
181
+ bounds wall-clock time, and spend only for a step billed by compute time — a step priced per
182
+ unit can bill above `maxBuzz`. `estimate` returns the reservation as `cost.total`; it is not a
183
+ guaranteed maximum. Full rules: `WorkflowBodyPassThroughStep.maxBuzz`.
184
+
185
+ `training` and `imageResourceTraining` are **not** on that denylist — the host allows them on
186
+ this arm by an explicit operator decision. They get no special treatment: the quoted/unquoted
187
+ rules above apply to them as to any other `$type`. Whether a given training input is quoted,
188
+ and at what price, is the orchestrator's answer — read it from `estimate` before submitting.
189
+ The trained checkpoint is not part of the block contract (an older
190
+ host may still leak checkpoint urls into `imageUrls` / `stepOutputs` — a host defect, never
191
+ something to build on); a host that supports it reports the trained epochs on
192
+ `snapshot.trainedEpochs` (and on each `AppWorkflow` row of the app-queue read) without the
193
+ checkpoint, and the viewer publishes
194
+ one by being navigated (`useCivitaiNavigate`, `scope: 'site'`) to Civitai's own model wizard at
195
+ `models/train/from-orchestrator?workflowId=<id>&epoch=<n>`. `snapshot.publishedModel` (and
196
+ `AppWorkflow.publishedModel`) then reports the resulting model. These fields are absent on hosts
197
+ that predate them.
176
198
 
177
199
  ```ts
178
200
  import type { WorkflowBody } from '@civitai/app-sdk/blocks';
@@ -186,6 +208,18 @@ const body: WorkflowBody = {
186
208
  };
187
209
  ```
188
210
 
211
+ `WorkflowBodyTraining` (`kind: 'training'`) is the **quoted** way to train: an ai-toolkit LoRA
212
+ run on a dataset Civitai prepared from the viewer's own images, mirroring the host's
213
+ `blockTrainingBodySchema` (civitai/civitai#5434). There is no `maxBuzz` and no timeout — the
214
+ `estimate` reply carries `snapshot.trainingQuote` (`quoteId`, `total`, `imageCount`,
215
+ `expiresAt`), and the run starts only through the `RUN_TRAINING` bridge, after the viewer
216
+ confirms that price in Civitai's own dialog. A confirmed run may exceed the token's per-call
217
+ budget, up to `BLOCK_TRAINING_MAX_BUZZ_PER_RUN` (5,000). Page apps only, `ai:write:budgeted`,
218
+ behind the host flag `app-blocks-training-kind` (off by default), and refused from development
219
+ and review sessions. The dataset is prepared over `PREPARE_TRAINING_DATASET`
220
+ (civitai/civitai#5438). Use it through `@civitai/blocks-react`'s `usePrepareTrainingDataset()`
221
+ and `useRunTraining()`.
222
+
189
223
  ### `defineBlock` validator rules
190
224
 
191
225
  **There is no rule list here, and that is the point.** `defineBlock` does not
@@ -320,10 +354,58 @@ const { Viewer } = await import(viewerModuleSpecifier);
320
354
  for each global it actually replaced. `createMemoryStorage()` is exported too,
321
355
  if you want the standalone `Storage` work-alike.
322
356
 
357
+ ### Nested documents
358
+
359
+ 🔴 **A nested `<iframe src="…">` pointing at your own bundled content cannot
360
+ load, and no manifest change fixes it** — your block's origin is opaque and the
361
+ static host stamps `frame-ancestors` + `X-Frame-Options` on every path it
362
+ serves. The full derivation, the dated external browser matrix (an
363
+ observation of the platform — nothing in this repo verifies it) and the known
364
+ limits
365
+ are in one place: the header of
366
+ [`src/blocks/nestedDocument.ts`](src/blocks/nestedDocument.ts).
367
+
368
+ **Prefer a single-document design.** An engine build (Defold, Unity WebGL,
369
+ Phaser) is a `<canvas>` plus a JS loader that normally mounts straight into the
370
+ document you hand it, which avoids the whole problem class.
371
+
372
+ When a separate document is genuinely required, fetch it and inline it as the
373
+ iframe's `srcdoc` — that frame inherits your opaque origin and carries no
374
+ response headers of its own:
375
+
376
+ ```ts
377
+ import { fetchNestedDocument } from '@civitai/app-sdk/blocks';
378
+
379
+ const { srcDoc, baseHref } = await fetchNestedDocument({ src: '/game/index.html' });
380
+ // baseHref === 'https://<blockId>.civit.ai/game/'
381
+ const frame = document.createElement('iframe');
382
+ frame.setAttribute('sandbox', 'allow-scripts'); // your own; it does not inherit
383
+ frame.srcdoc = srcDoc;
384
+ ```
385
+
386
+ The injected `<base href>` is the mechanism: a `srcdoc` document's base URL is
387
+ `about:srcdoc`, inheriting yours, so every relative `src=` in the fetched markup
388
+ would otherwise resolve to nothing. The base is the directory of the
389
+ **response's final URL**, so a redirect is followed rather than resolved one
390
+ directory too high. A document that already declares a `<base href>` has that
391
+ one resolved against the final URL and replaced — the base the parser uses is
392
+ always absolute. It is **not** a de-duplication: markup declaring two
393
+ `<base href>` tags comes back with two, the first (the only one a parser
394
+ honours) rewritten and the second left inert. Only real markup counts — a
395
+ `<base>` or a `<head>` inside a comment or an inline `<script>`/`<style>` body
396
+ is ignored, and tag names match case-insensitively.
397
+
398
+ **The returned string is NOT sanitized**, on purpose — it is your own markup and
399
+ scripts, verbatim, and stripping them would remove the thing the nested document
400
+ exists to run. Only pass a `src` you control. React callers want
401
+ `useNestedDocument()` from
402
+ [`@civitai/blocks-react`](../civitai-blocks-react/README.md).
403
+
323
404
  ### Version compatibility
324
405
 
325
406
  | `@civitai/app-sdk` | adds (blocks surface) |
326
407
  |---|---|
408
+ | `0.57.0` | `fetchNestedDocument` / `NestedDocumentError` — the `srcdoc` escape hatch for embedding your own bundled documents |
327
409
  | `0.27.0` | `@civitai/app-sdk/safe-storage` — opaque-origin `localStorage`/`sessionStorage` shim, auto-installed by the `blocks` subpath |
328
410
  | `0.24.0` | `QUERY_APP_WORKFLOWS` / `CANCEL_APP_WORKFLOW` messages + the `AppWorkflow` type (app generator subqueue, PR #3164) |
329
411
  | `0.7.0` | `CANCEL_WORKFLOW` / `WORKFLOW_CANCELED` messages (real cancel, gotcha #51) |
@@ -446,7 +528,7 @@ The starters in `civitai/civitai-app-starters` wire this into framework-specific
446
528
 
447
529
  ## Choosing a workflow step type
448
530
 
449
- The orchestrator is a workflow API: each request submits a list of typed steps. `WORKFLOW_STEP_TYPES` is the in-code catalog of every step `$type` it accepts, with a one-line description for each — `textToImage`, `imageGen`, `videoGen`, `comfy`, `customComfy`, `textToSpeech`, `aceStepAudio`, `transcription`, `imageUpscaler` among them (51 in total).
531
+ The orchestrator is a workflow API: each request submits a list of typed steps. `WORKFLOW_STEP_TYPES` is the in-code catalog of every step `$type` it accepts, with a one-line description for each — `textToImage`, `imageGen`, `videoGen`, `comfy`, `customComfy`, `textToSpeech`, `aceStepAudio`, `transcription`, `imageUpscaler` among them (53 in total).
450
532
 
451
533
  The catalog is pinned to the orchestrator's published OpenAPI spec two ways — an offline unit test against a transcribed copy of the spec's `WorkflowStepTemplate` discriminator mapping, and a CI job (`pnpm check:catalogs`) that re-fetches the live spec and diffs it. If a `$type` is listed here, the orchestrator accepts it.
452
534
 
@@ -521,15 +603,15 @@ What it exports:
521
603
 
522
604
  | Export | What |
523
605
  |---|---|
524
- | `WorkflowStepTemplates` | `$type` → template type, for 47 of the catalog's 51 step types. Keyed by the WIRE name, which the generated type names don't always match (`model3DPreview` → `Model3dPreviewStepTemplate`). |
606
+ | `WorkflowStepTemplates` | `$type` → template type, for 47 of the catalog's 53 step types. Keyed by the WIRE name, which the generated type names don't always match (`model3DPreview` → `Model3dPreviewStepTemplate`). |
525
607
  | `WorkflowStepTemplateFor<'videoGen'>` | One step's template. |
526
608
  | `WorkflowStepInputFor<'videoGen'>` | One step's `input` shape, without needing the generated `*Input` name. |
527
609
  | `AnyWorkflowStepTemplate` | Discriminated union of all 47 mapped templates — `Extract<…, { $type: 'comfy' }>` and exhaustive `switch` work. `@civitai/client`'s base `WorkflowStepTemplate` has `$type` as a bare `string`, so it narrows nothing. |
528
610
  | `TypedWorkflowTemplate` | The submit envelope with `steps` narrowed to that union. Pass it straight to `submitWorkflow` / `estimateWorkflow`. |
529
611
 
530
- > 🔴 **The map is not total over the catalog, and that is the expected state.** `WORKFLOW_STEP_TYPES` documents 51 `$type`s; this map covers 47. The 4 with no generated template in the pinned `@civitai/client` are `imageScanning`, `preprocessVideo`, `soniloAudioGen`, `yuE2`, and `WorkflowStepTemplateFor<…>` is a compile error for each of them.
612
+ > 🔴 **The map is not total over the catalog, and that is the expected state.** `WORKFLOW_STEP_TYPES` documents 53 `$type`s; this map covers 47. The 6 with no generated template in the pinned `@civitai/client` are `imageScanning`, `liveTranscription`, `merge`, `preprocessVideo`, `soniloAudioGen`, `yuE2`, and `WorkflowStepTemplateFor<…>` is a compile error for each of them.
531
613
  >
532
- > The two surfaces move independently on purpose: the catalog tracks the **live** orchestrator spec (a daily job syncs it), while these types track whatever `@civitai/client` was last published from. So the catalog runs ahead and the client catches up. The gap is never silent — `test/orchestrator/step-templates.test-d.ts` carries it as a `never` ledger plus one `@ts-expect-error` per gap `$type`, and `test/orchestrator/step-count-prose.test.ts` derives all four numbers (51, 47, 4, and the names) from `WORKFLOW_STEP_TYPES` and the map's own AST, then fails if this paragraph or its twin in `src/orchestrator/steps.ts` disagrees by one character.
614
+ > The two surfaces move independently on purpose: the catalog tracks the **live** orchestrator spec (a daily job syncs it), while these types track whatever `@civitai/client` was last published from. So the catalog runs ahead and the client catches up. The gap is never silent — `test/orchestrator/step-templates.test-d.ts` carries it as a `never` ledger plus one `@ts-expect-error` per gap `$type`, and `test/orchestrator/step-count-prose.test.ts` derives all four numbers (53, 47, 6, and the names) from `WORKFLOW_STEP_TYPES` and the map's own AST, then fails if this paragraph or its twin in `src/orchestrator/steps.ts` disagrees by one character.
533
615
 
534
616
  The generated `*StepTemplate` and `*Input` types are **not** re-exported individually. Using this subpath already requires `@civitai/client` installed, so if you want one by name, import it straight from there — `import type { TextToImageStepTemplate } from '@civitai/client'`.
535
617
 
@@ -564,9 +646,11 @@ A `$type` having a type here says nothing about whether you may submit it.
564
646
  - **App Blocks** don't reach the orchestrator at all. A block posts a `WorkflowBody` to the host, which validates it server-side against its own schema. That contract is `@civitai/app-sdk/blocks` and is completely unaffected by this subpath.
565
647
  - **Standalone apps / BFFs** submit directly with the user's OAuth token, and the orchestrator applies its own authorization. A body that compiles can still come back 400 or 403.
566
648
 
567
- Several of the 47 exist to serve Civitai's own pipelines rather than third-party apps — `modelPickleScan`, `xGuardModeration`, `training`, `comfyNodepackSnapshot`, `qwenImageBench`, the `model*`/`media*` hashing and classification steps. They're in the consumer spec, so they're typed here. They are not an invitation.
649
+ Several of the 47 exist to serve Civitai's own pipelines rather than third-party apps — `modelPickleScan`, `xGuardModeration`, `comfyNodepackSnapshot`, `qwenImageBench`, the `model*`/`media*` hashing and classification steps. They're in the consumer spec, so they're typed here. They are not an invitation.
650
+
651
+ `training` and `imageResourceTraining` are the exception: an App Block's host explicitly **allows** them on the pass-through arm (see `WorkflowBodyPassThroughStep` under Primitives above for the `maxBuzz` bound, and how a trained epoch is published). For a standalone app, the orchestrator's own authorization still decides.
568
652
 
569
- Note that `WORKFLOW_STEP_TYPES` does **not** mark most of them: of its 51 entries exactly two — `comfyNodepackSnapshot` and `qwenImageBench` — sit under its "Platform internals" heading, and the rest are ordinary documented entries (`webScrape` even carries usage notes). The reason the platform steps are typed anyway is not that the catalog flags them as internal; it's that the catalog *documents* them, so skipping them would make `WorkflowStepTemplateFor<'training'>` a compile error for a step type the SDK documents — which is exactly what is live today for the 3 `$type`s the pinned client cannot type, and is why that gap is spelled out above rather than left to be discovered.
653
+ Note that `WORKFLOW_STEP_TYPES` does **not** mark most of them: of its 53 entries exactly two — `comfyNodepackSnapshot` and `qwenImageBench` — sit under its "Platform internals" heading, and the rest are ordinary documented entries (`webScrape` even carries usage notes). The reason the platform steps are typed anyway is not that the catalog flags them as internal; it's that the catalog *documents* them, so skipping them would make `WorkflowStepTemplateFor<'training'>` a compile error for a step type the SDK documents — which is exactly what is live today for the 3 `$type`s the pinned client cannot type, and is why that gap is spelled out above rather than left to be discovered.
570
654
 
571
655
  ## Public vs. confidential clients
572
656
 
@@ -36,20 +36,16 @@
36
36
  * `PAYLOAD_TOO_LARGE` sites, so it missed the entire authorization family.
37
37
  * 2. **Draft 2 (RETRACTED)** kept the six, added a table of eight
38
38
  * authorization messages "measured in the same read", and presented THAT
39
- * as the surface. Also wrong. It missed, in the same file: `Apps are not
40
- * enabled`, thrown from TWO different gates with one spelling — the
41
- * `enforceAppBlocksFlag` middleware (defined `:249`, throws at `:255`
42
- * query / `:257` mutation), which is `.use()`d on all five storage
43
- * procedures at `:470`, `:509`, `:938`, `:1022`, `:1106` BEFORE their
44
- * `.input()`, so it fires before anything else on every call; and
45
- * `assertAppBlocksEnabledForTokenUser` (`:139-155`, throwing at `:153`),
46
- * reached from `resolveStorageContext`. Grepping `enforceAppBlocksFlag`
47
- * will NOT find `:153`. Also missed: `block token subject could
48
- * not be resolved` (`:148`, called unconditionally from
49
- * `resolveStorageContext`), `review token subject could not be resolved`
50
- * (`:82`) and `Apps authoring is not enabled for this account` (`:89`).
51
- * `Apps are not enabled` is a feature-flag kill switch — neither a ceiling
52
- * nor an authorization failure, so it fit neither published table.
39
+ * as the surface. Also wrong: it missed four more messages in the same
40
+ * host file, one of which was neither a ceiling nor an authorization
41
+ * failure and so fit neither of its published tables.
42
+ *
43
+ * 🔴 **Which messages those were, and which host code raises them, is
44
+ * deliberately NOT recorded here.** The retracted drafts spelled it out down to
45
+ * line numbers in the host's router — a citation nothing in this repository can
46
+ * check, and one that any unrelated edit upstream invalidates silently. Read it
47
+ * off the host when you need it (see "Re-deriving it" below); do not write the
48
+ * answer back into this comment.
53
49
  *
54
50
  * Each enumeration was wider than the last and each was still short; the
55
51
  * router carries **21** `throw new TRPCError` sites and **17** distinct
@@ -248,10 +244,9 @@ export declare const APP_STORAGE_ERROR_REQUEST_FAILED = "storage request failed"
248
244
  *
249
245
  * - The bridge's catch arms are blanket, so every other rejection the host
250
246
  * raises arrives on the SAME field and is absent here on purpose. `invalid
251
- * block token`, `block instance revoked`, `Apps are not enabled` and the
252
- * `storage … scope` template are examples of what that covers —
253
- * **illustrations, not a bound.** See this file's header for why no list
254
- * of them lives in this repository.
247
+ * block token`, `block instance revoked` and the `storage … scope` template
248
+ * are examples of what that covers — **illustrations, not a bound.** See
249
+ * this file's header for why no list of them lives in this repository.
255
250
  * - 🔴 The host also enforces **size ceilings zod-side** (`key` capped at 200
256
251
  * characters on the `.input()` schema, and three more on `list`). Those
257
252
  * throw no `TRPCError`, so they are invisible to the re-derivation recipe
@@ -322,9 +317,8 @@ export type AppStorageRejectionReason = 'value-too-large' | 'app-quota-exceeded'
322
317
  * failure.** The bridge's catch arms are blanket, so every other rejection
323
318
  * the host raises arrives on the same field and classifies `null` — for
324
319
  * example `invalid block token` (an expired token mid-session), `block
325
- * instance revoked`, `storage set requires the apps:storage:write scope`,
326
- * or `Apps are not enabled` (the feature flag, which fires before anything
327
- * else on every storage call). 🔴 **Those are ILLUSTRATIONS, not the set**:
320
+ * instance revoked`, or `storage set requires the apps:storage:write
321
+ * scope`. 🔴 **Those are ILLUSTRATIONS, not the set**:
328
322
  * see this module's header for why no list of them lives here.
329
323
  * - 🔴 **and a zod INPUT-VALIDATION refusal, which never reaches a handler at
330
324
  * all.** tRPC parses `.input()` before the procedure body, so a bound
@@ -36,20 +36,16 @@
36
36
  * `PAYLOAD_TOO_LARGE` sites, so it missed the entire authorization family.
37
37
  * 2. **Draft 2 (RETRACTED)** kept the six, added a table of eight
38
38
  * authorization messages "measured in the same read", and presented THAT
39
- * as the surface. Also wrong. It missed, in the same file: `Apps are not
40
- * enabled`, thrown from TWO different gates with one spelling — the
41
- * `enforceAppBlocksFlag` middleware (defined `:249`, throws at `:255`
42
- * query / `:257` mutation), which is `.use()`d on all five storage
43
- * procedures at `:470`, `:509`, `:938`, `:1022`, `:1106` BEFORE their
44
- * `.input()`, so it fires before anything else on every call; and
45
- * `assertAppBlocksEnabledForTokenUser` (`:139-155`, throwing at `:153`),
46
- * reached from `resolveStorageContext`. Grepping `enforceAppBlocksFlag`
47
- * will NOT find `:153`. Also missed: `block token subject could
48
- * not be resolved` (`:148`, called unconditionally from
49
- * `resolveStorageContext`), `review token subject could not be resolved`
50
- * (`:82`) and `Apps authoring is not enabled for this account` (`:89`).
51
- * `Apps are not enabled` is a feature-flag kill switch — neither a ceiling
52
- * nor an authorization failure, so it fit neither published table.
39
+ * as the surface. Also wrong: it missed four more messages in the same
40
+ * host file, one of which was neither a ceiling nor an authorization
41
+ * failure and so fit neither of its published tables.
42
+ *
43
+ * 🔴 **Which messages those were, and which host code raises them, is
44
+ * deliberately NOT recorded here.** The retracted drafts spelled it out down to
45
+ * line numbers in the host's router — a citation nothing in this repository can
46
+ * check, and one that any unrelated edit upstream invalidates silently. Read it
47
+ * off the host when you need it (see "Re-deriving it" below); do not write the
48
+ * answer back into this comment.
53
49
  *
54
50
  * Each enumeration was wider than the last and each was still short; the
55
51
  * router carries **21** `throw new TRPCError` sites and **17** distinct
@@ -251,10 +247,9 @@ export const APP_STORAGE_ERROR_REQUEST_FAILED = 'storage request failed';
251
247
  *
252
248
  * - The bridge's catch arms are blanket, so every other rejection the host
253
249
  * raises arrives on the SAME field and is absent here on purpose. `invalid
254
- * block token`, `block instance revoked`, `Apps are not enabled` and the
255
- * `storage … scope` template are examples of what that covers —
256
- * **illustrations, not a bound.** See this file's header for why no list
257
- * of them lives in this repository.
250
+ * block token`, `block instance revoked` and the `storage … scope` template
251
+ * are examples of what that covers — **illustrations, not a bound.** See
252
+ * this file's header for why no list of them lives in this repository.
258
253
  * - 🔴 The host also enforces **size ceilings zod-side** (`key` capped at 200
259
254
  * characters on the `.input()` schema, and three more on `list`). Those
260
255
  * throw no `TRPCError`, so they are invisible to the re-derivation recipe
@@ -327,9 +322,8 @@ export const APP_STORAGE_HOST_ERROR_MESSAGES = [
327
322
  * failure.** The bridge's catch arms are blanket, so every other rejection
328
323
  * the host raises arrives on the same field and classifies `null` — for
329
324
  * example `invalid block token` (an expired token mid-session), `block
330
- * instance revoked`, `storage set requires the apps:storage:write scope`,
331
- * or `Apps are not enabled` (the feature flag, which fires before anything
332
- * else on every storage call). 🔴 **Those are ILLUSTRATIONS, not the set**:
325
+ * instance revoked`, or `storage set requires the apps:storage:write
326
+ * scope`. 🔴 **Those are ILLUSTRATIONS, not the set**:
333
327
  * see this module's header for why no list of them lives here.
334
328
  * - 🔴 **and a zod INPUT-VALIDATION refusal, which never reaches a handler at
335
329
  * all.** tRPC parses `.input()` before the procedure body, so a bound
@@ -29,6 +29,37 @@ export { BrowsingLevel, SFW_LEVELS, NSFW_LEVELS, isSfwCeiling, isLevelAllowed, e
29
29
  export type { BrowsingLevelKey, BrowsingLevelBit, ColorDomain } from './browsingLevel.js';
30
30
  export { APP_STORAGE_MAX_VALUE_BYTES, APP_STORAGE_MAX_BYTES, APP_STORAGE_MAX_ROWS, } from './appStorageLimits.js';
31
31
  export { BLOCK_IDEMPOTENCY_KEY_REGEX, BLOCK_IDEMPOTENCY_KEY_MAX_LENGTH, isValidBlockIdempotencyKey, blockIdempotencyKeyRejection, } from './idempotency.js';
32
+ /**
33
+ * The `srcdoc` escape hatch for embedding one of your own bundled documents
34
+ * inside a block, because a plain `<iframe src>` of your own subdomain cannot
35
+ * load. Prefer a SINGLE-DOCUMENT design. The measured reason, the matrix and
36
+ * the limits live in ONE place: the header of `nestedDocument.ts`.
37
+ *
38
+ * 🔴 `injectBaseHref` and `InjectBaseHrefResult` ARE DELIBERATELY NOT HERE, and
39
+ * the omission is the same decision as the `appStorageErrors.ts` block below:
40
+ * publish the branching surface, not every internal the module happens to
41
+ * export. `fetchNestedDocument` covers every runnable example in this repo's
42
+ * four prose surfaces (this package's README, `@civitai/blocks-react`'s README,
43
+ * `docs/build-your-first-app-block.md` and the changeset); the only in-tree
44
+ * importers of the rewrite are this module's own unit tests, and
45
+ * `@civitai/blocks-react` does not value-import it. There can be no EXTERNAL
46
+ * consumer either. The DEFINING evidence is the git history, not a sample of
47
+ * tarballs: `nestedDocument.ts` is ADDED by the branch that introduced this
48
+ * helper — `git log --diff-filter=A` over it returns exactly one commit — so no
49
+ * version published before that commit can contain the symbol, whatever any
50
+ * individual tarball says. ⚠ An earlier revision of this comment derived that
51
+ * conclusion from a handful of tarball probes instead — a sample generalised
52
+ * into a claim about every published version. The conclusion was right; the
53
+ * grounds it stated were not, which is the part worth not repeating. The probes
54
+ * themselves, with their read dates and controls, are recorded in
55
+ * `packages/civitai-blocks-react/PEER_FLOOR.md`.
56
+ *
57
+ * Both stay exported from `nestedDocument.ts`, so the unit suite reaches them by
58
+ * file path — and adding one here later is a `minor`, while removing one once
59
+ * published is not.
60
+ */
61
+ export { fetchNestedDocument, NestedDocumentError } from './nestedDocument.js';
62
+ export type { FetchNestedDocumentOptions, NestedDocument, NestedDocumentErrorCode, } from './nestedDocument.js';
32
63
  /**
33
64
  * {@link classifyAppStorageError} — the matcher a block branches on — plus the
34
65
  * four rejection messages a MOCK HOST has to emit. The wire carries a
@@ -78,5 +109,10 @@ export { isModelSlotContext, isPageSlotContext } from './types.js';
78
109
  * in `types.ts` for which of the two it uses and why.
79
110
  */
80
111
  export { isSignedIn } from './types.js';
81
- export type { BlockContext, KnownSlotId, ModelSlotId, PageSlotContext, PageSlotId, UnknownSlotContext, BlockManifest, BlockManifestGood, BlockManifestV1, BlockSettings, BlockToken, ContentRating, ManifestBooleanField, ManifestIframe, ManifestNumberField, ManifestPage, ManifestPreview, ManifestSettingField, ManifestSettings, ManifestStringField, ManifestTarget, ModelSlotContext, SettingScope, SettingWidget, Theme, ViewerInfo, BlockCheckpointInfo, BlockResourceInfo, BlockResourcePickerType, BlockSourceImage, BlockUploadedImageInfo, BlockGenerationSourceImageInfo, BlockPendingImageInfo, BlockImageScanResult, BlockUploadPurpose, BlockNavigateScope, BlockTextToImageParams, BlockWorkflowSnapshot, BuzzAccountType, ShowcaseImage, WorkflowBody, WorkflowBodyTextToImage, WorkflowBodyCustomComfy, WorkflowBodyCustomComfyRecipe, WorkflowBodyCustomComfyInline, InlineComfyNode, WorkflowBodyStep, WorkflowBodyPassThroughStep, WorkflowStatus, BlockBuzzTransaction, BlockBuzzAccount, BlockDailyCompensationResource, BlockViewer, BlockWildcardPack, BlockWildcardPackErrorCode, AppWorkflow, AppWorkflowImage, BlockGatedImage, BlockCollectionFollowErrorCode, BlockCollectionFollowResult, BlockPostSource, BlockCreatePostRequest, BlockCreatePostResult, BlockCreatePostHostError, } from './types.js';
112
+ export type { BlockContext, KnownSlotId, ModelSlotId, PageSlotContext, PageSlotId, UnknownSlotContext, BlockManifest, BlockManifestGood, BlockManifestV1, BlockSettings, BlockToken, ContentRating, ManifestBooleanField, ManifestIframe, ManifestNumberField, ManifestPage, ManifestPreview, ManifestSettingField, ManifestSettings, ManifestStringField, ManifestTarget, ModelSlotContext, SettingScope, SettingWidget, Theme, ViewerInfo, BlockCheckpointInfo, BlockResourceInfo, BlockResourcePickerType, BlockSourceImage, BlockUploadedImageInfo, BlockGenerationSourceImageInfo, BlockPendingImageInfo, BlockImageScanResult, BlockUploadPurpose, BlockNavigateScope, BlockTextToImageParams, BlockWorkflowSnapshot, BlockModelSubstitution, ModelSubstitutionReason, BlockStepToolCall, BlockTrainedEpoch, BlockPublishedModel, BuzzAccountType, ShowcaseImage, WorkflowBody, WorkflowBodyTextToImage, WorkflowBodyCustomComfy, WorkflowBodyCustomComfyRecipe, WorkflowBodyCustomComfyInline, InlineComfyNode, WorkflowBodyStep, WorkflowBodyPassThroughStep, WorkflowStatus, BlockBuzzTransaction, BlockBuzzAccount, BlockDailyCompensationResource, BlockViewer, BlockWildcardPack, BlockWildcardPackErrorCode, AppWorkflow, AppWorkflowImage, BlockGatedImage, BlockCollectionFollowErrorCode, BlockCollectionFollowResult, BlockPostSource, BlockCreatePostRequest, BlockCreatePostResult, BlockCreatePostHostError, WorkflowBodyTraining, AiToolkitTrainingParams, AiToolkitTrainingParamsBase, AiToolkitPlainEcosystem, AiToolkitLrScheduler, AiToolkitOptimizerType, BlockTrainingQuote, BlockTrainingDatasetItem, BlockTrainingDatasetResult, BlockTrainingRejectionReason, BlockPrepareTrainingDatasetHostError, BlockRunTrainingHostError, } from './types.js';
113
+ /**
114
+ * Host bounds for the App Blocks `kind: 'training'` flow, mirrored from
115
+ * civitai/civitai's zod — see `WorkflowBodyTraining`.
116
+ */
117
+ export { BLOCK_TRAINING_MAX_BUZZ_PER_RUN, BLOCK_TRAINING_DATASET_MAX_ITEMS, BLOCK_TRAINING_CAPTION_MAX_CHARS, BLOCK_TRAINING_SAMPLE_PROMPTS_MAX, BLOCK_TRAINING_SAMPLE_PROMPT_MAX_CHARS, BLOCK_TRAINING_TRIGGER_WORD_MAX_CHARS, BLOCK_TRAINING_MODEL_KEY_MAX_CHARS, } from './types.js';
82
118
  //# sourceMappingURL=index.d.ts.map
@@ -32,6 +32,36 @@ export { BLOCK_SCOPES, BLOCK_SCOPE_PATTERN, BLOCK_CATEGORIES, BLOCK_TAGLINE_MAX_
32
32
  export { BrowsingLevel, SFW_LEVELS, NSFW_LEVELS, isSfwCeiling, isLevelAllowed, effectiveBrowsingCeiling, } from './browsingLevel.js';
33
33
  export { APP_STORAGE_MAX_VALUE_BYTES, APP_STORAGE_MAX_BYTES, APP_STORAGE_MAX_ROWS, } from './appStorageLimits.js';
34
34
  export { BLOCK_IDEMPOTENCY_KEY_REGEX, BLOCK_IDEMPOTENCY_KEY_MAX_LENGTH, isValidBlockIdempotencyKey, blockIdempotencyKeyRejection, } from './idempotency.js';
35
+ /**
36
+ * The `srcdoc` escape hatch for embedding one of your own bundled documents
37
+ * inside a block, because a plain `<iframe src>` of your own subdomain cannot
38
+ * load. Prefer a SINGLE-DOCUMENT design. The measured reason, the matrix and
39
+ * the limits live in ONE place: the header of `nestedDocument.ts`.
40
+ *
41
+ * 🔴 `injectBaseHref` and `InjectBaseHrefResult` ARE DELIBERATELY NOT HERE, and
42
+ * the omission is the same decision as the `appStorageErrors.ts` block below:
43
+ * publish the branching surface, not every internal the module happens to
44
+ * export. `fetchNestedDocument` covers every runnable example in this repo's
45
+ * four prose surfaces (this package's README, `@civitai/blocks-react`'s README,
46
+ * `docs/build-your-first-app-block.md` and the changeset); the only in-tree
47
+ * importers of the rewrite are this module's own unit tests, and
48
+ * `@civitai/blocks-react` does not value-import it. There can be no EXTERNAL
49
+ * consumer either. The DEFINING evidence is the git history, not a sample of
50
+ * tarballs: `nestedDocument.ts` is ADDED by the branch that introduced this
51
+ * helper — `git log --diff-filter=A` over it returns exactly one commit — so no
52
+ * version published before that commit can contain the symbol, whatever any
53
+ * individual tarball says. ⚠ An earlier revision of this comment derived that
54
+ * conclusion from a handful of tarball probes instead — a sample generalised
55
+ * into a claim about every published version. The conclusion was right; the
56
+ * grounds it stated were not, which is the part worth not repeating. The probes
57
+ * themselves, with their read dates and controls, are recorded in
58
+ * `packages/civitai-blocks-react/PEER_FLOOR.md`.
59
+ *
60
+ * Both stay exported from `nestedDocument.ts`, so the unit suite reaches them by
61
+ * file path — and adding one here later is a `minor`, while removing one once
62
+ * published is not.
63
+ */
64
+ export { fetchNestedDocument, NestedDocumentError } from './nestedDocument.js';
35
65
  /**
36
66
  * {@link classifyAppStorageError} — the matcher a block branches on — plus the
37
67
  * four rejection messages a MOCK HOST has to emit. The wire carries a
@@ -78,4 +108,9 @@ export { isModelSlotContext, isPageSlotContext } from './types.js';
78
108
  * in `types.ts` for which of the two it uses and why.
79
109
  */
80
110
  export { isSignedIn } from './types.js';
111
+ /**
112
+ * Host bounds for the App Blocks `kind: 'training'` flow, mirrored from
113
+ * civitai/civitai's zod — see `WorkflowBodyTraining`.
114
+ */
115
+ export { BLOCK_TRAINING_MAX_BUZZ_PER_RUN, BLOCK_TRAINING_DATASET_MAX_ITEMS, BLOCK_TRAINING_CAPTION_MAX_CHARS, BLOCK_TRAINING_SAMPLE_PROMPTS_MAX, BLOCK_TRAINING_SAMPLE_PROMPT_MAX_CHARS, BLOCK_TRAINING_TRIGGER_WORD_MAX_CHARS, BLOCK_TRAINING_MODEL_KEY_MAX_CHARS, } from './types.js';
81
116
  //# sourceMappingURL=index.js.map
@@ -8,7 +8,7 @@
8
8
  * Wire format: `window.postMessage({ type, payload }, targetOrigin)`.
9
9
  */
10
10
  import type { ColorDomain } from './browsingLevel.js';
11
- import type { BlockCheckpointInfo, BlockResourceInfo, BlockResourcePickerType, BlockUploadedImageInfo, BlockGenerationSourceImageInfo, BlockPendingImageInfo, BlockImageScanResult, BlockUploadPurpose, BlockNavigateScope, BlockContext, BlockSettings, Theme, ViewerInfo, WorkflowBody, BlockWorkflowSnapshot, BlockBuzzTransaction, BlockBuzzAccount, BlockDailyCompensationResource, BlockViewer, BlockWildcardPack, BlockWildcardPackErrorCode, AppWorkflow, BlockGatedImage, BlockCollectionFollowErrorCode, BlockCollectionFollowResult, BlockPostSource, BlockCreatePostResult } from './types.js';
11
+ import type { BlockCheckpointInfo, BlockResourceInfo, BlockResourcePickerType, BlockUploadedImageInfo, BlockGenerationSourceImageInfo, BlockPendingImageInfo, BlockImageScanResult, BlockUploadPurpose, BlockNavigateScope, BlockContext, BlockSettings, Theme, ViewerInfo, WorkflowBody, BlockWorkflowSnapshot, BlockBuzzTransaction, BlockBuzzAccount, BlockDailyCompensationResource, BlockViewer, BlockWildcardPack, BlockWildcardPackErrorCode, AppWorkflow, BlockGatedImage, BlockCollectionFollowErrorCode, BlockCollectionFollowResult, BlockPostSource, BlockCreatePostResult, BlockTrainingDatasetItem, BlockTrainingDatasetResult, WorkflowBodyTraining } from './types.js';
12
12
  /**
13
13
  * Filter params for `GET_BUZZ_TRANSACTIONS`. All optional; the host validates
14
14
  * them server-side (they are NEVER trusted for auth — the account is self-bound
@@ -464,6 +464,20 @@ export type ParentToBlockMessage = {
464
464
  result?: BlockCreatePostResult;
465
465
  error?: string;
466
466
  };
467
+ } | {
468
+ type: 'TRAINING_DATASET_RESULT';
469
+ payload: {
470
+ requestId: string;
471
+ result?: BlockTrainingDatasetResult;
472
+ error?: string;
473
+ };
474
+ } | {
475
+ type: 'TRAINING_RESULT';
476
+ payload: {
477
+ requestId: string;
478
+ snapshot?: BlockWorkflowSnapshot;
479
+ error?: string;
480
+ };
467
481
  } | {
468
482
  type: 'IMAGES_RESULT';
469
483
  payload: {
@@ -774,6 +788,18 @@ export type BlockToParentMessage = {
774
788
  /** Optional model-version gallery attach. Gated hard server-side. */
775
789
  modelVersionId?: number;
776
790
  };
791
+ } | {
792
+ type: 'PREPARE_TRAINING_DATASET';
793
+ payload: {
794
+ requestId: string;
795
+ items: BlockTrainingDatasetItem[];
796
+ };
797
+ } | {
798
+ type: 'RUN_TRAINING';
799
+ payload: {
800
+ requestId: string;
801
+ body: WorkflowBodyTraining;
802
+ };
777
803
  } | {
778
804
  type: 'GET_IMAGES_BY_IDS';
779
805
  payload: {
@@ -998,7 +1024,7 @@ export type BlockToParentMessageType = BlockToParentMessage['type'];
998
1024
  * it is a measurement, not an invariant, and civitai's own compile-time gate
999
1025
  * (published SDK union ⊆ `keyof INVENTORY`) is what holds one direction of it.
1000
1026
  */
1001
- export declare const BLOCK_TO_PARENT_MESSAGE_TYPES: readonly ["BLOCK_HELLO", "BLOCK_READY", "BLOCK_ERROR", "BLOCK_MESSAGE_REJECTED", "REQUEST_TOKEN", "RESIZE_IFRAME", "SUBMIT_WORKFLOW", "ESTIMATE_WORKFLOW", "POLL_WORKFLOW", "CANCEL_WORKFLOW", "OPEN_BUZZ_PURCHASE", "GET_BUZZ_BALANCE", "GET_VIEWER", "GET_BUZZ_TRANSACTIONS", "GET_BUZZ_ACCOUNTS", "GET_DAILY_COMPENSATION", "GET_WILDCARD_PACK", "QUERY_APP_WORKFLOWS", "PUBLISH_GENERATION_OUTPUTS", "CREATE_POST_FROM_APP", "GET_IMAGES_BY_IDS", "CANCEL_APP_WORKFLOW", "OPEN_CHECKPOINT_PICKER", "OPEN_RESOURCE_PICKER", "OPEN_IMAGE_UPLOAD", "SET_USER_CHECKPOINT", "NAVIGATE", "REQUEST_SIGN_IN", "REQUEST_CONSENT", "TRACK_EVENT", "APP_STORAGE_GET", "APP_STORAGE_SET", "APP_STORAGE_DELETE", "APP_STORAGE_LIST", "APP_STORAGE_QUOTA", "SHARED_LIST", "SHARED_GET_COUNT", "SHARED_GET_COUNTS", "SHARED_APPEND", "SHARED_VOTE", "SHARED_UNVOTE", "SHARED_WITHDRAW", "SHARED_UPDATE", "SHARED_GET", "SHARED_REPORT", "SAVE_IMAGE", "SET_COLLECTION_FOLLOW"];
1027
+ export declare const BLOCK_TO_PARENT_MESSAGE_TYPES: readonly ["BLOCK_HELLO", "BLOCK_READY", "BLOCK_ERROR", "BLOCK_MESSAGE_REJECTED", "REQUEST_TOKEN", "RESIZE_IFRAME", "SUBMIT_WORKFLOW", "ESTIMATE_WORKFLOW", "POLL_WORKFLOW", "CANCEL_WORKFLOW", "OPEN_BUZZ_PURCHASE", "GET_BUZZ_BALANCE", "GET_VIEWER", "GET_BUZZ_TRANSACTIONS", "GET_BUZZ_ACCOUNTS", "GET_DAILY_COMPENSATION", "GET_WILDCARD_PACK", "QUERY_APP_WORKFLOWS", "PUBLISH_GENERATION_OUTPUTS", "CREATE_POST_FROM_APP", "PREPARE_TRAINING_DATASET", "RUN_TRAINING", "GET_IMAGES_BY_IDS", "CANCEL_APP_WORKFLOW", "OPEN_CHECKPOINT_PICKER", "OPEN_RESOURCE_PICKER", "OPEN_IMAGE_UPLOAD", "SET_USER_CHECKPOINT", "NAVIGATE", "REQUEST_SIGN_IN", "REQUEST_CONSENT", "TRACK_EVENT", "APP_STORAGE_GET", "APP_STORAGE_SET", "APP_STORAGE_DELETE", "APP_STORAGE_LIST", "APP_STORAGE_QUOTA", "SHARED_LIST", "SHARED_GET_COUNT", "SHARED_GET_COUNTS", "SHARED_APPEND", "SHARED_VOTE", "SHARED_UNVOTE", "SHARED_WITHDRAW", "SHARED_UPDATE", "SHARED_GET", "SHARED_REPORT", "SAVE_IMAGE", "SET_COLLECTION_FOLLOW"];
1002
1028
  /**
1003
1029
  * The bucket a message type falls into when the protocol does not declare it.
1004
1030
  *
@@ -69,6 +69,8 @@ export const BLOCK_TO_PARENT_MESSAGE_TYPES = [
69
69
  'QUERY_APP_WORKFLOWS',
70
70
  'PUBLISH_GENERATION_OUTPUTS',
71
71
  'CREATE_POST_FROM_APP',
72
+ 'PREPARE_TRAINING_DATASET',
73
+ 'RUN_TRAINING',
72
74
  'GET_IMAGES_BY_IDS',
73
75
  'CANCEL_APP_WORKFLOW',
74
76
  'OPEN_CHECKPOINT_PICKER',