Developers

Plugins

JavaScript plugins

A JavaScript plugin is Site Code packaged as a plugin — the manifest, code scopes, settings, migrations, dependencies, packing the .zip and testing

12 min readLast updated

View as Markdown

On this page

A JavaScript plugin ("runtime": "js") uses the same API as Site Code but runs as a separate unit: it has its own tables, settings, cookies, hooks and routes, and can only use the permissions the administrator approved. The official plugins are written this way (the sources are in plugins-official/ of the repository).

Package layout#

my-plugin/
├── manifest.json          (required — at the zip root)
├── README.md              (shown in the store — write Thai + English)
├── code/
│   ├── main.ts            (the entry file)
│   ├── lib.ts
│   └── index.d.ts         (optional: types for plugins that import it)
├── migrations/
│   └── 001_create_tables.ts
├── assets/                (publicly served css / js / images / fonts)
└── screenshots/           (images for the store page)

Files in code/ and migrations/ may be .ts .js .mjs .json .md, at most 200 files, 512 KB each, 2 MB in total; the whole package at most 30 MB.

manifest.json#

{
  "id": "event-booking",
  "name": "Event booking",
  "version": "1.0.0",
  "description": "จองที่นั่งอีเวนต์ / Event seat booking",
  "author": "Your name",
  "icon": "🎟",
  "category": "content",
  "license": "MIT",
  "minCore": "2.0.4",
  "runtime": "js",
  "permissions": ["code", "settings"],
  "settings": [
    { "key": "notifyEmail", "type": "text", "label": { "th": "อีเมลแจ้งเตือน", "en": "Notification email" } }
  ],
  "code": {
    "entry": "code/main.ts",
    "scopes": ["db", "routes", "mail", "admin-pages"],
    "routes": ["/booking"],
    "exports": ["seatsLeft"],
    "hooks": { "events": ["event-booking.booked"] }
  },
  "requires": { "thai": "^1.0.0" }
}
FieldNotes
id^[a-z0-9][a-z0-9-]{2,39}$, unique — the namespace for everything
versionsemver — every update must be higher
minCoreThe lowest Anasaki Studio version it installs on
permissionsMust include code and the permission of every feature used (settings, bodyEnd, webhooks…)
code.entryRequired; a .ts / .js / .mjs file in code/
code.scopesCode permissions — calling an API outside them throws
code.routesPublic path prefixes site.route / site.page may use (needs the routes scope) — a-z 0-9 _ -, and since CMS 2.2.2 dots too, e.g. /feed.xml
code.hostsDomains http.fetch may call (needs the http scope)
code.library / code.exportsA module other plugins can import / functions called with plugins.call
code.hooksNames of its own filters / events, starting with <id>.
requires / optionalRequiresPlugins it needs / works with when present (^1.2.0, ~1.2, 1.x, >=1.0.0 <2)
capabilitiesPlugin permissions administrators can tick per role (since 2.0.6) — see Plugin capabilities

Code scopes#

db · content · content-write · content-fields · post-types (since 2.0.5) · mail · http · webhooks · visitor · routes · jobs · admin-pages · filters-core · middleware · head-scripts — what each one means is in Plugin permissions. Ask only for what you use: administrators see every one before installing, and asking for more in a later version switches the plugin off until it is approved again.

Everything is namespaced#

ThingIn the event-booking plugin
Tablesschema.create('seats') → the real table p_event_booking_seats (the prefix is added/stripped for you)
Settingssite.settings('notifyEmail') reads Plugins → Settings first, then Site Code → Secrets & settings (for this plugin), then the manifest's default
Cookiesresponse.setCookie('cart', …) → the real name starts with pl_<id>_ — a plugin cannot see the system's or other plugins' cookies
Actions / collections/_a/event-booking:<name> · code:event-booking:<name>
Admin pages / jobsevent-booking:<name>
Its own hookssite.emit('event-booking.booked', …)

Plugins don't get db.query / schema.raw and cannot see other units' tables.

Plugin content types (since 2.0.5)#

Plugins with the post-types scope (and "minCore": "2.0.5") can call site.postType like Site Code:

site.postType('docs_doc', {
  label: { th: 'เอกสาร', en: 'Docs' }, icon: '📘',
  slug: 'docs',          // default = the id with _ turned into - (docs-doc)
  public: false,         // the system does not route /docs and /docs/<slug> — the plugin serves the pages
  fields: {
    product: { type: 'select', options: ['studio', 'store'] },
    order: 'number',
  },
});
  • The type id must be <plugin id with - turned into _>_<name> and still match ^[a-z][a-z0-9_]{1,19}$ (20 characters in all) — plugin docs → docs_doc ✔, just docs ✘, plugin event-booking → event_booking_seat ✔. If it is too long or the plugin id starts with a digit, activation fails with a message
  • public: false — the system makes no /<slug> archive and no /<slug>/<post-slug> pages (default true), but post links (post.url, the admin's "View" button) are still /<slug>/<post-slug>, so the plugin should handle that path itself (e.g. redirect). slug may match a prefix in the plugin's own code.routes, but must not clash with system paths, other plugins' paths or other types' slugs
  • Fields declared in the spec's fields are stored under their plain names (product, order) — usable in db.posts.list({ type: 'docs_doc', where: { 'meta.order': { gte: 1 } }, orderBy: 'meta.order' }) and returned as post.meta.product. A plugin's site.fields(type, …) still stores them as <id>.<key> (not filterable with where), so declare fields in the type's spec. Field specs (including select options) are fixed at registration — a settings change takes effect when the plugin reloads
  • Reading/writing the type's posts with db.posts needs the content / content-write scope as usual. Other units (Site Code, other plugins) can read them, but only the owning plugin can write
  • The type gets a menu and editor in the admin, appears in the designer's post list options and travels with site export/import — switching off or deleting the plugin keeps the posts (hidden) until it is activated again

The Plugin Store supports the post-types scope since Store 1.2.1 — plugins using it can be uploaded as usual.

Migrations#

// migrations/001_create_tables.ts
export default migration({
  up(schema) {
    schema.create('seats', (t) => {
      t.id();
      t.string('event_slug', 191).index();
      t.string('email', 191);
      t.timestamps();
    });
  },
  down(schema) { schema.drop('seats'); },
});

Needs the db scope — migrations run on activation and when an active plugin is upgraded. For changes that may lose data the administrator must tick the confirmation, and the table is backed up first.

Packing and testing#

  1. Type-check while writing: copy anasaki.d.ts (download it from the Site Code page or with anasaki-code types) into the folder
  2. Zip the folder (files at the zip root, or inside a single top folder)
    cd my-plugin && zip -r ../event-booking-1.0.0.zip .
  3. On a test site: Plugins → Upload .zip → approve the permissions → Activate — if the code doesn't build, the system reports file:line and the plugin stays off
  4. Read the plugin's logs under Site Code → Logs (or anasaki-code logs --unit event-booking)
  5. Fix, bump version and upload again — settings and data stay

Already have working Site Code? The Export as plugin button on the Site Code page makes a .zip from the published version, with a manifest.json that guesses the scopes, routes, exports and requires — check and fix it before sending it to the store.

Ready: Signing up and publishing plugins · a complete example: Plugin example · the whole API: Plugin API