diff --git a/.changeset/build-pdf-browser.md b/.changeset/build-pdf-browser.md new file mode 100644 index 00000000..1e10faaf --- /dev/null +++ b/.changeset/build-pdf-browser.md @@ -0,0 +1,8 @@ +--- +'@simplepdf/embed': minor +'@simplepdf/react-embed-pdf': minor +--- + +**Build and revise PDFs directly in the browser editor.** +- Use typed JavaScript and React methods for PDF building and task documentation. +- View the first-page preview with the build result and inspect other open-document pages by page number. WebMCP returns each preview as a native image. diff --git a/embed/README.md b/embed/README.md index 6e992a79..5eb9a5f7 100644 --- a/embed/README.md +++ b/embed/README.md @@ -92,10 +92,10 @@ createEmbed({ target: '#editor', companyIdentifier: 'acme', document: { url: 'ht ``` - **Off by default.** `{ enabled: false }` and omitting the option are the same state. -- **The tools are the editor's own.** Each one is the record the editor publishes in its manifest (`https://simplepdf.com/embed/json`, `operations[].tool`) and registers on its own page: the `simplepdf_embed_*` name, description, snake_case input schema and behavior hints (the readers carry the specification's `readOnlyHint` and `untrustedContentHint`; every other tool MCP's `destructiveHint`; the three that fetch an agent-supplied URL `openWorldHint`). A page gets the same tools whether the editor is embedded or opened directly. `exclude` takes SDK method names. +- **The tools are the editor's own.** Each one is the record the editor publishes in its manifest (`https://simplepdf.com/embed/json`, `operations[].tool`) and registers on its own page: the published tool name, description, snake_case input schema and behavior hints (the readers carry the specification's `readOnlyHint` and `untrustedContentHint`; every other tool MCP's `destructiveHint`; those that fetch an agent-supplied URL or requested Google Fonts `openWorldHint`). `build_pdf` and `get_documentation` use those names; existing tools retain the `simplepdf_embed_` prefix. A page gets the same tools whether the editor is embedded or opened directly. `exclude` takes SDK method names. - **Data path.** Every operation an agent can call runs in the browser, and nothing the agent reads (field values, extracted text, a page render) is computed server-side; it goes to the agent runtime the person attached, so treat that runtime as you would any other party that sees the filled document. Document storage is unchanged by this option: it follows your account's configuration exactly as it does without WebMCP (SimplePDF-managed storage, or your own S3, Azure Blob Storage or SharePoint), and `submit` sends the document through the same submission flow as a click on Submit. - **Timing.** Tools register once the editor is ready. While no usable model context has been found, the page is probed again on each later lifecycle transition, so a context installed after `EDITOR_READY` is still picked up, and until one appears nothing is loaded (`webmcp.unavailable` is logged, with the reason). -- **Results.** The editor validates each call like any other request (its permission model applies at call time: editing, allowlisted origin, plan, so a tool your configuration refuses resolves with the matching error code). A call resolves with an MCP tool result whose text is the editor's wire-shaped `{ success, data | error }` Result (`isError` on failure); `simplepdf_embed_get_annotated_page` carries its PNG as an `image` content block, with the badges map in the text block. A call the runtime aborted before it ran rejects and never reaches the editor. +- **Results.** The editor validates each call like any other request (its permission model applies at call time: editing, allowlisted origin, plan, so a tool your configuration refuses resolves with the matching error code). A call resolves with an MCP tool result whose text is the editor's wire-shaped `{ success, data | error }` Result (`isError` on failure). A successful page render from `build_pdf` or `simplepdf_embed_get_annotated_page` carries its PNG as an `image` content block and its field badges in the text block. A call the runtime aborted before it ran rejects and never reaches the editor. - **One embed per page.** A model context is one per page and keyed by tool name: a second WebMCP-enabled embed registers only the names the first did not take, and is reported for the rest (`webmcp.tool_already_registered`). `dispose()` unregisters everything. ## Subpaths @@ -170,6 +170,8 @@ else r.error.code // a closed BridgeErrorCode `embed.actions.*`: method names + arguments are camelCase (the snake_case wire is generated + transformed for you; [`/embed/json`](https://simplepdf.com/embed/json) or `@simplepdf/embed/schemas` carry every field): ```ts +await embed.actions.getDocumentation({ topic: 'build_pdf' }) +await embed.actions.buildPdf({ action: 'build', code: '= Hello' }) await embed.actions.loadDocument({ dataUrl, name, page }) await embed.actions.goTo({ page: 3 }) await embed.actions.selectTool({ tool: 'TEXT' }) // 'CHECKBOX' | 'SIGNATURE' | 'PICTURE' | 'COMB_TEXT' | null @@ -184,7 +186,11 @@ await embed.actions.rotatePage({ page: 1 }) await embed.actions.download() ``` -Full set: `batchSetFieldValues`, `createField`, `deleteFields`, `deletePages`, `detectFields`, `download`, `focusField`, `getAnnotatedPage`, `getDocumentContent`, `getFields`, `goTo`, `loadDocument`, `movePage`, `rotatePage`, `selectTool`, `setFieldValue`, `submit`. +Full set: `buildPdf`, `getDocumentation`, `batchSetFieldValues`, `createField`, `deleteFields`, `deletePages`, `detectFields`, `download`, `focusField`, `getAnnotatedPage`, `getDocumentContent`, `getFields`, `goTo`, `loadDocument`, `movePage`, `rotatePage`, `selectTool`, `setFieldValue`, `submit`. + +Start a build in an empty editor. If the job is still `running` after five seconds, call `buildPdf({ action: 'status', jobId })` until it finishes. A failed build reports diagnostics in `error`. A successful build opens the PDF and returns its page count, warnings and a first-page `preview`. Check `preview.success` before reading `preview.data.imageDataUrl`. To inspect another page of the currently open document, call `getAnnotatedPage({ page: 2 })`. Build preview identity is checked internally; page inspection has no build-specific parameters. Manual edits protect the document from replacement by a subsequent build. + +Call `getDocumentation()` for the topic index, then `getDocumentation({ topic })` to read a topic. **"Fill and read this document for me"** is just these operations in sequence, exactly what the agentic tools expose to a model: diff --git a/embed/embed-api.json b/embed/embed-api.json index 65df2c4f..9f5e56b3 100644 --- a/embed/embed-api.json +++ b/embed/embed-api.json @@ -1,5 +1,5 @@ { - "editor_version": "6f020890-20261114T210959Z", + "editor_version": null, "description": "This is the SimplePDF editor interface contract. Drive the editor programmatically over window.postMessage with the editor iframe: post a JSON string { \"type\": {{operation request_type}}, \"request_id\": {{a request correlation id you generate}}, \"data\": {{input matching input_schema}} } to the iframe; the editor replies with { \"type\": \"REQUEST_RESULT\", \"data\": { \"request_id\": {{the same correlation id}}, \"result\": {{result}} } } (match each reply to its request by this id), where result is { \"success\": true, \"data\": {{a value matching the operation's output_schema; null for ops that return nothing}} } or { \"success\": false, \"error\": { code, message } }. Each operation lists the op-specific `error_codes` it can return; on top of those, any op may also fail with a gateway/permission code (origin/plan/signup gating, editor-not-ready, or an internal error). Every code is within `editor_error_schema` (the complete closed union to narrow against), where each code const carries a `description` of its meaning. Outbound events (see `events`) are pushed the same way. `operations` lists every operation the editor supports. Most require the embedding origin to be allowlisted (\"whitelisted\") for the tenant in the SimplePDF admin dashboard, and the tenant plan to permit them (LOAD_DOCUMENT is always available). A call the current setup does not permit returns the matching gateway code: forbidden:origin_not_whitelisted when the origin is not allowlisted, or bad_request:plan_upgrade_required when the plan excludes it. All JSON schemas use the json_schema_dialect declared at the root. We recommend the @simplepdf/embed package for a typed, ergonomic wrapper over this contract (https://github.com/SimplePDF/simplepdf-embed).", "json_schema_dialect": "https://json-schema.org/draft/2020-12/schema", "protocol": { @@ -76,6 +76,725 @@ } }, "operations": [ + { + "request_type": "BUILD_PDF", + "description": "Build and display Typst PDFs. See documentation. Each build starts a new attempt; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.", + "input_schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "action": { + "type": "string", + "const": "build" + }, + "code": { + "type": "string" + }, + "fonts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "family": { + "type": "string" + }, + "weight": { + "type": "integer" + }, + "style": { + "type": "string", + "enum": ["normal", "italic"] + } + }, + "required": ["family"], + "additionalProperties": false + } + }, + "name": { + "type": "string" + }, + "assets": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "data_url": { + "type": "string" + } + }, + "required": ["path", "data_url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "shader": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "width": { + "type": "integer" + }, + "height": { + "type": "integer" + }, + "textures": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": ["code", "width", "height"], + "additionalProperties": false + } + }, + "required": ["path", "shader"], + "additionalProperties": false + } + ] + } + } + }, + "required": ["action", "code"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "action": { + "type": "string", + "const": "status" + }, + "job_id": { + "type": "string" + } + }, + "required": ["action", "job_id"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "action": { + "type": "string", + "const": "cancel" + }, + "job_id": { + "type": "string" + } + }, + "required": ["action", "job_id"], + "additionalProperties": false + } + ], + "description": "Build and display Typst PDFs. See documentation. Each build starts a new attempt; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing." + }, + "output_schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "job_id": { + "type": "string" + }, + "status": { + "type": "string", + "const": "running" + } + }, + "required": ["job_id", "status"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "job_id": { + "type": "string" + }, + "status": { + "type": "string", + "const": "succeeded" + }, + "page_count": { + "type": "integer" + }, + "warnings": { + "type": "array", + "items": { + "type": "object", + "properties": { + "severity": { + "type": "string", + "const": "warning" + }, + "code": { + "type": "string", + "enum": ["typst", "shader", "unsupported_dependency"] + }, + "message": { + "type": "string" + }, + "file": { + "type": "string" + }, + "line": { + "type": "integer" + }, + "column": { + "type": "integer" + } + }, + "required": ["severity", "code", "message"], + "additionalProperties": false + } + }, + "preview": { + "anyOf": [ + { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "const": true + }, + "data": { + "type": "object", + "properties": { + "page": { + "type": "integer", + "description": "1-based page position this render shows." + }, + "image_data_url": { + "type": "string", + "description": "PNG render of the page as a data URL, with every field outlined and a numbered badge drawn inside it on the right, or just to its left when the field is too small to hold it." + }, + "image_width": { + "type": "integer", + "description": "Render width in pixels." + }, + "image_height": { + "type": "integer", + "description": "Render height in pixels." + }, + "badges": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Badge number (as drawn on the render) to field_id, for every field on the page." + } + }, + "required": [ + "page", + "image_data_url", + "image_width", + "image_height", + "badges" + ] + } + }, + "required": ["success", "data"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "success": { + "type": "boolean", + "const": false + }, + "error": { + "type": "object", + "properties": { + "code": { + "anyOf": [ + { + "type": "string", + "const": "bad_request:no_document_loaded", + "description": "No document is loaded. Load a document before calling this operation." + }, + { + "type": "string", + "const": "bad_request:invalid_page", + "description": "page is missing or is not a positive integer." + }, + { + "type": "string", + "const": "bad_request:page_out_of_range", + "description": "page is outside the document range (1 to the document page_count)." + }, + { + "type": "string", + "const": "bad_request:editor_not_ready", + "description": "The editor is still initializing and cannot accept this operation yet. Retry the operation shortly." + }, + { + "type": "string", + "const": "bad_request:event_not_allowed", + "description": "This operation is not available in this context (the portal configuration or this page does not offer it); the message says why." + }, + { + "type": "string", + "const": "bad_request:plan_upgrade_required", + "description": "The tenant's plan does not include this operation. Upgrade the plan in the SimplePDF admin dashboard." + }, + { + "type": "string", + "const": "bad_request:signup_required", + "description": "This operation requires the end user to sign up or authenticate first at https://simplepdf.com/auth/signup." + }, + { + "type": "string", + "const": "forbidden:origin_not_whitelisted", + "description": "The embedding origin is not allowlisted for this tenant, or is not the allowlisted origin the editor was loaded from. Allowlist it in the SimplePDF admin dashboard and let the embedding page's Referer reach the editor." + }, + { + "type": "string", + "const": "forbidden:whitelist_required", + "description": "This tenant requires the embedding origin to be allowlisted before any operation is accepted. Configure it in the admin dashboard." + }, + { + "type": "string", + "const": "conflict:inspection_state_changed", + "description": "The build is no longer displayed or the editor changed during its automatic preview." + }, + { + "type": "string", + "const": "unexpected:internal_error", + "description": "An unexpected internal error occurred. Try again, and if the issue persists, reach out to support@simplepdf.com." + } + ] + }, + "message": { + "type": "string" + } + }, + "required": ["code", "message"], + "additionalProperties": false + } + }, + "required": ["success", "error"], + "additionalProperties": false + } + ] + } + }, + "required": [ + "job_id", + "status", + "page_count", + "warnings", + "preview" + ], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "job_id": { + "type": "string" + }, + "status": { + "type": "string", + "const": "failed" + }, + "error": { + "type": "object", + "properties": { + "code": { + "type": "string", + "enum": [ + "unsupported_dependency", + "font_unavailable", + "engine_initialization_failed", + "compile_error", + "compile_timeout", + "job_timeout", + "resource_limit", + "invalid_pdf", + "editor_load_failed", + "editor_conflict", + "worker_crashed", + "internal_error" + ] + }, + "message": { + "type": "string" + }, + "retryable": { + "type": "boolean" + }, + "diagnostics": { + "type": "array", + "items": { + "type": "object", + "properties": { + "severity": { + "type": "string", + "enum": ["error", "warning"] + }, + "code": { + "type": "string", + "enum": ["typst", "shader", "unsupported_dependency"] + }, + "message": { + "type": "string" + }, + "file": { + "type": "string" + }, + "line": { + "type": "integer" + }, + "column": { + "type": "integer" + } + }, + "required": ["severity", "code", "message"], + "additionalProperties": false + } + } + }, + "required": ["code", "message", "retryable", "diagnostics"], + "additionalProperties": false + } + }, + "required": ["job_id", "status", "error"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "job_id": { + "type": "string" + }, + "status": { + "type": "string", + "const": "cancelled" + } + }, + "required": ["job_id", "status"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "job_id": { + "type": "string" + }, + "status": { + "type": "string", + "const": "superseded" + } + }, + "required": ["job_id", "status"], + "additionalProperties": false + } + ] + }, + "error_codes": [ + "conflict:editor_modified", + "conflict:unmanaged_document", + "not_found:job", + "not_found:job_expired", + "resource:session_limit", + "bad_request:invalid_value", + "forbidden:editing_not_allowed" + ], + "tool": { + "name": "build_pdf", + "description": "Build and display Typst PDFs. See documentation. Each build starts a new attempt; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.", + "input_schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "action": { + "type": "string", + "const": "build" + }, + "code": { + "type": "string" + }, + "fonts": { + "type": "array", + "items": { + "type": "object", + "properties": { + "family": { + "type": "string" + }, + "weight": { + "type": "integer" + }, + "style": { + "type": "string", + "enum": ["normal", "italic"] + } + }, + "required": ["family"], + "additionalProperties": false + } + }, + "name": { + "type": "string" + }, + "assets": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "data_url": { + "type": "string" + } + }, + "required": ["path", "data_url"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "path": { + "type": "string" + }, + "shader": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "width": { + "type": "integer" + }, + "height": { + "type": "integer" + }, + "textures": { + "type": "array", + "items": { + "type": "string" + } + } + }, + "required": ["code", "width", "height"], + "additionalProperties": false + } + }, + "required": ["path", "shader"], + "additionalProperties": false + } + ] + } + } + }, + "required": ["action", "code"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "action": { + "type": "string", + "const": "status" + }, + "job_id": { + "type": "string" + } + }, + "required": ["action", "job_id"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "action": { + "type": "string", + "const": "cancel" + }, + "job_id": { + "type": "string" + } + }, + "required": ["action", "job_id"], + "additionalProperties": false + } + ], + "type": "object", + "properties": {} + }, + "annotations": { + "destructiveHint": true, + "untrustedContentHint": true, + "openWorldHint": true + } + } + }, + { + "request_type": "GET_DOCUMENTATION", + "description": "Read task guidance and tested PDF recipes. Omit topic for the index.", + "input_schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "topic": { + "type": "string", + "enum": [ + "build_pdf", + "build_pdf.templates", + "build_pdf.forms", + "build_pdf.assets", + "build_pdf.graphics", + "build_pdf.shaders", + "build_pdf.troubleshooting", + "fields", + "inspection" + ] + } + }, + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "topic": { + "type": "string", + "enum": ["build_pdf.fonts"] + }, + "query": { + "type": "string" + } + }, + "required": ["topic"], + "additionalProperties": false + } + ], + "description": "Read task guidance and tested PDF recipes. Omit topic for the index." + }, + "output_schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "index" + }, + "topics": { + "type": "array", + "items": { + "type": "object", + "properties": { + "topic": { + "type": "string", + "enum": [ + "build_pdf", + "build_pdf.templates", + "build_pdf.forms", + "build_pdf.assets", + "build_pdf.fonts", + "build_pdf.graphics", + "build_pdf.shaders", + "build_pdf.troubleshooting", + "fields", + "inspection" + ] + }, + "description": { + "type": "string" + } + }, + "required": ["topic", "description"], + "additionalProperties": false + } + } + }, + "required": ["kind", "topics"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "kind": { + "type": "string", + "const": "topic" + }, + "markdown": { + "type": "string" + } + }, + "required": ["kind", "markdown"], + "additionalProperties": false + } + ] + }, + "error_codes": ["bad_request:invalid_value"], + "tool": { + "name": "get_documentation", + "description": "Read task guidance and tested PDF recipes. Omit topic for the index.", + "input_schema": { + "anyOf": [ + { + "type": "object", + "properties": { + "topic": { + "type": "string", + "enum": [ + "build_pdf", + "build_pdf.templates", + "build_pdf.forms", + "build_pdf.assets", + "build_pdf.graphics", + "build_pdf.shaders", + "build_pdf.troubleshooting", + "fields", + "inspection" + ] + } + }, + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "topic": { + "type": "string", + "enum": ["build_pdf.fonts"] + }, + "query": { + "type": "string" + } + }, + "required": ["topic"], + "additionalProperties": false + } + ], + "type": "object", + "properties": {} + }, + "annotations": { + "readOnlyHint": true, + "untrustedContentHint": true + } + } + }, { "request_type": "BATCH_SET_FIELD_VALUES", "description": "Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data.", @@ -123,6 +842,7 @@ "name": "simplepdf_embed_batch_set_field_values", "description": "Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data.", "input_schema": { + "required": ["updates"], "type": "object", "properties": { "updates": { @@ -150,8 +870,7 @@ "description": "The fields to set, at least one, each field at most once. Fields not listed keep their value.", "type": "array" } - }, - "required": ["updates"] + } }, "annotations": { "destructiveHint": false, @@ -222,6 +941,7 @@ "name": "simplepdf_embed_create_field", "description": "Create a new overlay field on a page. Returns the id of the created field.", "input_schema": { + "required": ["type", "x", "y", "width", "height", "page"], "type": "object", "properties": { "type": { @@ -253,8 +973,7 @@ "description": "Optional initial value. A string for text/checkbox fields; a data URL or http(s) URL (fetched by the editor) for signature/picture fields, or plain text for a signature, drawn as a typed signature.", "type": "string" } - }, - "required": ["type", "x", "y", "width", "height", "page"] + } }, "annotations": { "destructiveHint": false, @@ -354,6 +1073,7 @@ "name": "simplepdf_embed_delete_pages", "description": "Delete pages from the document (it cannot delete every visible page). Returns no data. Destructive.", "input_schema": { + "required": ["pages"], "type": "object", "properties": { "pages": { @@ -363,8 +1083,7 @@ "description": "1-based page numbers to delete.", "type": "array" } - }, - "required": ["pages"] + } }, "annotations": { "destructiveHint": true @@ -474,14 +1193,14 @@ "name": "simplepdf_embed_focus_field", "description": "Scroll an existing field into view and focus it, addressed by its id from the field list. Returns a hint describing the user action expected next.", "input_schema": { + "required": ["field_id"], "type": "object", "properties": { "field_id": { "description": "ID of the field to focus and scroll into view.", "type": "string" } - }, - "required": ["field_id"] + } }, "annotations": { "destructiveHint": false @@ -546,14 +1265,14 @@ "name": "simplepdf_embed_get_annotated_page", "description": "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block.", "input_schema": { + "required": ["page"], "type": "object", "properties": { "page": { "description": "1-based page to render, at its current position.", "type": "integer" } - }, - "required": ["page"] + } }, "annotations": { "readOnlyHint": true, @@ -746,14 +1465,14 @@ "name": "simplepdf_embed_go_to", "description": "Scroll the editor to a page. Returns no data.", "input_schema": { + "required": ["page"], "type": "object", "properties": { "page": { "description": "1-based page to navigate to.", "type": "integer" } - }, - "required": ["page"] + } }, "annotations": { "destructiveHint": false @@ -794,6 +1513,7 @@ "name": "simplepdf_embed_load_document", "description": "Replace the document in the editor with one supplied as a base64 data URL or an http(s) URL the editor fetches. Destructive: the current document and every edit in it are discarded. Replies once the document and its fields are ready, so the next operation can act on it, and DOCUMENT_LOADED follows the reply; the URL already open is left as is and answers once it settles; a document that cannot be loaded or prepared answers bad_request:failed_to_load_document. Returns no data.", "input_schema": { + "required": ["data_url"], "type": "object", "properties": { "data_url": { @@ -808,8 +1528,7 @@ "description": "Optional 1-based page to open the document on.", "type": "integer" } - }, - "required": ["data_url"] + } }, "annotations": { "destructiveHint": true, @@ -849,6 +1568,7 @@ "name": "simplepdf_embed_move_page", "description": "Move a page to another position, reordering the document. Returns no data. Destructive.", "input_schema": { + "required": ["from_page", "to_page"], "type": "object", "properties": { "from_page": { @@ -859,8 +1579,7 @@ "description": "1-based destination position for the page.", "type": "integer" } - }, - "required": ["from_page", "to_page"] + } }, "annotations": { "destructiveHint": true @@ -895,14 +1614,14 @@ "name": "simplepdf_embed_rotate_page", "description": "Rotate a page 90 degrees clockwise. Returns no data. Destructive.", "input_schema": { + "required": ["page"], "type": "object", "properties": { "page": { "description": "1-based page to rotate.", "type": "integer" } - }, - "required": ["page"] + } }, "annotations": { "destructiveHint": true @@ -948,6 +1667,7 @@ "name": "simplepdf_embed_select_tool", "description": "Activate a field-placement tool in the editor toolbar so the user can draw that field type, or pass null to clear the active tool. Returns no data.", "input_schema": { + "required": ["tool"], "type": "object", "properties": { "tool": { @@ -968,8 +1688,7 @@ ], "description": "Tool to activate, or null to deselect." } - }, - "required": ["tool"] + } }, "annotations": { "destructiveHint": false @@ -1019,6 +1738,7 @@ "name": "simplepdf_embed_set_field_value", "description": "Set or clear (null) one existing field, addressed by its id from the field list. Text is typed out unless animate is false. Returns no data.", "input_schema": { + "required": ["field_id", "value"], "type": "object", "properties": { "animate": { @@ -1040,8 +1760,7 @@ ], "description": "New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature." } - }, - "required": ["field_id", "value"] + } }, "annotations": { "destructiveHint": false, @@ -1069,20 +1788,21 @@ "error_codes": [ "bad_request:no_document_loaded", "bad_request:invalid_value", - "bad_request:missing_required_fields" + "bad_request:missing_required_fields", + "forbidden:recipient_link_used" ], "tool": { "name": "simplepdf_embed_submit", "description": "Submit the completed document through the editor's finalization flow. This is irreversible. Fails with bad_request:missing_required_fields when required fields are unfilled. Returns no data.", "input_schema": { + "required": ["download_copy"], "type": "object", "properties": { "download_copy": { "description": "When true, the signer also receives a downloaded copy on submit.", "type": "boolean" } - }, - "required": ["download_copy"] + } }, "annotations": { "destructiveHint": true @@ -1093,7 +1813,7 @@ "events": [ { "event_type": "EDITOR_READY", - "description": "Pushed once when the editor iframe boots in loading-placeholder mode (the loadingPlaceholder=true iframe query flag, which @simplepdf/embed sets while it waits to post LOAD_DOCUMENT) and accepts operations; before it, LOAD_DOCUMENT fails with bad_request:editor_not_ready and every other operation with bad_request:no_document_loaded. An iframe opened with a document instead goes straight to DOCUMENT_LOADED. It is not replayed: a listener attached after boot never receives it, so treat bad_request:editor_not_ready as \"retry shortly\" rather than waiting for this event.", + "description": "Pushed once when the editor iframe boots in loading-placeholder mode (the loadingPlaceholder=true iframe query flag, which @simplepdf/embed sets while it waits to post LOAD_DOCUMENT) and accepts operations; before it, LOAD_DOCUMENT fails with bad_request:editor_not_ready and document-dependent operations with bad_request:no_document_loaded; PDF building and documentation are available in an empty editor. An iframe opened with a document instead goes straight to DOCUMENT_LOADED. It is not replayed: a listener attached after boot never receives it, so treat bad_request:editor_not_ready as \"retry shortly\" rather than waiting for this event.", "payload_schema": { "type": "object", "properties": {} @@ -1101,7 +1821,7 @@ }, { "event_type": "DOCUMENT_LOADED", - "description": "Pushed exactly once per loaded document, when the document and its fields are ready; the payload carries the document_id. It follows the LOAD_DOCUMENT reply, which is itself sent once the document is ready, so a request sent after that reply acts on the new document; before any document, operations other than LOAD_DOCUMENT fail with bad_request:no_document_loaded, and until it fires for a document the page opened itself GET_FIELDS may report an incomplete field list. On a blank editor it fires once a document is loaded, by LOAD_DOCUMENT or by the user.", + "description": "Pushed exactly once per loaded document, when the document and its fields are ready; the payload carries the document_id. It follows the LOAD_DOCUMENT reply, which is itself sent once the document is ready, so a request sent after that reply acts on the new document; before any document, document-dependent operations fail with bad_request:no_document_loaded; PDF building and documentation are available in an empty editor, and until it fires for a document the page opened itself GET_FIELDS may report an incomplete field list. On a blank editor it fires once a document is loaded, by LOAD_DOCUMENT or by the user.", "payload_schema": { "type": "object", "properties": { @@ -1245,6 +1965,31 @@ "properties": { "code": { "anyOf": [ + { + "type": "string", + "const": "conflict:editor_modified", + "description": "Edits block rebuilding. Start a new session in an empty editor." + }, + { + "type": "string", + "const": "conflict:unmanaged_document", + "description": "Open an empty editor before building." + }, + { + "type": "string", + "const": "not_found:job", + "description": "Unknown job in this editor session." + }, + { + "type": "string", + "const": "not_found:job_expired", + "description": "Job expired. Submit a new build." + }, + { + "type": "string", + "const": "resource:session_limit", + "description": "Session job limit reached. Open an empty editor." + }, { "type": "string", "const": "bad_request:download_blocked", @@ -1340,6 +2085,11 @@ "const": "bad_request:signup_required", "description": "This operation requires the end user to sign up or authenticate first at https://simplepdf.com/auth/signup." }, + { + "type": "string", + "const": "conflict:inspection_state_changed", + "description": "The build is no longer displayed or the editor changed during its automatic preview." + }, { "type": "string", "const": "forbidden:editing_not_allowed", @@ -1350,6 +2100,11 @@ "const": "forbidden:origin_not_whitelisted", "description": "The embedding origin is not allowlisted for this tenant, or is not the allowlisted origin the editor was loaded from. Allowlist it in the SimplePDF admin dashboard and let the embedding page's Referer reach the editor." }, + { + "type": "string", + "const": "forbidden:recipient_link_used", + "description": "The document was opened through a recipient link that has already been submitted (each link takes one submission), so this submit was refused and no submission was completed. The editor keeps the entered values and shows the end user a dialog saying so. Do not retry: the document owner reopens the link by deleting its submission, or shares a new one." + }, { "type": "string", "const": "forbidden:whitelist_required", diff --git a/embed/etc/ai-sdk.api.md b/embed/etc/ai-sdk.api.md index 1c565a7f..eabf065e 100644 --- a/embed/etc/ai-sdk.api.md +++ b/embed/etc/ai-sdk.api.md @@ -4,8 +4,7 @@ ```ts -import * as zod from 'zod'; -import * as zod_v4_core from 'zod/v4/core'; +import { z } from 'zod'; // Warning: (ae-forgotten-export) The symbol "BridgeResult" needs to be exported by the entry point ai-sdk.d.ts // @@ -24,7 +23,7 @@ export type SimplePDFToolName = keyof typeof TOOL_DEFINITIONS; // Warnings were encountered during analysis: // -// dist/ai-sdk.d.ts:10:5 - (ae-forgotten-export) The symbol "Embed" needs to be exported by the entry point ai-sdk.d.ts +// dist/ai-sdk.d.ts:9:5 - (ae-forgotten-export) The symbol "Embed" needs to be exported by the entry point ai-sdk.d.ts // (No @packageDocumentation comment for this package) diff --git a/embed/etc/index.api.md b/embed/etc/index.api.md index 3b7195b0..7cdf09b9 100644 --- a/embed/etc/index.api.md +++ b/embed/etc/index.api.md @@ -70,6 +70,92 @@ export class BridgeUnwrapError extends Error { readonly error: BridgeError; } +// @public (undocumented) +export type BuildPdfInput = { + action: "build"; + code: string; + fonts?: Array<{ + family: string; + weight?: number; + style?: "normal" | "italic"; + }>; + name?: string; + assets?: Array<{ + path: string; + dataUrl: string; + } | { + path: string; + shader: { + code: string; + width: number; + height: number; + textures?: string[]; + }; + }>; +} | { + action: "status"; + jobId: string; +} | { + action: "cancel"; + jobId: string; +}; + +// @public (undocumented) +export type BuildPdfOutput = { + jobId: string; + status: "running"; +} | { + jobId: string; + status: "succeeded"; + pageCount: number; + warnings: Array<{ + severity: "warning"; + code: "typst" | "shader" | "unsupported_dependency"; + message: string; + file?: string; + line?: number; + column?: number; + }>; + preview: { + success: true; + data: { + page: number; + imageDataUrl: string; + imageWidth: number; + imageHeight: number; + badges: Record; + }; + } | { + success: false; + error: { + code: "bad_request:no_document_loaded" | "bad_request:invalid_page" | "bad_request:page_out_of_range" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:plan_upgrade_required" | "bad_request:signup_required" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "conflict:inspection_state_changed" | "unexpected:internal_error"; + message: string; + }; + }; +} | { + jobId: string; + status: "failed"; + error: { + code: "unsupported_dependency" | "font_unavailable" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; + message: string; + retryable: boolean; + diagnostics: Array<{ + severity: "error" | "warning"; + code: "typst" | "shader" | "unsupported_dependency"; + message: string; + file?: string; + line?: number; + column?: number; + }>; + }; +} | { + jobId: string; + status: "cancelled"; +} | { + jobId: string; + status: "superseded"; +}; + // @public (undocumented) export const createEmbed: (args: CreateEmbedArgs) => Embed; @@ -247,6 +333,26 @@ export type GetAnnotatedPageOutput = { badges: Record; }; +// @public (undocumented) +export type GetDocumentationInput = { + topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.graphics" | "build_pdf.shaders" | "build_pdf.troubleshooting" | "fields" | "inspection"; +} | { + topic: "build_pdf.fonts"; + query?: string; +}; + +// @public (undocumented) +export type GetDocumentationOutput = { + kind: "index"; + topics: Array<{ + topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.graphics" | "build_pdf.shaders" | "build_pdf.troubleshooting" | "fields" | "inspection"; + description: string; + }>; +} | { + kind: "topic"; + markdown: string; +}; + // @public (undocumented) export type GetDocumentContentInput = { extractionMode?: ExtractionMode; @@ -280,6 +386,8 @@ export type GoToInput = { // @public (undocumented) export type IframeActions = { + buildPdf: (input: BuildPdfInput) => Promise>; + getDocumentation: (input?: GetDocumentationInput) => Promise>; batchSetFieldValues: (input: BatchSetFieldValuesInput) => Promise; createField: (input: CreateFieldInput) => Promise>; deleteFields: (input?: DeleteFieldsInput) => Promise>; diff --git a/embed/etc/protocol.api.md b/embed/etc/protocol.api.md index 46a405dd..75f34dbf 100644 --- a/embed/etc/protocol.api.md +++ b/embed/etc/protocol.api.md @@ -5,7 +5,7 @@ ```ts // @public (undocumented) -export const EDITOR_ERROR_CODES: readonly ["bad_request:batch_validation_failed", "bad_request:download_blocked", "bad_request:editor_not_ready", "bad_request:event_not_allowed", "bad_request:failed_to_load_document", "bad_request:field_not_found", "bad_request:invalid_dimensions", "bad_request:invalid_event_type", "bad_request:invalid_field_ids", "bad_request:invalid_field_type", "bad_request:invalid_page", "bad_request:invalid_signature_url", "bad_request:invalid_tool", "bad_request:invalid_value", "bad_request:missing_required_fields", "bad_request:no_document_loaded", "bad_request:page_not_found", "bad_request:page_out_of_range", "bad_request:plan_upgrade_required", "bad_request:read_only", "bad_request:signup_required", "forbidden:editing_not_allowed", "forbidden:origin_not_whitelisted", "forbidden:whitelist_required", "unexpected:internal_error"]; +export const EDITOR_ERROR_CODES: readonly ["bad_request:batch_validation_failed", "bad_request:download_blocked", "bad_request:editor_not_ready", "bad_request:event_not_allowed", "bad_request:failed_to_load_document", "bad_request:field_not_found", "bad_request:invalid_dimensions", "bad_request:invalid_event_type", "bad_request:invalid_field_ids", "bad_request:invalid_field_type", "bad_request:invalid_page", "bad_request:invalid_signature_url", "bad_request:invalid_tool", "bad_request:invalid_value", "bad_request:missing_required_fields", "bad_request:no_document_loaded", "bad_request:page_not_found", "bad_request:page_out_of_range", "bad_request:plan_upgrade_required", "bad_request:read_only", "bad_request:signup_required", "conflict:editor_modified", "conflict:inspection_state_changed", "conflict:unmanaged_document", "forbidden:editing_not_allowed", "forbidden:origin_not_whitelisted", "forbidden:recipient_link_used", "forbidden:whitelist_required", "not_found:job", "not_found:job_expired", "resource:session_limit", "unexpected:internal_error"]; // @public (undocumented) export const EXTRACTION_MODES: readonly ["auto", "ocr"]; @@ -27,6 +27,22 @@ export const LOCALES: readonly ["fr", "en", "it", "de", "pt", "es", "ja", "nl"]; // @public (undocumented) export const OPERATIONS: readonly [{ + readonly request_type: "BUILD_PDF"; + readonly wire_type: "BUILD_PDF"; + readonly method: "buildPdf"; + readonly description: "Build and display Typst PDFs. See documentation. Each build starts a new attempt; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing."; + readonly error_codes: readonly ["conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", "bad_request:invalid_value", "forbidden:editing_not_allowed"]; + readonly is_agentic_tool: true; + readonly has_output: true; +}, { + readonly request_type: "GET_DOCUMENTATION"; + readonly wire_type: "GET_DOCUMENTATION"; + readonly method: "getDocumentation"; + readonly description: "Read task guidance and tested PDF recipes. Omit topic for the index."; + readonly error_codes: readonly ["bad_request:invalid_value"]; + readonly is_agentic_tool: true; + readonly has_output: true; +}, { readonly request_type: "BATCH_SET_FIELD_VALUES"; readonly wire_type: "BATCH_SET_FIELD_VALUES"; readonly method: "batchSetFieldValues"; @@ -159,7 +175,7 @@ export const OPERATIONS: readonly [{ readonly wire_type: "SUBMIT"; readonly method: "submit"; readonly description: "Submit the completed document through the editor's finalization flow. This is irreversible. Fails with bad_request:missing_required_fields when required fields are unfilled. Returns no data."; - readonly error_codes: readonly ["bad_request:no_document_loaded", "bad_request:invalid_value", "bad_request:missing_required_fields"]; + readonly error_codes: readonly ["bad_request:no_document_loaded", "bad_request:invalid_value", "bad_request:missing_required_fields", "forbidden:recipient_link_used"]; readonly is_agentic_tool: true; readonly has_output: false; }]; @@ -170,10 +186,10 @@ export const OUTBOUND_EVENT_TYPES: ("EDITOR_READY" | "DOCUMENT_LOADED" | "PAGE_F // @public (undocumented) export const OUTBOUND_EVENTS: readonly [{ readonly event_type: "EDITOR_READY"; - readonly description: "Pushed once when the editor iframe boots in loading-placeholder mode (the loadingPlaceholder=true iframe query flag, which @simplepdf/embed sets while it waits to post LOAD_DOCUMENT) and accepts operations; before it, LOAD_DOCUMENT fails with bad_request:editor_not_ready and every other operation with bad_request:no_document_loaded. An iframe opened with a document instead goes straight to DOCUMENT_LOADED. It is not replayed: a listener attached after boot never receives it, so treat bad_request:editor_not_ready as \"retry shortly\" rather than waiting for this event."; + readonly description: "Pushed once when the editor iframe boots in loading-placeholder mode (the loadingPlaceholder=true iframe query flag, which @simplepdf/embed sets while it waits to post LOAD_DOCUMENT) and accepts operations; before it, LOAD_DOCUMENT fails with bad_request:editor_not_ready and document-dependent operations with bad_request:no_document_loaded; PDF building and documentation are available in an empty editor. An iframe opened with a document instead goes straight to DOCUMENT_LOADED. It is not replayed: a listener attached after boot never receives it, so treat bad_request:editor_not_ready as \"retry shortly\" rather than waiting for this event."; }, { readonly event_type: "DOCUMENT_LOADED"; - readonly description: "Pushed exactly once per loaded document, when the document and its fields are ready; the payload carries the document_id. It follows the LOAD_DOCUMENT reply, which is itself sent once the document is ready, so a request sent after that reply acts on the new document; before any document, operations other than LOAD_DOCUMENT fail with bad_request:no_document_loaded, and until it fires for a document the page opened itself GET_FIELDS may report an incomplete field list. On a blank editor it fires once a document is loaded, by LOAD_DOCUMENT or by the user."; + readonly description: "Pushed exactly once per loaded document, when the document and its fields are ready; the payload carries the document_id. It follows the LOAD_DOCUMENT reply, which is itself sent once the document is ready, so a request sent after that reply acts on the new document; before any document, document-dependent operations fail with bad_request:no_document_loaded; PDF building and documentation are available in an empty editor, and until it fires for a document the page opened itself GET_FIELDS may report an incomplete field list. On a blank editor it fires once a document is loaded, by LOAD_DOCUMENT or by the user."; }, { readonly event_type: "PAGE_FOCUSED"; readonly description: "Pushed when the focused page changes (the user scrolls to a new page, or a GO_TO completes). The payload reports the current page."; @@ -192,13 +208,13 @@ export const OVERLAY_TOOL_TYPES: readonly ["TEXT", "SIGNATURE", "PICTURE", "CHEC export type OverlayToolType = (typeof OVERLAY_TOOL_TYPES)[number]; // @public (undocumented) -export const REQUEST_TYPES: ("BATCH_SET_FIELD_VALUES" | "CREATE_FIELD" | "DELETE_FIELDS" | "DELETE_PAGES" | "DETECT_FIELDS" | "DOWNLOAD" | "FOCUS_FIELD" | "GET_ANNOTATED_PAGE" | "GET_DOCUMENT_CONTENT" | "GET_FIELDS" | "GO_TO" | "LOAD_DOCUMENT" | "MOVE_PAGE" | "ROTATE_PAGE" | "SELECT_TOOL" | "SET_FIELD_VALUE" | "SUBMIT")[]; +export const REQUEST_TYPES: ("BUILD_PDF" | "GET_DOCUMENTATION" | "BATCH_SET_FIELD_VALUES" | "CREATE_FIELD" | "DELETE_FIELDS" | "DELETE_PAGES" | "DETECT_FIELDS" | "DOWNLOAD" | "FOCUS_FIELD" | "GET_ANNOTATED_PAGE" | "GET_DOCUMENT_CONTENT" | "GET_FIELDS" | "GO_TO" | "LOAD_DOCUMENT" | "MOVE_PAGE" | "ROTATE_PAGE" | "SELECT_TOOL" | "SET_FIELD_VALUE" | "SUBMIT")[]; // @public (undocumented) export type RequestType = (typeof OPERATIONS)[number]["request_type"]; // @public (undocumented) -export const WIRE_TYPES: ("BATCH_SET_FIELD_VALUES" | "CREATE_FIELD" | "DELETE_FIELDS" | "DELETE_PAGES" | "DETECT_FIELDS" | "DOWNLOAD" | "FOCUS_FIELD" | "GET_ANNOTATED_PAGE" | "GET_DOCUMENT_CONTENT" | "GET_FIELDS" | "GO_TO" | "LOAD_DOCUMENT" | "MOVE_PAGE" | "ROTATE_PAGE" | "SELECT_TOOL" | "SET_FIELD_VALUE" | "SUBMIT")[]; +export const WIRE_TYPES: ("BUILD_PDF" | "GET_DOCUMENTATION" | "BATCH_SET_FIELD_VALUES" | "CREATE_FIELD" | "DELETE_FIELDS" | "DELETE_PAGES" | "DETECT_FIELDS" | "DOWNLOAD" | "FOCUS_FIELD" | "GET_ANNOTATED_PAGE" | "GET_DOCUMENT_CONTENT" | "GET_FIELDS" | "GO_TO" | "LOAD_DOCUMENT" | "MOVE_PAGE" | "ROTATE_PAGE" | "SELECT_TOOL" | "SET_FIELD_VALUE" | "SUBMIT")[]; // @public (undocumented) export type WireType = (typeof OPERATIONS)[number]["wire_type"]; diff --git a/embed/etc/schemas.api.md b/embed/etc/schemas.api.md index 6becd80f..b8955821 100644 --- a/embed/etc/schemas.api.md +++ b/embed/etc/schemas.api.md @@ -17,6 +17,42 @@ export const BatchSetFieldValuesInput: z.ZodObject<{ // @public (undocumented) export type BatchSetFieldValuesInput = z.infer; +// @public (undocumented) +export const BuildPdfInput: z.ZodUnion; + code: z.ZodString; + fonts: z.ZodOptional; + style: z.ZodOptional>; + }, z.core.$strict>>>; + name: z.ZodOptional; + assets: z.ZodOptional, z.ZodObject<{ + path: z.ZodString; + shader: z.ZodObject<{ + code: z.ZodString; + width: z.ZodNumber; + height: z.ZodNumber; + textures: z.ZodOptional>; + }, z.core.$strict>; + }, z.core.$strict>]>>>; +}, z.core.$strict>, z.ZodObject<{ + action: z.ZodLiteral<"status">; + jobId: z.ZodString; +}, z.core.$strict>, z.ZodObject<{ + action: z.ZodLiteral<"cancel">; + jobId: z.ZodString; +}, z.core.$strict>]>; + +// @public (undocumented) +export type BuildPdfInput = z.infer; + // @public (undocumented) export const CreateFieldInput: z.ZodObject<{ type: z.ZodEnum<{ @@ -82,6 +118,29 @@ export const GetAnnotatedPageInput: z.ZodObject<{ // @public (undocumented) export type GetAnnotatedPageInput = z.infer; +// @public (undocumented) +export const GetDocumentationInput: z.ZodUnion>; +}, z.core.$strict>, z.ZodObject<{ + topic: z.ZodEnum<{ + "build_pdf.fonts": "build_pdf.fonts"; + }>; + query: z.ZodOptional; +}, z.core.$strict>]>; + +// @public (undocumented) +export type GetDocumentationInput = z.infer; + // @public (undocumented) export const GetDocumentContentInput: z.ZodObject<{ extractionMode: z.ZodOptional value is SimplePDFToolName; @@ -18,123 +17,285 @@ export const routeToolCall: (actions: IframeActions, toolName: SimplePDFToolName // @public (undocumented) export const SIMPLEPDF_TOOLS: { + readonly buildPdf: { + readonly description: "Build and display Typst PDFs. See documentation. Each build starts a new attempt; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing."; + readonly inputSchema: z.ZodObject<{ + action: z.ZodUnion, z.ZodLiteral<"status">, z.ZodLiteral<"cancel">]>; + code: z.ZodOptional; + fonts: z.ZodOptional; + style: z.ZodOptional>; + }, z.core.$strict>>>; + name: z.ZodOptional; + assets: z.ZodOptional, z.ZodObject<{ + path: z.ZodString; + shader: z.ZodObject<{ + code: z.ZodString; + width: z.ZodNumber; + height: z.ZodNumber; + textures: z.ZodOptional>; + }, z.core.$strict>; + }, z.core.$strict>]>>>; + jobId: z.ZodOptional; + }, z.core.$strict> & z.ZodType<{ + action: "build"; + code: string; + fonts?: { + family: string; + weight?: number | undefined; + style?: "normal" | "italic" | undefined; + }[] | undefined; + name?: string | undefined; + assets?: ({ + path: string; + dataUrl: string; + } | { + path: string; + shader: { + code: string; + width: number; + height: number; + textures?: string[] | undefined; + }; + })[] | undefined; + } | { + action: "status"; + jobId: string; + } | { + action: "cancel"; + jobId: string; + }, { + action: "build" | "status" | "cancel"; + code?: string | undefined; + fonts?: { + family: string; + weight?: number | undefined; + style?: "normal" | "italic" | undefined; + }[] | undefined; + name?: string | undefined; + assets?: ({ + path: string; + dataUrl: string; + } | { + path: string; + shader: { + code: string; + width: number; + height: number; + textures?: string[] | undefined; + }; + })[] | undefined; + jobId?: string | undefined; + }, z.core.$ZodTypeInternals<{ + action: "build"; + code: string; + fonts?: { + family: string; + weight?: number | undefined; + style?: "normal" | "italic" | undefined; + }[] | undefined; + name?: string | undefined; + assets?: ({ + path: string; + dataUrl: string; + } | { + path: string; + shader: { + code: string; + width: number; + height: number; + textures?: string[] | undefined; + }; + })[] | undefined; + } | { + action: "status"; + jobId: string; + } | { + action: "cancel"; + jobId: string; + }, { + action: "build" | "status" | "cancel"; + code?: string | undefined; + fonts?: { + family: string; + weight?: number | undefined; + style?: "normal" | "italic" | undefined; + }[] | undefined; + name?: string | undefined; + assets?: ({ + path: string; + dataUrl: string; + } | { + path: string; + shader: { + code: string; + width: number; + height: number; + textures?: string[] | undefined; + }; + })[] | undefined; + jobId?: string | undefined; + }>>; + }; + readonly getDocumentation: { + readonly description: "Read task guidance and tested PDF recipes. Omit topic for the index."; + readonly inputSchema: z.ZodObject<{ + topic: z.ZodOptional, z.ZodEnum<{ + "build_pdf.fonts": "build_pdf.fonts"; + }>]>>; + query: z.ZodOptional; + }, z.core.$strict> & z.ZodType<{ + topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.graphics" | "build_pdf.shaders" | "build_pdf.troubleshooting" | "fields" | "inspection" | undefined; + } | { + topic: "build_pdf.fonts"; + query?: string | undefined; + }, { + topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.graphics" | "build_pdf.shaders" | "build_pdf.troubleshooting" | "fields" | "inspection" | "build_pdf.fonts" | undefined; + query?: string | undefined; + }, z.core.$ZodTypeInternals<{ + topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.graphics" | "build_pdf.shaders" | "build_pdf.troubleshooting" | "fields" | "inspection" | undefined; + } | { + topic: "build_pdf.fonts"; + query?: string | undefined; + }, { + topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.graphics" | "build_pdf.shaders" | "build_pdf.troubleshooting" | "fields" | "inspection" | "build_pdf.fonts" | undefined; + query?: string | undefined; + }>>; + }; readonly batchSetFieldValues: { readonly description: "Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data."; - readonly inputSchema: zod.ZodObject<{ - updates: zod.ZodArray; - }, zod_v4_core.$strip>>; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + updates: z.ZodArray; + }, z.core.$strip>>; + }, z.core.$strip>; }; readonly createField: { readonly description: "Create a new overlay field on a page. Returns the id of the created field."; - readonly inputSchema: zod.ZodObject<{ - type: zod.ZodEnum<{ + readonly inputSchema: z.ZodObject<{ + type: z.ZodEnum<{ TEXT: "TEXT"; SIGNATURE: "SIGNATURE"; PICTURE: "PICTURE"; CHECKBOX: "CHECKBOX"; COMB_TEXT: "COMB_TEXT"; }>; - x: zod.ZodNumber; - y: zod.ZodNumber; - width: zod.ZodNumber; - height: zod.ZodNumber; - page: zod.ZodNumber; - value: zod.ZodOptional; - }, zod_v4_core.$strip>; + x: z.ZodNumber; + y: z.ZodNumber; + width: z.ZodNumber; + height: z.ZodNumber; + page: z.ZodNumber; + value: z.ZodOptional; + }, z.core.$strip>; }; readonly deleteFields: { readonly description: "Delete overlay fields: the ones listed, every one on a page, or every one in the document. Returns the number of fields deleted. Destructive."; - readonly inputSchema: zod.ZodObject<{ - fieldIds: zod.ZodOptional>; - page: zod.ZodOptional; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + fieldIds: z.ZodOptional>; + page: z.ZodOptional; + }, z.core.$strip>; }; readonly deletePages: { readonly description: "Delete pages from the document (it cannot delete every visible page). Returns no data. Destructive."; - readonly inputSchema: zod.ZodObject<{ - pages: zod.ZodArray; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + pages: z.ZodArray; + }, z.core.$strip>; }; readonly detectFields: { readonly description: "Automatically detect fillable fields in the loaded document and add them as editable fields. Returns the number of fields detected."; - readonly inputSchema: zod.ZodObject<{}, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{}, z.core.$strip>; }; readonly download: { readonly description: "Generate and download the current document as a PDF. Returns no data."; - readonly inputSchema: zod.ZodObject<{}, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{}, z.core.$strip>; }; readonly focusField: { readonly description: "Scroll an existing field into view and focus it, addressed by its id from the field list. Returns a hint describing the user action expected next."; - readonly inputSchema: zod.ZodObject<{ - fieldId: zod.ZodString; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + fieldId: z.ZodString; + }, z.core.$strip>; }; readonly getAnnotatedPage: { readonly description: "Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block."; - readonly inputSchema: zod.ZodObject<{ - page: zod.ZodNumber; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + page: z.ZodNumber; + }, z.core.$strip>; }; readonly getDocumentContent: { readonly description: "Extract the document's content page by page as Markdown, or as plain text when optical recognition is forced. Use it to read what the document says. Returns the document name and each page's content."; - readonly inputSchema: zod.ZodObject<{ - extractionMode: zod.ZodOptional>; - }, zod_v4_core.$strip>; + }, z.core.$strip>; }; readonly getFields: { readonly description: "List every fillable field in the loaded document, including native dropdown and radio AcroFields. Each field reports its id, name, type, page, current value, and the options its value must be one of, if any. Call this first to discover field ids before reading or setting values. To SEE where each field sits on the printed page, render the annotated page. Returns the field list."; - readonly inputSchema: zod.ZodObject<{}, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{}, z.core.$strip>; }; readonly goTo: { readonly description: "Scroll the editor to a page. Returns no data."; - readonly inputSchema: zod.ZodObject<{ - page: zod.ZodNumber; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + page: z.ZodNumber; + }, z.core.$strip>; }; readonly movePage: { readonly description: "Move a page to another position, reordering the document. Returns no data. Destructive."; - readonly inputSchema: zod.ZodObject<{ - fromPage: zod.ZodNumber; - toPage: zod.ZodNumber; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + fromPage: z.ZodNumber; + toPage: z.ZodNumber; + }, z.core.$strip>; }; readonly rotatePage: { readonly description: "Rotate a page 90 degrees clockwise. Returns no data. Destructive."; - readonly inputSchema: zod.ZodObject<{ - page: zod.ZodNumber; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + page: z.ZodNumber; + }, z.core.$strip>; }; readonly selectTool: { readonly description: "Activate a field-placement tool in the editor toolbar so the user can draw that field type, or pass null to clear the active tool. Returns no data."; - readonly inputSchema: zod.ZodObject<{ - tool: zod.ZodNullable>; - }, zod_v4_core.$strip>; + }, z.core.$strip>; }; readonly setFieldValue: { readonly description: "Set or clear (null) one existing field, addressed by its id from the field list. Text is typed out unless animate is false. Returns no data."; - readonly inputSchema: zod.ZodObject<{ - animate: zod.ZodOptional; - fieldId: zod.ZodString; - value: zod.ZodNullable; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + animate: z.ZodOptional; + fieldId: z.ZodString; + value: z.ZodNullable; + }, z.core.$strip>; }; readonly submit: { readonly description: "Submit the completed document through the editor's finalization flow. This is irreversible. Fails with bad_request:missing_required_fields when required fields are unfilled. Returns no data."; - readonly inputSchema: zod.ZodObject<{ - downloadCopy: zod.ZodBoolean; - }, zod_v4_core.$strip>; + readonly inputSchema: z.ZodObject<{ + downloadCopy: z.ZodBoolean; + }, z.core.$strip>; }; }; diff --git a/embed/scripts/generate.mjs b/embed/scripts/generate.mjs index d10c9508..7d89eee9 100644 --- a/embed/scripts/generate.mjs +++ b/embed/scripts/generate.mjs @@ -3,20 +3,8 @@ // source of truth; this script is the only consumer that re-materializes it as // TypeScript. Run via `npm run generate` (wired into prebuild + pretest). // -// Four outputs, all derived from one source so they cannot hand-drift: -// - src/generated/contract.ts : zero-runtime-dep plain TS types + const tables -// (locales, error codes, operations, events). -// The zero-dep root imports only from here and -// from method-names.ts. -// - src/generated/schemas.ts : zod schemas (peer dep). Each schema is compile-time -// drift-guarded against the plain type in contract.ts, -// so a divergence fails `tsc`. -// - src/generated/method-names.ts : the SDK method names alone, the one generated -// VALUE the zero-dep root imports (to validate -// `webMCP.exclude`). -// - src/generated/webmcp-tools.ts : each operation's WebMCP tool record (manifest -// `tool`), verbatim, read only by the lazily-loaded -// WebMCP module. +// The bridge vocabulary is separate from the full contract so the zero-dependency +// root does not download the operations table. Runtime schemas remain opt-in. // // The JSON Schema vocabulary in embed-api.json is closed and small (object/string/ // integer/number/boolean/null/array/enum/const/anyOf), so the emitter below covers @@ -69,8 +57,8 @@ const NAMED_ENUMS = new Map() // The closed vocabulary the emitter understands. A node carrying any other // keyword (minLength, pattern, format, minimum, oneOf, allOf, $ref, ...) fails // loud so a new manifest constraint can never be silently dropped from the -// generated types/schemas. `additionalProperties` is honored only as a schema on -// an object with no `properties` (a map: Record / z.record). +// generated types/schemas. `additionalProperties:false` preserves strict objects; a schema on an object +// without properties describes a map (Record / z.record). const KNOWN_SCHEMA_KEYWORDS = new Set([ 'type', 'enum', @@ -90,9 +78,9 @@ const assertKnownKeywords = (node) => { ) } } - if (node.additionalProperties !== undefined && !isMapNode(node)) { + if (node.additionalProperties !== undefined && node.additionalProperties !== false && !isMapNode(node)) { throw new Error( - `Unsupported 'additionalProperties' in ${JSON.stringify(node)} — only a schema on an object without 'properties' is honored (a map)`, + `Unsupported 'additionalProperties' in ${JSON.stringify(node)} — only false or a schema on an object without 'properties' is honored`, ) } if (isMapNode(node) && node.required !== undefined) { @@ -249,15 +237,16 @@ const zodForObject = (node) => { const properties = node.properties ?? {} const required = new Set(node.required ?? []) const keys = Object.keys(properties) + const constructor = node.additionalProperties === false ? 'z.strictObject' : 'z.object' if (keys.length === 0) { - return 'z.object({})' + return `${constructor}({})` } const members = keys.map((key) => { const inner = zodForNode(properties[key], { withDescription: true }) const withOptional = required.has(key) ? inner : `${inner}.optional()` return ` ${toCamel(key)}: ${withOptional},` }) - return `z.object({\n${members.join('\n')}\n})` + return `${constructor}({\n${members.join('\n')}\n})` } // --------------------------------------------------------------------------- @@ -333,8 +322,8 @@ const constArray = (name, values, typeName) => { const contractLines = [] contractLines.push('// AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand.') -contractLines.push('// Zero runtime dependencies: the zero-dep root imports only from this module and method-names.ts.') -contractLines.push("import type { METHOD_NAMES } from './method-names'") +contractLines.push('// Zero runtime dependencies: the zero-dep root imports only from this module and bridge-vocabulary.ts.') +contractLines.push("import type { METHOD_NAMES } from './bridge-vocabulary.js'") contractLines.push('') contractLines.push(constArray('LOCALES', contract.locales, 'Locale')) contractLines.push(constArray('EDITOR_ERROR_CODES', editorErrorCodes, 'EditorErrorCode')) @@ -445,17 +434,17 @@ schemaLines.push('') writeFileSync(join(GENERATED_DIR, 'schemas.ts'), renderFile(schemaLines)) -// --- method-names.ts (zero runtime deps; the one generated value the root imports) --- +// --- bridge-vocabulary.ts (the small runtime subset used by the root) --- const methodNames = contract.operations.map((op) => toCamel(op.request_type)) writeFileSync( - join(GENERATED_DIR, 'method-names.ts'), + join(GENERATED_DIR, 'bridge-vocabulary.ts'), renderFile([ '// AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand.', - '// The SDK method names alone, so createEmbed can validate a `webMCP.exclude` list', - '// without pulling the operations table into the zero-dep root; contract.ts derives', - '// MethodName from this list.', + '// Kept separate from the full manifest to preserve the root entry bundle boundary.', `export const METHOD_NAMES = [${methodNames.map((name) => JSON.stringify(name)).join(', ')}] as const`, + `export const STRICT_INPUT_REQUEST_TYPES = ${JSON.stringify(contract.operations.filter((op) => (op.input_schema.anyOf ?? [op.input_schema]).every((schema) => schema.additionalProperties === false)).map((op) => op.request_type))} as const`, + `export const EDITOR_ERROR_PREFIXES = ${JSON.stringify([...new Set(editorErrorCodes.map((code) => code.slice(0, code.indexOf(':') + 1)))])} as const\n`, ]), ) @@ -512,6 +501,8 @@ webmcpToolLines.push(' readonly inputSchema: {') webmcpToolLines.push(" readonly type: 'object'") webmcpToolLines.push(' readonly properties?: Readonly>') webmcpToolLines.push(' readonly required?: readonly string[]') +webmcpToolLines.push(' readonly anyOf?: readonly unknown[]') +webmcpToolLines.push(' readonly additionalProperties?: false') webmcpToolLines.push(' }') webmcpToolLines.push(' readonly annotations: {') for (const hint of WEBMCP_ANNOTATION_KEYS) { @@ -564,17 +555,44 @@ writeFileSync(join(GENERATED_DIR, 'drift.ts'), renderFile(driftLines)) const agenticOperations = contract.operations.filter( (op) => !NON_AGENTIC_OPERATIONS.has(op.request_type.toLowerCase()), ) +// Provider tools require an object root. The broad advertisement is derived from the +// same variants; dispatch still validates the exact action-specific input union. +const toolInputObject = (schema) => { + if (!schema.anyOf) return null + const variants = schema.anyOf + if (variants.some((variant) => variant.type !== 'object')) { + throw new Error('Tool input variants must be objects') + } + const keys = [...new Set(variants.flatMap((variant) => Object.keys(variant.properties ?? {})))] + return { + type: 'object', + additionalProperties: false, + properties: Object.fromEntries(keys.map((key) => { + const values = [...new Map(variants.flatMap((variant) => + variant.properties?.[key] ? [[JSON.stringify(variant.properties[key]), variant.properties[key]]] : [], + )).values()] + return [key, values.length === 1 ? values[0] : { anyOf: values }] + })), + required: keys.filter((key) => variants.every((variant) => variant.required?.includes(key))), + } +} + const toolLines = [] toolLines.push('// AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand.') toolLines.push("import * as Schemas from './schemas'") +toolLines.push("import { z } from 'zod'") toolLines.push('') toolLines.push('// The agentic tool registry. Each tool name is the camelCase operation name;') toolLines.push('// load_document is excluded here (a host/setup action; the WebMCP surface registers it).') toolLines.push('export const TOOL_DEFINITIONS = {') for (const op of agenticOperations) { const stem = toPascal(op.request_type) + const advertisement = toolInputObject(op.input_schema) + const inputSchema = advertisement + ? `${zodForObject(advertisement)}.refine((input): input is z.infer => Schemas.${stem}Input.safeParse(input).success, { message: 'Invalid action input' })` + : `Schemas.${stem}Input` toolLines.push( - ` ${toCamel(op.request_type)}: { description: ${JSON.stringify(op.description)}, inputSchema: Schemas.${stem}Input },`, + ` ${toCamel(op.request_type)}: { description: ${JSON.stringify(op.description)}, inputSchema: ${inputSchema} },`, ) } toolLines.push('} as const') @@ -586,5 +604,5 @@ writeFileSync(join(GENERATED_DIR, 'tools.ts'), renderFile(toolLines)) console.log( `Generated contract.ts (${contract.operations.length} ops, ${contract.events.length} events, ` + - `${contract.locales.length} locales, ${editorErrorCodes.length} editor error codes) + schemas.ts + method-names.ts + webmcp-tools.ts`, + `${contract.locales.length} locales, ${editorErrorCodes.length} editor error codes) + schemas.ts + bridge-vocabulary.ts + webmcp-tools.ts`, ) diff --git a/embed/src/agentic.test-d.ts b/embed/src/agentic.test-d.ts index 5a515914..7a23d15a 100644 --- a/embed/src/agentic.test-d.ts +++ b/embed/src/agentic.test-d.ts @@ -14,3 +14,12 @@ expectTypeOf[number]['name']>().toEq // Browser tools are the documented `AnyClientTool[]`, passed straight to useChat({ tools }). expectTypeOf>().toEqualTypeOf() + +// Provider-compatible JSON must retain the canonical discriminated input in TypeScript. +import type { z } from 'zod' +import { SIMPLEPDF_TOOLS } from './tools' +import type { BuildPdfInput } from './types' +type AdvertisedBuildInput = z.infer +expectTypeOf().toExtend() +expectTypeOf<{ action: 'build' }>().not.toExtend() +expectTypeOf['code']>().toEqualTypeOf() diff --git a/embed/src/bridge.ts b/embed/src/bridge.ts index 80a99669..44fb453b 100644 --- a/embed/src/bridge.ts +++ b/embed/src/bridge.ts @@ -1,4 +1,5 @@ -import { fromWireData, toWireData } from './case-transform' +import { fromWireData, toWireData, InvalidSdkInputError } from './case-transform' +import { STRICT_INPUT_REQUEST_TYPES } from './generated/bridge-vocabulary' import { type BridgeLogger, makeSafeLogger, NOOP_LOGGER } from './logger' import { isBridgeResultLike } from './result' import type { OutboundEventType, WireType } from './generated/contract' @@ -75,11 +76,11 @@ const relabelResult = (result: BridgeResult): BridgeResult) => void - resultShape: ResultShape + payloadShape: PayloadShape wireType: WireType startedAtMs: number timeoutId: ReturnType @@ -215,7 +216,7 @@ export const attachEmbed = ({ } } - const postRequest = (wireType: WireType, data: unknown, resultShape: ResultShape): Promise> => + const postRequest = (wireType: WireType, data: unknown, payloadShape: PayloadShape): Promise> => new Promise>((resolve) => { if (disposed) { resolve({ @@ -233,6 +234,7 @@ export const attachEmbed = ({ return } + const strictInput = STRICT_INPUT_REQUEST_TYPES.some((type) => type === wireType) const requestId = generateRequestId() const startedAtMs = Date.now() // Log identifiers + timing only — never the payload body (it can carry the @@ -253,7 +255,7 @@ export const attachEmbed = ({ pending.set(requestId, { resolve: (result) => resolve(relabelResult(result)), - resultShape, + payloadShape, wireType, startedAtMs, timeoutId, @@ -262,7 +264,19 @@ export const attachEmbed = ({ // Serializing (circular / BigInt input) or posting (dead contentWindow) can // throw; convert that into a Result rather than rejecting the promise. try { - const outbound = JSON.stringify({ type: wireType, request_id: requestId, data: toWireData(data) }) + let wireData: unknown + switch (payloadShape) { + case 'sdk': + wireData = toWireData(data, strictInput) + break + case 'wire': + // Preserve strict inputs for editor validation; established operations retain SDK-key conversion. + wireData = strictInput ? data : toWireData(data) + break + default: + payloadShape satisfies never + } + const outbound = JSON.stringify({ type: wireType, request_id: requestId, data: wireData }) iframe.contentWindow.postMessage(outbound, editorOrigin) logger.debug('iframe.request_posted', { request_id: requestId, type: wireType, char_count: outbound.length }) } catch (error) { @@ -271,7 +285,7 @@ export const attachEmbed = ({ resolve({ success: false, error: { - code: 'unexpected:unknown', + code: error instanceof InvalidSdkInputError ? 'bad_request:invalid_value' : 'unexpected:unknown', message: `Failed to post '${wireType}': ${error instanceof Error ? error.message : String(error)}`, }, }) @@ -479,7 +493,7 @@ export const attachEmbed = ({ if (rawResult.success === true && !('data' in rawResult)) { return { success: true, data: null } } - switch (entry.resultShape) { + switch (entry.payloadShape) { case 'wire': return rawResult case 'sdk': { @@ -496,7 +510,7 @@ export const attachEmbed = ({ return camelCased } default: - entry.resultShape satisfies never + entry.payloadShape satisfies never return rawResult } })() @@ -515,6 +529,8 @@ export const attachEmbed = ({ // ordering, input validation, and typed errors, and always replies. Each method // posts the request and correlates the reply; no client-side validation. const methods = { + buildPdf: (input) => sendRequest('BUILD_PDF', input), + getDocumentation: (input) => sendRequest('GET_DOCUMENTATION', input ?? {}), batchSetFieldValues: (input) => sendRequest('BATCH_SET_FIELD_VALUES', input), createField: (input) => sendRequest('CREATE_FIELD', input), // All-optional input: deleteFields() with no args clears every field. diff --git a/embed/src/case-transform.ts b/embed/src/case-transform.ts index 5173199c..a23db127 100644 --- a/embed/src/case-transform.ts +++ b/embed/src/case-transform.ts @@ -4,7 +4,7 @@ // // KEYS ONLY: string / number / boolean values pass through untouched, so a field // value that happens to contain underscores is never mangled. Payload keys are the -// contract's (SDK callers) or an agent's (the WebMCP path forwards its input as-is); +// contract's (SDK callers) or an agent's (legacy WebMCP calls also normalize keys); // `__proto__` is dropped below and the editor validates every payload, so a // data-controlled key can neither pollute a prototype nor reach an operation unchecked. // The editor `context` is baked into the iframe URL at mount and never travels as an op payload. @@ -46,10 +46,17 @@ const transformKeysDeep = (value: unknown, mapKey: (key: string) => string): unk return value } -// SDK (camelCase) -> wire (snake_case), applied to every outbound request payload. -export const toWireData = (input: unknown): unknown => transformKeysDeep(input, camelToSnakeKey) +// Distinguish rejected SDK input from browser transport failures at the bridge boundary. +export class InvalidSdkInputError extends Error {} -// wire (snake_case) -> SDK (camelCase), applied to every inbound operation RESULT -// payload. Editor EVENTS are NOT transformed — they are forwarded verbatim (snake) to +// SDK (camelCase) -> wire (snake_case). Strict WebMCP inputs bypass conversion so unknown keys reach validation. +export const toWireData = (input: unknown, strict = false): unknown => transformKeysDeep(input, (key) => { + // Strict SDK inputs are camelCase: reject wire aliases before conversion can collapse two keys. + if (strict && key.includes('_')) throw new InvalidSdkInputError('Use camelCase keys for SDK actions.') + return camelToSnakeKey(key) +}) + +// wire (snake_case) -> SDK (camelCase), applied to SDK operation results. WebMCP results remain wire-shaped. +// Editor EVENTS are NOT transformed — they are forwarded verbatim (snake) to // keep the established EmbedEvent contract. export const fromWireData = (data: unknown): unknown => transformKeysDeep(data, snakeToCamelKey) diff --git a/embed/src/generated/bridge-vocabulary.ts b/embed/src/generated/bridge-vocabulary.ts new file mode 100644 index 00000000..e0784a79 --- /dev/null +++ b/embed/src/generated/bridge-vocabulary.ts @@ -0,0 +1,5 @@ +// AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand. +// Kept separate from the full manifest to preserve the root entry bundle boundary. +export const METHOD_NAMES = ["buildPdf", "getDocumentation", "batchSetFieldValues", "createField", "deleteFields", "deletePages", "detectFields", "download", "focusField", "getAnnotatedPage", "getDocumentContent", "getFields", "goTo", "loadDocument", "movePage", "rotatePage", "selectTool", "setFieldValue", "submit"] as const +export const STRICT_INPUT_REQUEST_TYPES = ["BUILD_PDF","GET_DOCUMENTATION"] as const +export const EDITOR_ERROR_PREFIXES = ["bad_request:","conflict:","forbidden:","not_found:","resource:","unexpected:"] as const diff --git a/embed/src/generated/contract.ts b/embed/src/generated/contract.ts index 6addc71b..f0ac8928 100644 --- a/embed/src/generated/contract.ts +++ b/embed/src/generated/contract.ts @@ -1,11 +1,11 @@ // AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand. -// Zero runtime dependencies: the zero-dep root imports only from this module and method-names.ts. -import type { METHOD_NAMES } from './method-names' +// Zero runtime dependencies: the zero-dep root imports only from this module and bridge-vocabulary.ts. +import type { METHOD_NAMES } from './bridge-vocabulary.js' export const LOCALES = ["fr", "en", "it", "de", "pt", "es", "ja", "nl"] as const export type Locale = (typeof LOCALES)[number] -export const EDITOR_ERROR_CODES = ["bad_request:batch_validation_failed", "bad_request:download_blocked", "bad_request:editor_not_ready", "bad_request:event_not_allowed", "bad_request:failed_to_load_document", "bad_request:field_not_found", "bad_request:invalid_dimensions", "bad_request:invalid_event_type", "bad_request:invalid_field_ids", "bad_request:invalid_field_type", "bad_request:invalid_page", "bad_request:invalid_signature_url", "bad_request:invalid_tool", "bad_request:invalid_value", "bad_request:missing_required_fields", "bad_request:no_document_loaded", "bad_request:page_not_found", "bad_request:page_out_of_range", "bad_request:plan_upgrade_required", "bad_request:read_only", "bad_request:signup_required", "forbidden:editing_not_allowed", "forbidden:origin_not_whitelisted", "forbidden:whitelist_required", "unexpected:internal_error"] as const +export const EDITOR_ERROR_CODES = ["bad_request:batch_validation_failed", "bad_request:download_blocked", "bad_request:editor_not_ready", "bad_request:event_not_allowed", "bad_request:failed_to_load_document", "bad_request:field_not_found", "bad_request:invalid_dimensions", "bad_request:invalid_event_type", "bad_request:invalid_field_ids", "bad_request:invalid_field_type", "bad_request:invalid_page", "bad_request:invalid_signature_url", "bad_request:invalid_tool", "bad_request:invalid_value", "bad_request:missing_required_fields", "bad_request:no_document_loaded", "bad_request:page_not_found", "bad_request:page_out_of_range", "bad_request:plan_upgrade_required", "bad_request:read_only", "bad_request:signup_required", "conflict:editor_modified", "conflict:inspection_state_changed", "conflict:unmanaged_document", "forbidden:editing_not_allowed", "forbidden:origin_not_whitelisted", "forbidden:recipient_link_used", "forbidden:whitelist_required", "not_found:job", "not_found:job_expired", "resource:session_limit", "unexpected:internal_error"] as const export type EditorErrorCode = (typeof EDITOR_ERROR_CODES)[number] export const FIELD_TYPES = ["TEXT", "SIGNATURE", "PICTURE", "CHECKBOX", "COMB_TEXT", "DROPDOWN", "RADIO"] as const @@ -17,6 +17,10 @@ export type OverlayToolType = (typeof OVERLAY_TOOL_TYPES)[number] export const EXTRACTION_MODES = ["auto", "ocr"] as const export type ExtractionMode = (typeof EXTRACTION_MODES)[number] +export type BuildPdfInput = { action: "build"; code: string; fonts?: Array<{ family: string; weight?: number; style?: "normal" | "italic" }>; name?: string; assets?: Array<{ path: string; dataUrl: string } | { path: string; shader: { code: string; width: number; height: number; textures?: string[] } }> } | { action: "status"; jobId: string } | { action: "cancel"; jobId: string } +export type BuildPdfOutput = { jobId: string; status: "running" } | { jobId: string; status: "succeeded"; pageCount: number; warnings: Array<{ severity: "warning"; code: "typst" | "shader" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number }>; preview: { success: true; data: { page: number; imageDataUrl: string; imageWidth: number; imageHeight: number; badges: Record } } | { success: false; error: { code: "bad_request:no_document_loaded" | "bad_request:invalid_page" | "bad_request:page_out_of_range" | "bad_request:editor_not_ready" | "bad_request:event_not_allowed" | "bad_request:plan_upgrade_required" | "bad_request:signup_required" | "forbidden:origin_not_whitelisted" | "forbidden:whitelist_required" | "conflict:inspection_state_changed" | "unexpected:internal_error"; message: string } } } | { jobId: string; status: "failed"; error: { code: "unsupported_dependency" | "font_unavailable" | "engine_initialization_failed" | "compile_error" | "compile_timeout" | "job_timeout" | "resource_limit" | "invalid_pdf" | "editor_load_failed" | "editor_conflict" | "worker_crashed" | "internal_error"; message: string; retryable: boolean; diagnostics: Array<{ severity: "error" | "warning"; code: "typst" | "shader" | "unsupported_dependency"; message: string; file?: string; line?: number; column?: number }> } } | { jobId: string; status: "cancelled" } | { jobId: string; status: "superseded" } +export type GetDocumentationInput = { topic?: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.graphics" | "build_pdf.shaders" | "build_pdf.troubleshooting" | "fields" | "inspection" } | { topic: "build_pdf.fonts"; query?: string } +export type GetDocumentationOutput = { kind: "index"; topics: Array<{ topic: "build_pdf" | "build_pdf.templates" | "build_pdf.forms" | "build_pdf.assets" | "build_pdf.fonts" | "build_pdf.graphics" | "build_pdf.shaders" | "build_pdf.troubleshooting" | "fields" | "inspection"; description: string }> } | { kind: "topic"; markdown: string } export type BatchSetFieldValuesInput = { updates: Array<{ fieldId: string; value: string | null }> } export type BatchSetFieldValuesOutput = null export type CreateFieldInput = { type: OverlayToolType; x: number; y: number; width: number; height: number; page: number; value?: string } @@ -68,6 +72,24 @@ export type PageFocusedPayload = { previous_page: number | null; current_page: n export type SubmissionSentPayload = { document_id: string; submission_id: string } export const OPERATIONS = [ + { + request_type: "BUILD_PDF", + wire_type: "BUILD_PDF", + method: "buildPdf", + description: "Build and display Typst PDFs. See documentation. Each build starts a new attempt; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.", + error_codes: ["conflict:editor_modified", "conflict:unmanaged_document", "not_found:job", "not_found:job_expired", "resource:session_limit", "bad_request:invalid_value", "forbidden:editing_not_allowed"] as const, + is_agentic_tool: true, + has_output: true, + } /* BuildPdf */, + { + request_type: "GET_DOCUMENTATION", + wire_type: "GET_DOCUMENTATION", + method: "getDocumentation", + description: "Read task guidance and tested PDF recipes. Omit topic for the index.", + error_codes: ["bad_request:invalid_value"] as const, + is_agentic_tool: true, + has_output: true, + } /* GetDocumentation */, { request_type: "BATCH_SET_FIELD_VALUES", wire_type: "BATCH_SET_FIELD_VALUES", @@ -217,7 +239,7 @@ export const OPERATIONS = [ wire_type: "SUBMIT", method: "submit", description: "Submit the completed document through the editor's finalization flow. This is irreversible. Fails with bad_request:missing_required_fields when required fields are unfilled. Returns no data.", - error_codes: ["bad_request:no_document_loaded", "bad_request:invalid_value", "bad_request:missing_required_fields"] as const, + error_codes: ["bad_request:no_document_loaded", "bad_request:invalid_value", "bad_request:missing_required_fields", "forbidden:recipient_link_used"] as const, is_agentic_tool: true, has_output: false, } /* Submit */, @@ -228,8 +250,8 @@ export type RequestType = (typeof OPERATIONS)[number]["request_type"] export type MethodName = (typeof METHOD_NAMES)[number] export const OUTBOUND_EVENTS = [ - { event_type: "EDITOR_READY", description: "Pushed once when the editor iframe boots in loading-placeholder mode (the loadingPlaceholder=true iframe query flag, which @simplepdf/embed sets while it waits to post LOAD_DOCUMENT) and accepts operations; before it, LOAD_DOCUMENT fails with bad_request:editor_not_ready and every other operation with bad_request:no_document_loaded. An iframe opened with a document instead goes straight to DOCUMENT_LOADED. It is not replayed: a listener attached after boot never receives it, so treat bad_request:editor_not_ready as \"retry shortly\" rather than waiting for this event." }, - { event_type: "DOCUMENT_LOADED", description: "Pushed exactly once per loaded document, when the document and its fields are ready; the payload carries the document_id. It follows the LOAD_DOCUMENT reply, which is itself sent once the document is ready, so a request sent after that reply acts on the new document; before any document, operations other than LOAD_DOCUMENT fail with bad_request:no_document_loaded, and until it fires for a document the page opened itself GET_FIELDS may report an incomplete field list. On a blank editor it fires once a document is loaded, by LOAD_DOCUMENT or by the user." }, + { event_type: "EDITOR_READY", description: "Pushed once when the editor iframe boots in loading-placeholder mode (the loadingPlaceholder=true iframe query flag, which @simplepdf/embed sets while it waits to post LOAD_DOCUMENT) and accepts operations; before it, LOAD_DOCUMENT fails with bad_request:editor_not_ready and document-dependent operations with bad_request:no_document_loaded; PDF building and documentation are available in an empty editor. An iframe opened with a document instead goes straight to DOCUMENT_LOADED. It is not replayed: a listener attached after boot never receives it, so treat bad_request:editor_not_ready as \"retry shortly\" rather than waiting for this event." }, + { event_type: "DOCUMENT_LOADED", description: "Pushed exactly once per loaded document, when the document and its fields are ready; the payload carries the document_id. It follows the LOAD_DOCUMENT reply, which is itself sent once the document is ready, so a request sent after that reply acts on the new document; before any document, document-dependent operations fail with bad_request:no_document_loaded; PDF building and documentation are available in an empty editor, and until it fires for a document the page opened itself GET_FIELDS may report an incomplete field list. On a blank editor it fires once a document is loaded, by LOAD_DOCUMENT or by the user." }, { event_type: "PAGE_FOCUSED", description: "Pushed when the focused page changes (the user scrolls to a new page, or a GO_TO completes). The payload reports the current page." }, { event_type: "SUBMISSION_SENT", description: "Pushed after a SUBMIT completes successfully. This is how you confirm a submission landed: the SUBMIT operation itself resolves with data: null, so listen for this event to get the resulting document_id and submission_id." }, ] as const diff --git a/embed/src/generated/drift.ts b/embed/src/generated/drift.ts index 674c0034..d3ec4010 100644 --- a/embed/src/generated/drift.ts +++ b/embed/src/generated/drift.ts @@ -14,6 +14,8 @@ export type DriftGuards = [ AssertTrue>, AssertTrue>, AssertTrue>, + AssertTrue>, + AssertTrue>, AssertTrue>, AssertTrue>, AssertTrue>, diff --git a/embed/src/generated/method-names.ts b/embed/src/generated/method-names.ts deleted file mode 100644 index 596c7cef..00000000 --- a/embed/src/generated/method-names.ts +++ /dev/null @@ -1,5 +0,0 @@ -// AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand. -// The SDK method names alone, so createEmbed can validate a `webMCP.exclude` list -// without pulling the operations table into the zero-dep root; contract.ts derives -// MethodName from this list. -export const METHOD_NAMES = ["batchSetFieldValues", "createField", "deleteFields", "deletePages", "detectFields", "download", "focusField", "getAnnotatedPage", "getDocumentContent", "getFields", "goTo", "loadDocument", "movePage", "rotatePage", "selectTool", "setFieldValue", "submit"] as const diff --git a/embed/src/generated/schemas.ts b/embed/src/generated/schemas.ts index eaa4055d..20a5498c 100644 --- a/embed/src/generated/schemas.ts +++ b/embed/src/generated/schemas.ts @@ -1,6 +1,42 @@ // AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand. import { z } from 'zod' +export const BuildPdfInput = z.union([z.strictObject({ + action: z.literal("build"), + code: z.string(), + fonts: z.array(z.strictObject({ + family: z.string(), + weight: z.number().int().optional(), + style: z.enum(["normal", "italic"]).optional(), +})).optional(), + name: z.string().optional(), + assets: z.array(z.union([z.strictObject({ + path: z.string(), + dataUrl: z.string(), +}), z.strictObject({ + path: z.string(), + shader: z.strictObject({ + code: z.string(), + width: z.number().int(), + height: z.number().int(), + textures: z.array(z.string()).optional(), +}), +})])).optional(), +}), z.strictObject({ + action: z.literal("status"), + jobId: z.string(), +}), z.strictObject({ + action: z.literal("cancel"), + jobId: z.string(), +})]) +export type BuildPdfInput = z.infer +export const GetDocumentationInput = z.union([z.strictObject({ + topic: z.enum(["build_pdf", "build_pdf.templates", "build_pdf.forms", "build_pdf.assets", "build_pdf.graphics", "build_pdf.shaders", "build_pdf.troubleshooting", "fields", "inspection"]).optional(), +}), z.strictObject({ + topic: z.enum(["build_pdf.fonts"]), + query: z.string().optional(), +})]) +export type GetDocumentationInput = z.infer export const BatchSetFieldValuesInput = z.object({ updates: z.array(z.object({ fieldId: z.string().describe("ID of the field to update."), diff --git a/embed/src/generated/tools.ts b/embed/src/generated/tools.ts index d18bcc6a..c0a2f727 100644 --- a/embed/src/generated/tools.ts +++ b/embed/src/generated/tools.ts @@ -1,9 +1,37 @@ // AUTO-GENERATED from embed-api.json by scripts/generate.mjs. Do not edit by hand. import * as Schemas from './schemas' +import { z } from 'zod' // The agentic tool registry. Each tool name is the camelCase operation name; // load_document is excluded here (a host/setup action; the WebMCP surface registers it). export const TOOL_DEFINITIONS = { + buildPdf: { description: "Build and display Typst PDFs. See documentation. Each build starts a new attempt; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.", inputSchema: z.strictObject({ + action: z.union([z.literal("build"), z.literal("status"), z.literal("cancel")]), + code: z.string().optional(), + fonts: z.array(z.strictObject({ + family: z.string(), + weight: z.number().int().optional(), + style: z.enum(["normal", "italic"]).optional(), +})).optional(), + name: z.string().optional(), + assets: z.array(z.union([z.strictObject({ + path: z.string(), + dataUrl: z.string(), +}), z.strictObject({ + path: z.string(), + shader: z.strictObject({ + code: z.string(), + width: z.number().int(), + height: z.number().int(), + textures: z.array(z.string()).optional(), +}), +})])).optional(), + jobId: z.string().optional(), +}).refine((input): input is z.infer => Schemas.BuildPdfInput.safeParse(input).success, { message: 'Invalid action input' }) }, + getDocumentation: { description: "Read task guidance and tested PDF recipes. Omit topic for the index.", inputSchema: z.strictObject({ + topic: z.union([z.enum(["build_pdf", "build_pdf.templates", "build_pdf.forms", "build_pdf.assets", "build_pdf.graphics", "build_pdf.shaders", "build_pdf.troubleshooting", "fields", "inspection"]), z.enum(["build_pdf.fonts"])]).optional(), + query: z.string().optional(), +}).refine((input): input is z.infer => Schemas.GetDocumentationInput.safeParse(input).success, { message: 'Invalid action input' }) }, batchSetFieldValues: { description: "Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data.", inputSchema: Schemas.BatchSetFieldValuesInput }, createField: { description: "Create a new overlay field on a page. Returns the id of the created field.", inputSchema: Schemas.CreateFieldInput }, deleteFields: { description: "Delete overlay fields: the ones listed, every one on a page, or every one in the document. Returns the number of fields deleted. Destructive.", inputSchema: Schemas.DeleteFieldsInput }, diff --git a/embed/src/generated/webmcp-tools.ts b/embed/src/generated/webmcp-tools.ts index 36854d9c..ecefbd3a 100644 --- a/embed/src/generated/webmcp-tools.ts +++ b/embed/src/generated/webmcp-tools.ts @@ -15,6 +15,8 @@ export type WebMCPToolRecord = { readonly type: 'object' readonly properties?: Readonly> readonly required?: readonly string[] + readonly anyOf?: readonly unknown[] + readonly additionalProperties?: false } readonly annotations: { readonly destructiveHint?: boolean @@ -25,21 +27,23 @@ export type WebMCPToolRecord = { } export const WEBMCP_TOOLS = { - batchSetFieldValues: {"name":"simplepdf_embed_batch_set_field_values","description":"Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data.","inputSchema":{"type":"object","properties":{"updates":{"items":{"type":"object","properties":{"field_id":{"type":"string","description":"ID of the field to update."},"value":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature."}},"required":["field_id","value"]},"description":"The fields to set, at least one, each field at most once. Fields not listed keep their value.","type":"array"}},"required":["updates"]},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"BATCH_SET_FIELD_VALUES"}, - createField: {"name":"simplepdf_embed_create_field","description":"Create a new overlay field on a page. Returns the id of the created field.","inputSchema":{"type":"object","properties":{"type":{"enum":["TEXT","SIGNATURE","PICTURE","CHECKBOX","COMB_TEXT"],"description":"Field type to create.","type":"string"},"x":{"description":"Field x position, in PDF points.","type":"number"},"y":{"description":"Field y position, in PDF points.","type":"number"},"width":{"description":"Field width, in PDF points.","type":"number"},"height":{"description":"Field height, in PDF points.","type":"number"},"page":{"description":"1-based page to place the field on.","type":"integer"},"value":{"description":"Optional initial value. A string for text/checkbox fields; a data URL or http(s) URL (fetched by the editor) for signature/picture fields, or plain text for a signature, drawn as a typed signature.","type":"string"}},"required":["type","x","y","width","height","page"]},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"CREATE_FIELD"}, + buildPdf: {"name":"build_pdf","description":"Build and display Typst PDFs. See documentation. Each build starts a new attempt; poll pending jobs. Success includes a first-page preview. Edits block rebuilding. No sharing.","inputSchema":{"anyOf":[{"type":"object","properties":{"action":{"type":"string","const":"build"},"code":{"type":"string"},"fonts":{"type":"array","items":{"type":"object","properties":{"family":{"type":"string"},"weight":{"type":"integer"},"style":{"type":"string","enum":["normal","italic"]}},"required":["family"],"additionalProperties":false}},"name":{"type":"string"},"assets":{"type":"array","items":{"anyOf":[{"type":"object","properties":{"path":{"type":"string"},"data_url":{"type":"string"}},"required":["path","data_url"],"additionalProperties":false},{"type":"object","properties":{"path":{"type":"string"},"shader":{"type":"object","properties":{"code":{"type":"string"},"width":{"type":"integer"},"height":{"type":"integer"},"textures":{"type":"array","items":{"type":"string"}}},"required":["code","width","height"],"additionalProperties":false}},"required":["path","shader"],"additionalProperties":false}]}}},"required":["action","code"],"additionalProperties":false},{"type":"object","properties":{"action":{"type":"string","const":"status"},"job_id":{"type":"string"}},"required":["action","job_id"],"additionalProperties":false},{"type":"object","properties":{"action":{"type":"string","const":"cancel"},"job_id":{"type":"string"}},"required":["action","job_id"],"additionalProperties":false}],"type":"object","properties":{}},"annotations":{"destructiveHint":true,"untrustedContentHint":true,"openWorldHint":true},"wireType":"BUILD_PDF"}, + getDocumentation: {"name":"get_documentation","description":"Read task guidance and tested PDF recipes. Omit topic for the index.","inputSchema":{"anyOf":[{"type":"object","properties":{"topic":{"type":"string","enum":["build_pdf","build_pdf.templates","build_pdf.forms","build_pdf.assets","build_pdf.graphics","build_pdf.shaders","build_pdf.troubleshooting","fields","inspection"]}},"additionalProperties":false},{"type":"object","properties":{"topic":{"type":"string","enum":["build_pdf.fonts"]},"query":{"type":"string"}},"required":["topic"],"additionalProperties":false}],"type":"object","properties":{}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_DOCUMENTATION"}, + batchSetFieldValues: {"name":"simplepdf_embed_batch_set_field_values","description":"Set existing fields, addressed by ids from the field list, in one atomic undo step. If any update is rejected, nothing changes and the call fails with bad_request:batch_validation_failed, whose details list each rejection with its field id, code and message. Text is set at once, never typed. Returns no data.","inputSchema":{"required":["updates"],"type":"object","properties":{"updates":{"items":{"type":"object","properties":{"field_id":{"type":"string","description":"ID of the field to update."},"value":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature."}},"required":["field_id","value"]},"description":"The fields to set, at least one, each field at most once. Fields not listed keep their value.","type":"array"}}},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"BATCH_SET_FIELD_VALUES"}, + createField: {"name":"simplepdf_embed_create_field","description":"Create a new overlay field on a page. Returns the id of the created field.","inputSchema":{"required":["type","x","y","width","height","page"],"type":"object","properties":{"type":{"enum":["TEXT","SIGNATURE","PICTURE","CHECKBOX","COMB_TEXT"],"description":"Field type to create.","type":"string"},"x":{"description":"Field x position, in PDF points.","type":"number"},"y":{"description":"Field y position, in PDF points.","type":"number"},"width":{"description":"Field width, in PDF points.","type":"number"},"height":{"description":"Field height, in PDF points.","type":"number"},"page":{"description":"1-based page to place the field on.","type":"integer"},"value":{"description":"Optional initial value. A string for text/checkbox fields; a data URL or http(s) URL (fetched by the editor) for signature/picture fields, or plain text for a signature, drawn as a typed signature.","type":"string"}}},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"CREATE_FIELD"}, deleteFields: {"name":"simplepdf_embed_delete_fields","description":"Delete overlay fields: the ones listed, every one on a page, or every one in the document. Returns the number of fields deleted. Destructive.","inputSchema":{"type":"object","properties":{"field_ids":{"description":"IDs of the fields to delete. Omit to delete every field on the target page.","items":{"type":"string"},"type":"array"},"page":{"description":"1-based page to scope the deletion to. Omit to target all pages.","type":"integer"}}},"annotations":{"destructiveHint":true},"wireType":"DELETE_FIELDS"}, - deletePages: {"name":"simplepdf_embed_delete_pages","description":"Delete pages from the document (it cannot delete every visible page). Returns no data. Destructive.","inputSchema":{"type":"object","properties":{"pages":{"items":{"type":"integer"},"description":"1-based page numbers to delete.","type":"array"}},"required":["pages"]},"annotations":{"destructiveHint":true},"wireType":"DELETE_PAGES"}, + deletePages: {"name":"simplepdf_embed_delete_pages","description":"Delete pages from the document (it cannot delete every visible page). Returns no data. Destructive.","inputSchema":{"required":["pages"],"type":"object","properties":{"pages":{"items":{"type":"integer"},"description":"1-based page numbers to delete.","type":"array"}}},"annotations":{"destructiveHint":true},"wireType":"DELETE_PAGES"}, detectFields: {"name":"simplepdf_embed_detect_fields","description":"Automatically detect fillable fields in the loaded document and add them as editable fields. Returns the number of fields detected.","inputSchema":{"type":"object","properties":{}},"annotations":{"destructiveHint":false},"wireType":"DETECT_FIELDS"}, download: {"name":"simplepdf_embed_download","description":"Generate and download the current document as a PDF. Returns no data.","inputSchema":{"type":"object","properties":{}},"annotations":{"destructiveHint":false},"wireType":"DOWNLOAD"}, - focusField: {"name":"simplepdf_embed_focus_field","description":"Scroll an existing field into view and focus it, addressed by its id from the field list. Returns a hint describing the user action expected next.","inputSchema":{"type":"object","properties":{"field_id":{"description":"ID of the field to focus and scroll into view.","type":"string"}},"required":["field_id"]},"annotations":{"destructiveHint":false},"wireType":"FOCUS_FIELD"}, - getAnnotatedPage: {"name":"simplepdf_embed_get_annotated_page","description":"Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block.","inputSchema":{"type":"object","properties":{"page":{"description":"1-based page to render, at its current position.","type":"integer"}},"required":["page"]},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_ANNOTATED_PAGE"}, + focusField: {"name":"simplepdf_embed_focus_field","description":"Scroll an existing field into view and focus it, addressed by its id from the field list. Returns a hint describing the user action expected next.","inputSchema":{"required":["field_id"],"type":"object","properties":{"field_id":{"description":"ID of the field to focus and scroll into view.","type":"string"}}},"annotations":{"destructiveHint":false},"wireType":"FOCUS_FIELD"}, + getAnnotatedPage: {"name":"simplepdf_embed_get_annotated_page","description":"Render a page as a PNG with every field outlined and numbered, so a vision model can see which field sits where on the printed form (placement only: read values from the field list). Returns the page, the PNG as a data URL, its width and height in pixels, and badges mapping each number drawn on the image to a field id; as a WebMCP tool the PNG arrives as an image block and the rest as a text block.","inputSchema":{"required":["page"],"type":"object","properties":{"page":{"description":"1-based page to render, at its current position.","type":"integer"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_ANNOTATED_PAGE"}, getDocumentContent: {"name":"simplepdf_embed_get_document_content","description":"Extract the document's content page by page as Markdown, or as plain text when optical recognition is forced. Use it to read what the document says. Returns the document name and each page's content.","inputSchema":{"type":"object","properties":{"extraction_mode":{"description":"Extraction strategy: 'auto' (default) or 'ocr' to force optical recognition.","enum":["auto","ocr"],"type":"string"}}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_DOCUMENT_CONTENT"}, getFields: {"name":"simplepdf_embed_get_fields","description":"List every fillable field in the loaded document, including native dropdown and radio AcroFields. Each field reports its id, name, type, page, current value, and the options its value must be one of, if any. Call this first to discover field ids before reading or setting values. To SEE where each field sits on the printed page, render the annotated page. Returns the field list.","inputSchema":{"type":"object","properties":{}},"annotations":{"readOnlyHint":true,"untrustedContentHint":true},"wireType":"GET_FIELDS"}, - goTo: {"name":"simplepdf_embed_go_to","description":"Scroll the editor to a page. Returns no data.","inputSchema":{"type":"object","properties":{"page":{"description":"1-based page to navigate to.","type":"integer"}},"required":["page"]},"annotations":{"destructiveHint":false},"wireType":"GO_TO"}, - loadDocument: {"name":"simplepdf_embed_load_document","description":"Replace the document in the editor with one supplied as a base64 data URL or an http(s) URL the editor fetches. Destructive: the current document and every edit in it are discarded. Replies once the document and its fields are ready, so the next operation can act on it, and DOCUMENT_LOADED follows the reply; the URL already open is left as is and answers once it settles; a document that cannot be loaded or prepared answers bad_request:failed_to_load_document. Returns no data.","inputSchema":{"type":"object","properties":{"data_url":{"description":"The document to load: a data URL, or an http(s) URL the editor fetches.","type":"string"},"name":{"description":"Optional display name for the document.","type":"string"},"page":{"description":"Optional 1-based page to open the document on.","type":"integer"}},"required":["data_url"]},"annotations":{"destructiveHint":true,"openWorldHint":true},"wireType":"LOAD_DOCUMENT"}, - movePage: {"name":"simplepdf_embed_move_page","description":"Move a page to another position, reordering the document. Returns no data. Destructive.","inputSchema":{"type":"object","properties":{"from_page":{"description":"1-based current position of the page to move.","type":"integer"},"to_page":{"description":"1-based destination position for the page.","type":"integer"}},"required":["from_page","to_page"]},"annotations":{"destructiveHint":true},"wireType":"MOVE_PAGE"}, - rotatePage: {"name":"simplepdf_embed_rotate_page","description":"Rotate a page 90 degrees clockwise. Returns no data. Destructive.","inputSchema":{"type":"object","properties":{"page":{"description":"1-based page to rotate.","type":"integer"}},"required":["page"]},"annotations":{"destructiveHint":true},"wireType":"ROTATE_PAGE"}, - selectTool: {"name":"simplepdf_embed_select_tool","description":"Activate a field-placement tool in the editor toolbar so the user can draw that field type, or pass null to clear the active tool. Returns no data.","inputSchema":{"type":"object","properties":{"tool":{"anyOf":[{"type":"string","enum":["TEXT","SIGNATURE","PICTURE","CHECKBOX","COMB_TEXT"]},{"type":"null"}],"description":"Tool to activate, or null to deselect."}},"required":["tool"]},"annotations":{"destructiveHint":false},"wireType":"SELECT_TOOL"}, - setFieldValue: {"name":"simplepdf_embed_set_field_value","description":"Set or clear (null) one existing field, addressed by its id from the field list. Text is typed out unless animate is false. Returns no data.","inputSchema":{"type":"object","properties":{"animate":{"description":"Type a text value out character by character (true, the default) so a person watching the editor can follow the field being filled, or set it at once (false) for headless or batch filling where speed matters. Only text values are typed: checkbox, option, signature, picture and null values are always set at once.","type":"boolean"},"field_id":{"description":"ID of the field to update.","type":"string"},"value":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature."}},"required":["field_id","value"]},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"SET_FIELD_VALUE"}, - submit: {"name":"simplepdf_embed_submit","description":"Submit the completed document through the editor's finalization flow. This is irreversible. Fails with bad_request:missing_required_fields when required fields are unfilled. Returns no data.","inputSchema":{"type":"object","properties":{"download_copy":{"description":"When true, the signer also receives a downloaded copy on submit.","type":"boolean"}},"required":["download_copy"]},"annotations":{"destructiveHint":true},"wireType":"SUBMIT"}, + goTo: {"name":"simplepdf_embed_go_to","description":"Scroll the editor to a page. Returns no data.","inputSchema":{"required":["page"],"type":"object","properties":{"page":{"description":"1-based page to navigate to.","type":"integer"}}},"annotations":{"destructiveHint":false},"wireType":"GO_TO"}, + loadDocument: {"name":"simplepdf_embed_load_document","description":"Replace the document in the editor with one supplied as a base64 data URL or an http(s) URL the editor fetches. Destructive: the current document and every edit in it are discarded. Replies once the document and its fields are ready, so the next operation can act on it, and DOCUMENT_LOADED follows the reply; the URL already open is left as is and answers once it settles; a document that cannot be loaded or prepared answers bad_request:failed_to_load_document. Returns no data.","inputSchema":{"required":["data_url"],"type":"object","properties":{"data_url":{"description":"The document to load: a data URL, or an http(s) URL the editor fetches.","type":"string"},"name":{"description":"Optional display name for the document.","type":"string"},"page":{"description":"Optional 1-based page to open the document on.","type":"integer"}}},"annotations":{"destructiveHint":true,"openWorldHint":true},"wireType":"LOAD_DOCUMENT"}, + movePage: {"name":"simplepdf_embed_move_page","description":"Move a page to another position, reordering the document. Returns no data. Destructive.","inputSchema":{"required":["from_page","to_page"],"type":"object","properties":{"from_page":{"description":"1-based current position of the page to move.","type":"integer"},"to_page":{"description":"1-based destination position for the page.","type":"integer"}}},"annotations":{"destructiveHint":true},"wireType":"MOVE_PAGE"}, + rotatePage: {"name":"simplepdf_embed_rotate_page","description":"Rotate a page 90 degrees clockwise. Returns no data. Destructive.","inputSchema":{"required":["page"],"type":"object","properties":{"page":{"description":"1-based page to rotate.","type":"integer"}}},"annotations":{"destructiveHint":true},"wireType":"ROTATE_PAGE"}, + selectTool: {"name":"simplepdf_embed_select_tool","description":"Activate a field-placement tool in the editor toolbar so the user can draw that field type, or pass null to clear the active tool. Returns no data.","inputSchema":{"required":["tool"],"type":"object","properties":{"tool":{"anyOf":[{"type":"string","enum":["TEXT","SIGNATURE","PICTURE","CHECKBOX","COMB_TEXT"]},{"type":"null"}],"description":"Tool to activate, or null to deselect."}}},"annotations":{"destructiveHint":false},"wireType":"SELECT_TOOL"}, + setFieldValue: {"name":"simplepdf_embed_set_field_value","description":"Set or clear (null) one existing field, addressed by its id from the field list. Text is typed out unless animate is false. Returns no data.","inputSchema":{"required":["field_id","value"],"type":"object","properties":{"animate":{"description":"Type a text value out character by character (true, the default) so a person watching the editor can follow the field being filled, or set it at once (false) for headless or batch filling where speed matters. Only text values are typed: checkbox, option, signature, picture and null values are always set at once.","type":"boolean"},"field_id":{"description":"ID of the field to update.","type":"string"},"value":{"anyOf":[{"type":"string"},{"type":"null"}],"description":"New value for the field, or null to clear it. If the field has options (see the field list), it must be one of them; otherwise a string (text/checkbox), or a data URL or http(s) URL, fetched by the editor (signature/picture), or plain text for a signature, drawn as a typed signature."}}},"annotations":{"destructiveHint":false,"openWorldHint":true},"wireType":"SET_FIELD_VALUE"}, + submit: {"name":"simplepdf_embed_submit","description":"Submit the completed document through the editor's finalization flow. This is irreversible. Fails with bad_request:missing_required_fields when required fields are unfilled. Returns no data.","inputSchema":{"required":["download_copy"],"type":"object","properties":{"download_copy":{"description":"When true, the signer also receives a downloaded copy on submit.","type":"boolean"}}},"annotations":{"destructiveHint":true},"wireType":"SUBMIT"}, } as const satisfies Record diff --git a/embed/src/mount.ts b/embed/src/mount.ts index c396c4b8..60075eba 100644 --- a/embed/src/mount.ts +++ b/embed/src/mount.ts @@ -1,7 +1,7 @@ import { attachEmbed } from './bridge' import { type BridgeLogger, makeSafeLogger, NOOP_LOGGER } from './logger' import type { BridgeState, Embed } from './types' -import { METHOD_NAMES } from './generated/method-names' +import { METHOD_NAMES } from './generated/bridge-vocabulary' import type { Locale } from './generated/contract' import type { WebMCPOptions } from './webmcp-shared' diff --git a/embed/src/result.ts b/embed/src/result.ts index ca0feaf5..3ee598b8 100644 --- a/embed/src/result.ts +++ b/embed/src/result.ts @@ -1,4 +1,5 @@ import type { BridgeResult } from './types' +import { EDITOR_ERROR_PREFIXES } from './generated/bridge-vocabulary' // Runtime guard for the result envelope received from the editor. The payload is // JSON parsed from the editor origin; same-origin policy narrows the attacker @@ -29,12 +30,9 @@ export const isBridgeResultLike = (value: unknown): value is BridgeResult code.startsWith(prefix)) } return false } diff --git a/embed/src/tools.ts b/embed/src/tools.ts index fc2eb598..19e95e7e 100644 --- a/embed/src/tools.ts +++ b/embed/src/tools.ts @@ -7,6 +7,8 @@ import type { z } from 'zod' import { TOOL_DEFINITIONS, type SimplePDFToolName } from './generated/tools' import { + BuildPdfInput, + GetDocumentationInput, BatchSetFieldValuesInput, CreateFieldInput, DeleteFieldsInput, @@ -59,6 +61,10 @@ export const routeToolCall = ( input: unknown, ): Promise> => { switch (toolName) { + case 'buildPdf': + return dispatch(BuildPdfInput, input, (value) => actions.buildPdf(value)) + case 'getDocumentation': + return dispatch(GetDocumentationInput, input ?? {}, (value) => actions.getDocumentation(value)) case 'batchSetFieldValues': return dispatch(BatchSetFieldValuesInput, input, (value) => actions.batchSetFieldValues(value)) case 'createField': diff --git a/embed/src/types.ts b/embed/src/types.ts index afc4e310..c4419108 100644 --- a/embed/src/types.ts +++ b/embed/src/types.ts @@ -4,6 +4,10 @@ // the single source of truth; nothing in this file restates a wire shape. import type { + BuildPdfInput, + BuildPdfOutput, + GetDocumentationInput, + GetDocumentationOutput, BatchSetFieldValuesInput, CreateFieldInput, CreateFieldOutput, @@ -31,9 +35,13 @@ import type { SetFieldValueInput, SubmissionSentPayload, SubmitInput, -} from './generated/contract' +} from './generated/contract.js' export type { + BuildPdfInput, + BuildPdfOutput, + GetDocumentationInput, + GetDocumentationOutput, BatchSetFieldValuesInput, BatchValidationFailedDetails, CreateFieldInput, @@ -69,7 +77,7 @@ export type { SetFieldValueInput, SubmissionSentPayload, SubmitInput, -} from './generated/contract' +} from './generated/contract.js' // A single field as reported by get_fields. Alias kept for ergonomics; the // shape is owned by the generated GetFieldsOutput. @@ -139,6 +147,8 @@ export type EditorEventMap = { [TEvent in EditorEvent as TEvent['type']]: TEvent // throws. Drift-guarded against the generated operation set in ./generated/drift.ts // (a new operation fails the build until added here). export type IframeActions = { + buildPdf: (input: BuildPdfInput) => Promise> + getDocumentation: (input?: GetDocumentationInput) => Promise> batchSetFieldValues: (input: BatchSetFieldValuesInput) => Promise createField: (input: CreateFieldInput) => Promise> deleteFields: (input?: DeleteFieldsInput) => Promise> diff --git a/embed/src/webmcp.ts b/embed/src/webmcp.ts index 156b1fd6..d6de1904 100644 --- a/embed/src/webmcp.ts +++ b/embed/src/webmcp.ts @@ -12,7 +12,6 @@ // CF: https://webmachinelearning.github.io/webmcp/ import type { MethodName, WireType } from './generated/contract' -import { METHOD_NAMES } from './generated/method-names' import { WEBMCP_TOOLS, type WebMCPToolRecord } from './generated/webmcp-tools' import type { BridgeLogger } from './logger' import type { BridgeResult } from './types' @@ -36,32 +35,43 @@ const PNG_DATA_URL_PREFIX = 'data:image/png;base64,' const isModelContext = (value: unknown): value is ModelContext => typeof value === 'object' && value !== null && 'registerTool' in value && typeof value.registerTool === 'function' -const readModelContext = (): ModelContext | null => modelContextCandidates().find(isModelContext) ?? null - const toTextToolResult = (result: BridgeResult): CallToolResult => ({ content: [{ type: 'text', text: JSON.stringify(result) }], ...(result.success ? {} : { isError: true }), }) -// The render travels once, as the image block a vision-capable runtime shows the -// model; the text block keeps the rest of the result (page, size, badges). Anything -// but a successful PNG render takes the plain text envelope. +// Both an annotated page and a build preview carry their PNG once as a native MCP image. +const splitPageImage = (render: unknown): { image: ToolContent; metadata: Record } | null => { + if (typeof render !== 'object' || render === null || !('image_data_url' in render)) return null + const { image_data_url: image, ...metadata } = render + if (typeof image !== 'string' || !image.startsWith(PNG_DATA_URL_PREFIX)) return null + return { image: { type: 'image', data: image.slice(PNG_DATA_URL_PREFIX.length), mimeType: 'image/png' }, metadata } +} + const toAnnotatedPageToolResult = (result: BridgeResult): CallToolResult => { - if (!result.success) { - return toTextToolResult(result) - } - const render: unknown = result.data - if (typeof render !== 'object' || render === null || !('image_data_url' in render)) { - return toTextToolResult(result) - } - const { image_data_url: imageDataUrl, ...renderWithoutImage } = render - if (typeof imageDataUrl !== 'string' || !imageDataUrl.startsWith(PNG_DATA_URL_PREFIX)) { - return toTextToolResult(result) + if (!result.success) return toTextToolResult(result) + const page = splitPageImage(result.data) + if (page === null) return toTextToolResult(result) + return { + content: [page.image, ...toTextToolResult({ success: true, data: page.metadata }).content], } +} + +const toBuildPdfToolResult = (result: BridgeResult): CallToolResult => { + if (!result.success) return toTextToolResult(result) + const job = result.data + if (typeof job !== 'object' || job === null || !('preview' in job)) return toTextToolResult(result) + const preview = job.preview + if ( + typeof preview !== 'object' || preview === null || + !('success' in preview) || preview.success !== true || !('data' in preview) + ) return toTextToolResult(result) + const page = splitPageImage(preview.data) + if (page === null) return toTextToolResult(result) return { content: [ - { type: 'image', data: imageDataUrl.slice(PNG_DATA_URL_PREFIX.length), mimeType: 'image/png' }, - { type: 'text', text: JSON.stringify({ success: true, data: renderWithoutImage }) }, + page.image, + ...toTextToolResult({ success: true, data: { ...job, preview: { success: true, data: page.metadata } } }).content, ], } } @@ -70,8 +80,11 @@ const toAnnotatedPageToolResult = (result: BridgeResult): CallToolResul // is text or a picture instead of taking the text envelope unnoticed. const toCallToolResult = (wireType: WireType, result: BridgeResult): CallToolResult => { switch (wireType) { + case 'BUILD_PDF': + return toBuildPdfToolResult(result) case 'GET_ANNOTATED_PAGE': return toAnnotatedPageToolResult(result) + case 'GET_DOCUMENTATION': case 'BATCH_SET_FIELD_VALUES': case 'CREATE_FIELD': case 'DELETE_FIELDS': @@ -124,32 +137,28 @@ export const registerWebMCPTools = ({ if (signal.aborted) { return false } - const modelContext = readModelContext() - if (modelContext === null) { + const modelContext = modelContextCandidates().find(isModelContext) + if (modelContext === undefined) { logger.info('webmcp.unavailable', { reason: 'invalid_model_context' }) return false } - const excluded = new Set(exclude) - for (const method of METHOD_NAMES) { + const excluded = new Set(exclude) + for (const [method, { wireType, ...record }] of Object.entries(WEBMCP_TOOLS)) { if (excluded.has(method)) { continue } - const record = WEBMCP_TOOLS[method] if (liveTools.has(record.name)) { logger.warn('webmcp.tool_already_registered', { tool: record.name }) continue } const tool: WebMCPTool = { - name: record.name, - description: record.description, - inputSchema: record.inputSchema, - annotations: record.annotations, + ...record, // A call the runtime already aborted never reaches the editor; one aborted after it // was posted still runs there (the wire has no cancel frame). A nullish input becomes // an empty payload (the no-input operations' wire shape). execute: async (input, options) => { options?.signal.throwIfAborted() - return toCallToolResult(record.wireType, await dispatch(record.wireType, input ?? {})) + return toCallToolResult(wireType, await dispatch(wireType, input ?? {})) }, } liveTools.set(tool.name, signal) diff --git a/embed/test/bridge.test.ts b/embed/test/bridge.test.ts index 8de61194..ab91cb94 100644 --- a/embed/test/bridge.test.ts +++ b/embed/test/bridge.test.ts @@ -91,6 +91,24 @@ describe(attachEmbed.name, () => { await expect(promise).resolves.toEqual({ success: true, data: null }) }) + it('posts an empty documentation input when called without arguments', async () => { + const harness = makeHarness() + const pending = harness.embed.actions.getDocumentation() + expect(harness.posted.at(-1)).toMatchObject({ type: 'GET_DOCUMENTATION', data: {} }) + replyResult(harness, harness.lastRequestId(), { success: true, data: { kind: 'index', topics: [] } }) + expect(await pending).toEqual({ success: true, data: { kind: 'index', topics: [] } }) + }) + + it.each(['conflict:editor_modified', 'not_found:job', 'resource:session_limit'])( + 'preserves the build error %s', async (code) => { + const harness = makeHarness() + const pending = harness.embed.actions.buildPdf({ action: 'status', jobId: 'job' }) + const result = { success: false, error: { code, message: 'Build request rejected' } } + replyResult(harness, harness.lastRequestId(), result) + expect(await pending).toEqual(result) + } + ) + it('forwards a typed editor error and camelCases its details payload', async () => { const harness = makeHarness() const promise = harness.embed.actions.submit({ downloadCopy: false }) @@ -185,10 +203,13 @@ describe(attachEmbed.name, () => { vi.spyOn(harness.contentWindow, 'postMessage').mockImplementation(() => { throw new Error('dead window') }) - const result = await harness.embed.actions.getFields() - expect(result.success).toBe(false) - if (!result.success) { - expect(result.error.code).toBe('unexpected:unknown') + // A dead contentWindow is an injected browser failure, not reproducible through a live host. + for (const result of await Promise.all([ + harness.embed.actions.getFields(), + harness.embed.actions.buildPdf({ action: 'build', code: 'Valid source' }), + harness.embed.actions.getDocumentation(), + ])) { + expect(result).toMatchObject({ success: false, error: { code: 'unexpected:unknown' } }) } }) diff --git a/embed/test/helpers.ts b/embed/test/helpers.ts index 823ea02c..ecd54ed9 100644 --- a/embed/test/helpers.ts +++ b/embed/test/helpers.ts @@ -1,13 +1,16 @@ import { vi } from 'vitest' import type { BridgeResult, Embed, IframeActions } from '../src/types' -const okResult: BridgeResult = { success: true, data: null } +const result: BridgeResult = { success: false, error: { code: 'bad_request:invalid_input', message: 'Test action' } } // A fully-stubbed actions group: every editor operation is a vi.fn resolving to a -// success Result. Shared by the tools + adapter tests. +// failure Result. Shared by the tools + adapter tests. export const makeActionsStub = (): IframeActions => { - const method = (): Promise> => Promise.resolve(okResult) + const method = (): Promise> => Promise.resolve(result) return { + batchSetFieldValues: vi.fn(method), + buildPdf: vi.fn(method), + getDocumentation: vi.fn(method), createField: vi.fn(method), deleteFields: vi.fn(method), deletePages: vi.fn(method), diff --git a/embed/test/mount.test.ts b/embed/test/mount.test.ts index 33f76536..e4c06347 100644 --- a/embed/test/mount.test.ts +++ b/embed/test/mount.test.ts @@ -414,6 +414,6 @@ describe(createEmbed.name, () => { document.body.innerHTML = '
' const misspelled: unknown = { target: '#root', companyIdentifier: 'acme', webMCP: { enabled: true, exclude: ['sumbit'] } } // @ts-expect-error exercising the runtime guard for untyped JS callers - expect(() => createEmbed(misspelled)).toThrow(/webMCP\.exclude names no tool: sumbit \(known: batchSetFieldValues, createField/) + expect(() => createEmbed(misspelled)).toThrow(/webMCP\.exclude names no tool: sumbit \(known: buildPdf, getDocumentation, batchSetFieldValues, createField/) }) }) diff --git a/embed/test/tanstack-ai.test.ts b/embed/test/tanstack-ai.test.ts index 4f2658cc..d510ec9e 100644 --- a/embed/test/tanstack-ai.test.ts +++ b/embed/test/tanstack-ai.test.ts @@ -1,24 +1,28 @@ import { describe, expect, it } from 'vitest' +import { convertSchemaToJsonSchema } from '@tanstack/ai' import { createSimplePDFTools, simplePDFToolDefinitions } from '../src/tanstack-ai' import type { BridgeResult } from '../src/types' import { makeEmbedStub } from './helpers' describe('simplePDFToolDefinitions', () => { - it('returns the 16 agentic operations as execute-less definitions (loadDocument excluded)', () => { + it('returns the 18 agentic operations as execute-less definitions (loadDocument excluded)', () => { const definitions = simplePDFToolDefinitions() - expect(definitions).toHaveLength(16) + expect(definitions).toHaveLength(18) expect(definitions.map((definition) => definition.name)).not.toContain('loadDocument') for (const definition of definitions) { expect(typeof definition.description).toBe('string') expect(definition.inputSchema).toBeDefined() + const schema = convertSchemaToJsonSchema(definition.inputSchema) + expect(schema?.type).toBe('object') + expect(schema?.anyOf).toBeUndefined() } }) }) describe('createSimplePDFTools', () => { - it('produces a client tool for each of the 16 agentic operations', () => { + it('produces a client tool for each of the 18 agentic operations', () => { const tools = createSimplePDFTools({ embed: makeEmbedStub() }) - expect(tools).toHaveLength(16) + expect(tools).toHaveLength(18) expect(tools.every((tool) => typeof tool.execute === 'function')).toBe(true) }) diff --git a/embed/test/tools.test.ts b/embed/test/tools.test.ts index 955742bb..f8578a96 100644 --- a/embed/test/tools.test.ts +++ b/embed/test/tools.test.ts @@ -5,6 +5,8 @@ import { makeActionsStub } from './helpers' describe(isSimplePDFToolName.name, () => { it('accepts agentic tool names', () => { expect(isSimplePDFToolName('getFields')).toBe(true) + expect(isSimplePDFToolName('buildPdf')).toBe(true) + expect(isSimplePDFToolName('getDocumentation')).toBe(true) expect(isSimplePDFToolName('goTo')).toBe(true) expect(isSimplePDFToolName('createField')).toBe(true) }) @@ -17,9 +19,9 @@ describe(isSimplePDFToolName.name, () => { }) describe('SIMPLEPDF_TOOLS', () => { - it('exposes the 16 agentic operations with descriptions + input schemas (loadDocument excluded)', () => { + it('exposes the 18 agentic operations with descriptions + input schemas (loadDocument excluded)', () => { const names = Object.keys(SIMPLEPDF_TOOLS) - expect(names).toHaveLength(16) + expect(names).toHaveLength(18) expect(names).not.toContain('loadDocument') for (const definition of Object.values(SIMPLEPDF_TOOLS)) { expect(typeof definition.description).toBe('string') @@ -41,6 +43,40 @@ describe(routeToolCall.name, () => { expect(actions.goTo).toHaveBeenCalledWith({ page: 2 }) }) + it('routes build actions and the documentation index with camelCase inputs', async () => { + const actions = makeActionsStub() + await routeToolCall(actions, 'buildPdf', { + action: 'build', + code: 'Hello', + }) + expect(actions.buildPdf).toHaveBeenCalledWith({ + action: 'build', + code: 'Hello', + }) + await routeToolCall(actions, 'buildPdf', { action: 'status', jobId: 'job' }) + expect(actions.buildPdf).toHaveBeenCalledWith({ action: 'status', jobId: 'job' }) + await routeToolCall(actions, 'getDocumentation', undefined) + expect(actions.getDocumentation).toHaveBeenCalledWith({}) + }) + + // Reject unrecognized keys on each action and in nested assets before dispatch. + it.each([ + { action: 'build', code: 'Hello', idempotencyKey: 'removed' }, + { action: 'build', code: 'Hello', jobId: 'job' }, + { action: 'build', code: 'Hello', inspect: {} }, + { action: 'build', code: 'Hello', assets: [{ path: 'a.png', dataUrl: 'data', extra: true }] }, + { action: 'cancel', jobId: 'job', code: 'Hello' }, + { action: 'build' }, + ])('rejects invalid build input without losing fields: %j', async (input) => { + expect(SIMPLEPDF_TOOLS.buildPdf.inputSchema.safeParse(input).success).toBe(false) + const actions = makeActionsStub() + expect(await routeToolCall(actions, 'buildPdf', input)).toMatchObject({ + success: false, + error: { code: 'bad_request:invalid_input' }, + }) + expect(actions.buildPdf).not.toHaveBeenCalled() + }) + it('returns bad_request:invalid_input on schema-invalid input without dispatching', async () => { const actions = makeActionsStub() const result = await routeToolCall(actions, 'goTo', { page: 'not-a-number' }) diff --git a/embed/test/webmcp.test.ts b/embed/test/webmcp.test.ts index 50c97fef..2a9f17e4 100644 --- a/embed/test/webmcp.test.ts +++ b/embed/test/webmcp.test.ts @@ -2,7 +2,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest' import { attachEmbed, type AttachEmbedArgs } from '../src/bridge' import type { BridgeLogger } from '../src/logger' import type { Embed } from '../src/types' -import { METHOD_NAMES } from '../src/generated/method-names' +import { METHOD_NAMES } from '../src/generated/bridge-vocabulary' import { WEBMCP_TOOLS } from '../src/generated/webmcp-tools' const EDITOR_ORIGIN = 'https://tenant.simplepdf.com' @@ -235,6 +235,22 @@ describe('attachEmbed({ webMCP })', () => { expect(toolResult.content).toEqual([{ type: 'text', text: JSON.stringify({ success: true, data: null }) }]) }) + it('preserves raw WebMCP keys so the editor can reject misspelled build inputs', async () => { + const modelContext = installModelContext(document) + const harness = mountReady({ webMCP: { enabled: true } }) + await waitForTools(modelContext, TOOL_COUNT) + const input = { + action: 'status', job_id: 'wire-id', jobId: 'duplicate', + assets: [{ path: 'image.png', dataUrl: 'invalid' }], + } + const pending = findTool(modelContext, 'build_pdf').execute(input) + const request = await waitForRequest(harness, 'BUILD_PDF') + expect(request.data).toEqual(input) + const result = { success: false, error: { code: 'bad_request:invalid_value', message: 'Unknown input keys' } } + harness.reply(request, result) + expect(await pending).toEqual({ isError: true, content: [{ type: 'text', text: JSON.stringify(result) }] }) + }) + it('hands the agent the wire-shaped result its tool description promises (snake_case, not the SDK camelCase)', async () => { const modelContext = installModelContext(document) const harness = mountReady({ webMCP: { enabled: true } }) @@ -266,6 +282,26 @@ describe('attachEmbed({ webMCP })', () => { ]) }) + it('returns the first-page build preview as a native image alongside the job metadata', async () => { + const modelContext = installModelContext(document) + const harness = mountReady({ webMCP: { enabled: true } }) + await waitForTools(modelContext, TOOL_COUNT) + const pending = findTool(modelContext, 'build_pdf').execute({ action: 'status', job_id: 'job' }) + const request = await waitForRequest(harness, 'BUILD_PDF') + const page = { page: 1, image_width: 10, image_height: 12, badges: {} } + const job = { job_id: 'job', status: 'succeeded', page_count: 2, warnings: [] } + harness.reply(request, { + success: true, + data: { ...job, preview: { success: true, data: { ...page, image_data_url: 'data:image/png;base64,iVBORw0KGgo=' } } }, + }) + expect(await pending).toEqual({ + content: [ + { type: 'image', data: 'iVBORw0KGgo=', mimeType: 'image/png' }, + { type: 'text', text: JSON.stringify({ success: true, data: { ...job, preview: { success: true, data: page } } }) }, + ], + }) + }) + it('keeps the text envelope for a failed annotated page render', async () => { const modelContext = installModelContext(document) const harness = mountReady({ webMCP: { enabled: true } }) diff --git a/embed/tsup.config.ts b/embed/tsup.config.ts index d86ffe95..a8bb7ad1 100644 --- a/embed/tsup.config.ts +++ b/embed/tsup.config.ts @@ -18,6 +18,9 @@ export default defineConfig({ format: ['esm', 'cjs'], dts: true, treeshake: true, + minify: true, + keepNames: true, + sourcemap: true, splitting: true, clean: true, external: ['zod', '@tanstack/ai'], diff --git a/react/README.md b/react/README.md index cccdbf70..8fe609dd 100644 --- a/react/README.md +++ b/react/README.md @@ -158,7 +158,7 @@ Actions are camelCase (the editor's snake_case wire is transformed for you). `us | `actions.batchSetFieldValues({ updates })` | Set several fields at once (`updates: [{ fieldId, value }]`): all apply, or none do | | `actions.submit({ downloadCopy })` | Submit the document | -…plus `createField`, `getFields`, `getAnnotatedPage`, `focusField`, `movePage`, `rotatePage`, `deletePages`, `download`, and `loadDocument`. All actions return a `Promise` with a result object: `{ success: true, data: ... }` or `{ success: false, error: { code, message } }`. +See the [core action reference](../embed/README.md#actions) for `buildPdf`, `getDocumentation` and all input shapes. Other actions include `createField`, `getFields`, `getAnnotatedPage`, `focusField`, `movePage`, `rotatePage`, `deletePages`, `download`, and `loadDocument`. All actions return a `Promise` with a result object: `{ success: true, data: ... }` or `{ success: false, error: { code, message } }`. ```jsx import { EmbedPDF, useEmbed } from '@simplepdf/react-embed-pdf'; diff --git a/react/src/embed-pdf.tsx b/react/src/embed-pdf.tsx index f4ee7bac..065b8c6e 100644 --- a/react/src/embed-pdf.tsx +++ b/react/src/embed-pdf.tsx @@ -408,6 +408,8 @@ export const useEmbed = (): { const actions = React.useMemo( () => ({ + buildPdf: (input) => embedRef.current?.buildPdf(input) ?? notMounted(), + getDocumentation: (input) => embedRef.current?.getDocumentation(input) ?? notMounted(), batchSetFieldValues: (input) => embedRef.current?.batchSetFieldValues(input) ?? notMounted(), createField: (input) => embedRef.current?.createField(input) ?? notMounted(), deleteFields: (input) => embedRef.current?.deleteFields(input) ?? notMounted(), diff --git a/skills/build-with-simplepdf/SKILL.md b/skills/build-with-simplepdf/SKILL.md index f86c7a97..329fe1ac 100644 --- a/skills/build-with-simplepdf/SKILL.md +++ b/skills/build-with-simplepdf/SKILL.md @@ -137,9 +137,9 @@ export function ControlledEditor() { Typical operations: `getFields()`, `setFieldValue({ fieldId, value })`, `getDocumentContent({ extractionMode })`, `getAnnotatedPage({ page })`, `goTo({ page })`, `focusField({ fieldId })`, `selectTool({ tool })`, `detectFields()`, `deleteFields({ fieldIds?, page? })`, `submit({ downloadCopy })`. Verify the exact current method names and input shapes from the installed package/docs before coding. -Editor events arrive via the `onEmbedEvent` prop (React) or `embed.events` (core) — the outbound events are `EDITOR_READY`, `DOCUMENT_LOADED`, `PAGE_FOCUSED` and `SUBMISSION_SENT` (`submit()` itself resolves with `data: null`; the event carries the resulting ids). Wait for `DOCUMENT_LOADED` before operating on the document; until then actions other than `loadDocument()` fail with `bad_request:editor_not_ready` or `bad_request:no_document_loaded` (and `getFields()` may report an incomplete list) — handle or retry rather than racing mount. +Editor events arrive via the `onEmbedEvent` prop (React) or `embed.events` (core) — the outbound events are `EDITOR_READY`, `DOCUMENT_LOADED`, `PAGE_FOCUSED` and `SUBMISSION_SENT` (`submit()` itself resolves with `data: null`; the event carries the resulting ids). In an empty editor, call `loadDocument()`, `buildPdf()` or `getDocumentation()` without waiting for a document event. `EDITOR_READY` is only emitted in loading-placeholder mode; a normal blank editor does not emit it. Retry `bad_request:editor_not_ready` shortly. Wait for `DOCUMENT_LOADED` before document-dependent operations (and `getFields()` may report an incomplete list before then); handle `bad_request:no_document_loaded` rather than racing the load. -Browser agents (WebMCP): `webMCP: { enabled: true, exclude: ['submit'] }` on `createEmbed` / `` registers the editor's operations as tools on the host page (`simplepdf_embed_*`, the same records the editor registers on its own page; `exclude` takes SDK method names). Off by default; one WebMCP-enabled embed per page. +Browser agents (WebMCP): `webMCP: { enabled: true, exclude: ['submit'] }` on `createEmbed` / `` registers the editor's operations as tools on the host page (`build_pdf`, `get_documentation`, and the existing `simplepdf_embed_*` tools, the same records the editor registers on its own page; `exclude` takes SDK method names). Off by default; one WebMCP-enabled embed per page. When relevant (`AskUserQuestion`, header `Editor UI`):