Skip to content
Esc
↑↓navigate↵open⌘Jpreview
On this page

Migrate an App to the package contract

Move an App saved as module, ui, and styles strings onto the package contract, keep its data and URL, and know what changes for its code.

Apps are packages now: a package.json, a server.js, and optionally a ui.js, a styles.css, and the files they import, saved as one files map. An App saved before packages, as module, ui, and styles strings with an exported manifest, keeps running as it is and still accepts those fields on update. Nothing forces a migration. Migrate when you want npm dependencies, more than one file, or the same contract the docs describe.

A migration is one save: the App’s tree as files with migrate_contract: true. Each file is its text, or a field of the current source plus the edits that turn it into the file, so a large App migrates without resending its code; see Migrate without resending the source. The App’s id, URL, data, shares, Routines, Webhooks, secrets, and History stay. Its description comes from package.json from then on, and its connector approvals stay only for the tools package.json declares; see the map below. The App keeps serving its current revision while the package builds, and only a published build switches it over.

Before you start

Read the current source. Over MCP, get_app_source({ app_id }) returns source.module, source.ui, source.styles, and the revision you will send back as expected_revision. Over HTTP, GET /app/<id>/source with the user’s chrm_user_* bearer returns the same fields and an ETag to send as If-Match. From the CLI, charming apps source <id> --out <dir> writes module.js, ui.js, and styles.css to a directory. Keep that copy. An App with an undated manifest (manifest.$schema is not a dated app-manifest URL) migrates like any other, but History cannot restore any of its earlier revisions afterwards, so the copy is its only way back. A buildy: id in capabilities.imports migrates too: buildy:storage/[email protected] and charming:storage/[email protected] name the same module, and the package takes the charming: form.

Every file in the package except styles.css counts toward one 1024 KiB cap, including package.json and .json data, and styles.css has its own 256 KiB cap, so the code of any App saved before packages fits: its module and ui were 256 KiB each at most. See Limits.

Saves on the package contract need a signed-in user’s token and an idempotency key. An App-scoped chrm_app_* token from an anonymous create cannot migrate; pair the user’s account first.

Map the old shape onto files

Before After
manifest.id package.json → name, the package name. Keep the same value: it never changes after the App is created, and other Apps import it as charming:app/<name>@1.0. It is not the app_id Charming assigns, the URL slug that rename_app changes, or the title shown in the UI.
manifest.* read by server.js at runtime, such as manifest.id or manifest.version A package handler receives no manifest and no App metadata. The package name, package.json → name, never changes, so write it as a literal. The title and the URL slug can change, so neither is safe to hard-code. For values that change, such as a version, keep them in a JSON file beside server.js, for example meta.json holding { "version": "1.0.0" }, and import meta from './meta.json'. import ... from './package.json' is refused as invalid_module, so meta.json repeats the value and you update both together.
manifest.meta.name, manifest.meta.icon package.json → charming.name, charming.icon. charming.name is the title people see in the UI, and it defaults to name when omitted.
The App’s description package.json → description, up to 500 characters. A package sets the App’s description from this field alone. When the migration’s package.json has none, Charming writes the App’s current description into it; after that, a save that leaves it out clears the description that list_apps and search match.
manifest.$schema Dropped. package.json may carry "$schema": "https://charm.ing/schema/app-package/2026-10-25.json"; it is optional.
manifest.capabilities.imports: ['charming:storage/[email protected]'] import { kv } from 'charming:storage/[email protected]' at the top of server.js. Each capability becomes an import of the module that provides it.
manifest.permissions.browser["img-src"], ["frame-src"], ["connect-src"] package.json → charming.permissions.browser["img-src"], ["frame-src"], ["connect-src"]
manifest.permissions.server.fetch package.json → charming.permissions.server.fetch
env.connectors.call(service, tool, args) charming.permissions.server.connectors in package.json plus import { connectors } from 'charming:[email protected]'. Declare every service and tool the old module calls: the migration deletes approvals and owner sharing for any the declaration leaves out, people must approve them again, and a History restore does not bring them back.
env.storage kv from charming:storage/[email protected], same get, put, delete, list
env.assets assets from charming:storage/[email protected], same methods
env.log log from charming:logging/[email protected]
plain fetch with charming:network/[email protected] declared import { fetch } from 'charming:network/[email protected]'
env.fetch, declared or not Add import 'charming:secrets/[email protected]' to server.js: plain fetch is then the sealed fetch. The import is the declaration, and a package has no env.fetch whether or not the old manifest listed the capability. The origins it may reach go in charming.permissions.server.fetch, and {{secret:NAME}} placeholders work the same way. A route that also needs the network fetch imports both under different names, import { fetch } from 'charming:network/[email protected]' and import { fetch as sealedFetch } from 'charming:secrets/[email protected]', and calls sealedFetch for anything with a placeholder, because the global fetch stays direct when both are imported.
env.apps['<id>'].fetch(request) import { app } from 'charming:app/<id>@1.0' then app.fetch(request)
env.user Unchanged: read it from the handler’s { env } argument. A package App’s env holds env.user, plus env.secrets and env.connectors when it imports them; the handles in the rows above are gone from env and from the handler’s context.
export const routes = [...] Stays in server.js with the same route shapes, callers, annotations, and schemas, but Charming reads every route field except handler without running the module. Each value must be a literal, a top-level const, Object.keys() of a literal object, or a spread of a literal object or array. A call to any other function, such as a schema helper obj({ ... }), is refused as invalid_module with the route, the field, and the line, and so is a spread directly in a route object, such as { ...COMMON, op, handler }. For example, inputSchema: { ...BASE, properties: { stage: { enum: Object.keys(STAGES) } } } works when BASE and STAGES are top-level consts holding literal objects.
export default { fetch } Removed; a server.js with a default export is refused as invalid_module. A request that matches no route gets Charming’s 404, so a fetch that only answers 404 is deleted. A fetch that dispatches on the path, such as new URLPattern({ pathname: '/api/:op' }) or switch (url.pathname), becomes one route per branch: { op: 'getState', handler } answers POST /api/getState, and method: 'GET' makes it GET /api/getState. Set path only when a fixed URL must differ from /api/<op>, for example { op: 'list', method: 'GET', path: '/api/items' }, and keep it under /api/, the only prefix HTTP App API calls reach. A route matches its path exactly, with no parameters or wildcards, so a value that varied in the URL moves into the input: query parameters for GET (GET /api/file?name=report.txt), the JSON body otherwise.
ui (an inline classic script) ui.js, an ES module. Replace const api = window.charming.api('<id>'), or window.charming.api(window.charming._self.manifestId), with import { api, onStateChange } from 'charming:ui/[email protected]'. The imported api is already bound to the App, whose id is the package.json name, so no _self lookup remains; _self belongs to the bridge, not the author API. window.charming.onStateChange becomes the imported onStateChange. Everything else on window.charming (user, login, withUser, images, assets, openLink, viewer) is unchanged. Top-level declarations in a module are not globals, so a function that markup or another script calls by name stops resolving: assign it with window.render = render, or bind it in ui.js with addEventListener. Inline on*= handlers still run, because the App page’s CSP keeps 'unsafe-inline', but they can only call what is on window.
inlined IIFE library in ui, or a pinned CDN <script> "dependencies": { "<package>": "<range>" } in package.json and import ... from '<package>'; the build bundles it. The browser bundle makes no CDN request.
styles styles.css, unchanged.

kv, assets, log, and fetch carry the same semantics and limits as the bindings they replace. Call them inside a route handler, not at module initialization.

Two shapes have no package equivalent. charming:browser/* permission imports that the old capabilities.imports carried for camera, microphone, geolocation, clipboard reading, screen capture, and MIDI need no import at all: Charming finds those calls in ui.js at publish time. device-motion, ambient-light, and storage stay as side-effect imports in ui.js, for example import 'charming:browser/[email protected]'.

A worked migration

Before, as module and ui strings:

// module
export const manifest = {
  $schema: 'https://charm.ing/schema/app-manifest/2026-10-16.json',
  id: 'todo',
  meta: { name: 'Todo' },
  capabilities: { imports: ['charming:storage/[email protected]'] },
};
export const routes = [
  {
    op: 'list',
    method: 'GET',
    annotations: { readOnlyHint: true },
    handler: async (_input, { env }) => (await env.storage.get('todos')) ?? [],
  },
];
// ui
const api = window.charming.api('todo');
const root = document.getElementById('app');
async function render() {
  root.textContent = JSON.stringify(await api.list());
}
render();
window.charming.onStateChange(render);

After, as three files:

{
  "name": "todo",
  "version": "1.0.0",
  "description": "A todo list.",
  "type": "module",
  "dependencies": {},
  "charming": { "name": "Todo" }
}
// server.js
import { kv } from 'charming:storage/[email protected]';

export const routes = [
  {
    op: 'list',
    method: 'GET',
    annotations: { readOnlyHint: true },
    handler: async () => (await kv.get('todos')) ?? [],
  },
];
// ui.js
import { api, onStateChange } from 'charming:ui/[email protected]';

const root = document.getElementById('app');
async function render() {
  root.textContent = JSON.stringify(await api.list());
}
render();
onStateChange(render);

Save the migration

Every path sends the tree as files, migrate_contract: true, the desired-source revision, and a fresh idempotency key. Each file is its text, as below, or a field of the current source plus edits, as in the next section.

Over MCP:

update_app({
  app_id: "<uuid>",
  files: { "package.json": "...", "server.js": "...", "ui.js": "..." },
  migrate_contract: true,
  expected_revision: <revision from get_app_source>,
  idempotency_key: "todo-migrate-001"
})

Over HTTP, with the ETag from GET /app/<id>/source:

jq -n --rawfile p package.json --rawfile s server.js --rawfile u ui.js \
  '{files: {"package.json": $p, "server.js": $s, "ui.js": $u}, migrate_contract: true}' \
  | curl -sS -i -X PUT https://charm.ing/app/<id> \
      -H "Authorization: Bearer $TOKEN" -H 'If-Match: "<etag>"' \
      -H 'Content-Type: application/json' \
      -H 'Idempotency-Key: todo-migrate-001' -d @-

From the CLI, after charming auth login:

charming apps update <id> --files ./todo --migrate-contract --dry-run
charming apps update <id> --files ./todo --migrate-contract

The save returns an accepted build (HTTP 202 with buildId and statusUrl; the MCP result carries buildId). Poll get_app_build({ build_id }) or GET /api/v1/app-builds/<buildId> until state is published; from the CLI, charming builds wait <buildId> does this, or add --wait to the apps update --files command. The App keeps serving the old revision until then. A failed build names the error kind and, when available, the file, line, and column; the App is unchanged, so fix the file and save again with a fresh key.

A save without migrate_contract: true on an App that is still on the earlier contract is refused with contract_migration_required. A save with module on an App that has already migrated is refused with invalid_request over MCP and app_build_unsupported over HTTP: once migrated, every save is files or path edits.

Migrate without resending the source

A migration save can build a file from the App’s current source instead of carrying its text. Give the file as { from, edits }: from is "module", "ui", or "styles", and edits are exact find-and-replace operations, the same old_string, new_string, and replace_all fields update_app edits take. Charming reads that field at expected_revision (If-Match over HTTP), applies the edits in order, and saves the result as the file. Omit edits to copy the field as it is. Files you send as text, such as package.json, mix freely with derived ones.

This keeps a migration small. An App whose module is 270 KB migrates with a request of about 2 KB:

update_app({
  app_id: "<uuid>",
  expected_revision: 41,
  idempotency_key: "deal-desk-migrate-1",
  migrate_contract: true,
  files: {
    "package.json": "{\"name\":\"deal-desk\",\"description\":\"Prices and tracks open deals.\",\"charming\":{\"name\":\"Deal Desk\",\"permissions\":{\"server\":{\"fetch\":[\"https://api.crm.example\"]}}}}",
    "server.js": {
      from: "module",
      edits: [
        { old_string: "<the whole export const manifest = {...}; block>",
          new_string: "import { kv } from 'charming:storage/[email protected]';\nimport 'charming:secrets/[email protected]';\n" },
        { old_string: "env.storage.", new_string: "kv.", replace_all: true },
        { old_string: "env.fetch(", new_string: "fetch(", replace_all: true },
        { old_string: "export default { fetch: () => new Response('Not found', { status: 404 }) };\n", new_string: "" }
      ]
    },
    "ui.js": {
      from: "ui",
      edits: [
        { old_string: "const api = window.charming.api('deal-desk');",
          new_string: "import { api, onStateChange } from 'charming:ui/[email protected]';" },
        { old_string: "window.charming.onStateChange(", new_string: "onStateChange(", replace_all: true },
        { old_string: "function openDeal(id) {", new_string: "window.openDeal = openDeal;\nfunction openDeal(id) {" }
      ]
    },
    "styles.css": { from: "styles" }
  }
})

package.json keeps name equal to the old manifest.id. Over HTTP, send the same files object in the PUT /app/<id> body with migrate_contract: true, If-Match, and Idempotency-Key.

You never see the assembled files before the build, so the save checks for what a missed edit commonly leaves behind and refuses it as invalid_module with the file, the line, and the fix: a manifest export in server.js; a route handler that reads env.storage, env.assets, env.log, env.fetch, or env.apps, including through ctx.env or a destructured env; kv, assets, or log used without its import; and a {{secret:…}} placeholder when nothing imports charming:secrets/[email protected]. The save does not run the code, so it catches nothing else; read the result back with get_app_build({ build_id, include_source: true }) to check it.

Only a migration save takes from. create_app’s input schema refuses it, and POST /app, PATCH /app/<id>/source, and a save to an App already on the package contract refuse it with invalid_request; change a package App with edits that name a path. All the edits in one save count toward one cap of 100, and no edit may build a file past the 1024 KiB package budget.

Error kind Meaning What to do
old_string_not_found, old_string_not_unique An edit did not match the field once. The error carries path, from, and editIndex, plus nearby text or the matching lines. Read source again and fix that edit, or set replace_all: true.
bucket_unset from names a field the App has no source for, such as styles on an App without styles. Send the file’s text, or leave the file out.
invalid_bucket from is not module, ui, or styles. Use one of those three.
empty_edits edits is an empty array. Omit edits to copy the field unchanged.
edits_too_large The save has more than 100 edits in all, or one string is over 256 KiB. Send a file’s text instead of editing it.
payload_too_large An edit, usually a replace_all, or a copy would bring the files other than styles.css past 1024 KiB together. The error names the file. Replace fewer matches, a shorter string, or fewer copies.

PATCH /app/<id>/source reports invalid_bucket, bucket_unset, and empty_edits as invalid_request with the kind in detail_kind; PUT /app/<id> and update_app report the kind itself.

After the migration

  • get_app_source returns the tree as source.files; source.module, source.ui, and source.styles mirror server.js, ui.js, and styles.css in the structured result; the text result lists each file once.
  • Exact edits name a path (server.js, lib/text.js) instead of a bucket.
  • History lists the migration as a new revision, in App settings → History (charm.ing/<owner>/~/apps/<app>/settings/history) and at GET /api/v1/apps/{appId}/revisions. Restoring a revision from before it (POST /api/v1/apps/{appId}/revisions/{revision}/restore) is an explicit recovery action: Charming validates that source under its own contract and publishes it as a fresh revision, so the App goes back to the earlier contract. Connector approvals that source does not declare are removed. Only revisions on a dated app-manifest contract can be restored this way. An App with an undated manifest can still migrate, but it has no such revision, so for it the migration is one-way apart from re-creating it from the copy you kept. Source saves never roll a contract back on their own.
  • Copies of the App, including Template copies, carry the package tree.
  • charming dev <directory> builds and runs the package locally, so you can check it before you save it, and charming dev <directory> --check renders it headless and prints a JSON report of errors. The build needs node and npm on PATH and access to the npm registry; see the CLI guide.

Errors on the way

Error kind Meaning What to do
contract_migration_required The App is on the earlier contract and the save did not set migrate_contract: true. Resend with migrate_contract: true and the whole tree.
invalid_manifest_schema package.json is malformed or carries a refused key. Fix the named key.
manifest_id_immutable (409) package.json → name differs from the App’s id. Set name back to the old manifest.id; the id never changes. Change the title with charming.name, or the URL with rename_app.
invalid_module, invalid_ui server.js or ui.js failed admission: an undeclared package, a relative import to a file the tree lacks, a manifest or default export, a charming: import for the wrong target, or, in a migration, a route handler that still reads env.storage, env.assets, env.log, env.fetch, or env.apps. The error names the file, line, and column, and for an env read the import that replaces it.
invalid_files A file no entry imports, a lockfile, tsconfig.json, or a bad path. Remove the file or import it.
revision_mismatch The App changed since you read it. Read source again and resend with the new revision.
unauthorized, bearer_required The credential is anonymous, App-scoped, a render token, or a browser session. Use the user’s chrm_user_* token.
app_build_unavailable Charming cannot build packages right now. Retry later; the App keeps serving.

Was this page helpful?